You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

206 lines
5.9 KiB

  1. // Copyright (C) 2013-2018 by Maxim Bublis <b@codemonkey.ru>
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to
  8. // permit persons to whom the Software is furnished to do so, subject to
  9. // the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be
  12. // included in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. package uuid
  22. import (
  23. "bytes"
  24. "encoding/hex"
  25. "fmt"
  26. )
  27. // FromBytes returns UUID converted from raw byte slice input.
  28. // It will return error if the slice isn't 16 bytes long.
  29. func FromBytes(input []byte) (u UUID, err error) {
  30. err = u.UnmarshalBinary(input)
  31. return
  32. }
  33. // FromBytesOrNil returns UUID converted from raw byte slice input.
  34. // Same behavior as FromBytes, but returns a Nil UUID on error.
  35. func FromBytesOrNil(input []byte) UUID {
  36. uuid, err := FromBytes(input)
  37. if err != nil {
  38. return Nil
  39. }
  40. return uuid
  41. }
  42. // FromString returns UUID parsed from string input.
  43. // Input is expected in a form accepted by UnmarshalText.
  44. func FromString(input string) (u UUID, err error) {
  45. err = u.UnmarshalText([]byte(input))
  46. return
  47. }
  48. // FromStringOrNil returns UUID parsed from string input.
  49. // Same behavior as FromString, but returns a Nil UUID on error.
  50. func FromStringOrNil(input string) UUID {
  51. uuid, err := FromString(input)
  52. if err != nil {
  53. return Nil
  54. }
  55. return uuid
  56. }
  57. // MarshalText implements the encoding.TextMarshaler interface.
  58. // The encoding is the same as returned by String.
  59. func (u UUID) MarshalText() (text []byte, err error) {
  60. text = []byte(u.String())
  61. return
  62. }
  63. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  64. // Following formats are supported:
  65. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  66. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  67. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  68. // "6ba7b8109dad11d180b400c04fd430c8"
  69. // ABNF for supported UUID text representation follows:
  70. // uuid := canonical | hashlike | braced | urn
  71. // plain := canonical | hashlike
  72. // canonical := 4hexoct '-' 2hexoct '-' 2hexoct '-' 6hexoct
  73. // hashlike := 12hexoct
  74. // braced := '{' plain '}'
  75. // urn := URN ':' UUID-NID ':' plain
  76. // URN := 'urn'
  77. // UUID-NID := 'uuid'
  78. // 12hexoct := 6hexoct 6hexoct
  79. // 6hexoct := 4hexoct 2hexoct
  80. // 4hexoct := 2hexoct 2hexoct
  81. // 2hexoct := hexoct hexoct
  82. // hexoct := hexdig hexdig
  83. // hexdig := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
  84. // 'a' | 'b' | 'c' | 'd' | 'e' | 'f' |
  85. // 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
  86. func (u *UUID) UnmarshalText(text []byte) (err error) {
  87. switch len(text) {
  88. case 32:
  89. return u.decodeHashLike(text)
  90. case 36:
  91. return u.decodeCanonical(text)
  92. case 38:
  93. return u.decodeBraced(text)
  94. case 41:
  95. fallthrough
  96. case 45:
  97. return u.decodeURN(text)
  98. default:
  99. return fmt.Errorf("uuid: incorrect UUID length: %s", text)
  100. }
  101. }
  102. // decodeCanonical decodes UUID string in format
  103. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8".
  104. func (u *UUID) decodeCanonical(t []byte) (err error) {
  105. if t[8] != '-' || t[13] != '-' || t[18] != '-' || t[23] != '-' {
  106. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  107. }
  108. src := t[:]
  109. dst := u[:]
  110. for i, byteGroup := range byteGroups {
  111. if i > 0 {
  112. src = src[1:] // skip dash
  113. }
  114. _, err = hex.Decode(dst[:byteGroup/2], src[:byteGroup])
  115. if err != nil {
  116. return
  117. }
  118. src = src[byteGroup:]
  119. dst = dst[byteGroup/2:]
  120. }
  121. return
  122. }
  123. // decodeHashLike decodes UUID string in format
  124. // "6ba7b8109dad11d180b400c04fd430c8".
  125. func (u *UUID) decodeHashLike(t []byte) (err error) {
  126. src := t[:]
  127. dst := u[:]
  128. if _, err = hex.Decode(dst, src); err != nil {
  129. return err
  130. }
  131. return
  132. }
  133. // decodeBraced decodes UUID string in format
  134. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" or in format
  135. // "{6ba7b8109dad11d180b400c04fd430c8}".
  136. func (u *UUID) decodeBraced(t []byte) (err error) {
  137. l := len(t)
  138. if t[0] != '{' || t[l-1] != '}' {
  139. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  140. }
  141. return u.decodePlain(t[1 : l-1])
  142. }
  143. // decodeURN decodes UUID string in format
  144. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in format
  145. // "urn:uuid:6ba7b8109dad11d180b400c04fd430c8".
  146. func (u *UUID) decodeURN(t []byte) (err error) {
  147. total := len(t)
  148. urn_uuid_prefix := t[:9]
  149. if !bytes.Equal(urn_uuid_prefix, urnPrefix) {
  150. return fmt.Errorf("uuid: incorrect UUID format: %s", t)
  151. }
  152. return u.decodePlain(t[9:total])
  153. }
  154. // decodePlain decodes UUID string in canonical format
  155. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in hash-like format
  156. // "6ba7b8109dad11d180b400c04fd430c8".
  157. func (u *UUID) decodePlain(t []byte) (err error) {
  158. switch len(t) {
  159. case 32:
  160. return u.decodeHashLike(t)
  161. case 36:
  162. return u.decodeCanonical(t)
  163. default:
  164. return fmt.Errorf("uuid: incorrrect UUID length: %s", t)
  165. }
  166. }
  167. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  168. func (u UUID) MarshalBinary() (data []byte, err error) {
  169. data = u.Bytes()
  170. return
  171. }
  172. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  173. // It will return error if the slice isn't 16 bytes long.
  174. func (u *UUID) UnmarshalBinary(data []byte) (err error) {
  175. if len(data) != Size {
  176. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  177. return
  178. }
  179. copy(u[:], data)
  180. return
  181. }