codec.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 a UUID generated from the raw byte slice input.
  28. // It will return an error if the slice isn't 16 bytes long.
  29. func FromBytes(input []byte) (UUID, error) {
  30. u := UUID{}
  31. err := u.UnmarshalBinary(input)
  32. return u, err
  33. }
  34. // FromBytesOrNil returns a UUID generated from the raw byte slice input.
  35. // Same behavior as FromBytes(), but returns uuid.Nil instead of an error.
  36. func FromBytesOrNil(input []byte) UUID {
  37. uuid, err := FromBytes(input)
  38. if err != nil {
  39. return Nil
  40. }
  41. return uuid
  42. }
  43. // FromString returns a UUID parsed from the input string.
  44. // Input is expected in a form accepted by UnmarshalText.
  45. func FromString(input string) (UUID, error) {
  46. u := UUID{}
  47. err := u.UnmarshalText([]byte(input))
  48. return u, err
  49. }
  50. // FromStringOrNil returns a UUID parsed from the input string.
  51. // Same behavior as FromString(), but returns uuid.Nil instead of an error.
  52. func FromStringOrNil(input string) UUID {
  53. uuid, err := FromString(input)
  54. if err != nil {
  55. return Nil
  56. }
  57. return uuid
  58. }
  59. // MarshalText implements the encoding.TextMarshaler interface.
  60. // The encoding is the same as returned by the String() method.
  61. func (u UUID) MarshalText() ([]byte, error) {
  62. return []byte(u.String()), nil
  63. }
  64. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  65. // Following formats are supported:
  66. //
  67. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  68. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  69. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  70. // "6ba7b8109dad11d180b400c04fd430c8"
  71. // "{6ba7b8109dad11d180b400c04fd430c8}",
  72. // "urn:uuid:6ba7b8109dad11d180b400c04fd430c8"
  73. //
  74. // ABNF for supported UUID text representation follows:
  75. //
  76. // URN := 'urn'
  77. // UUID-NID := 'uuid'
  78. //
  79. // hexdig := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
  80. // 'a' | 'b' | 'c' | 'd' | 'e' | 'f' |
  81. // 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
  82. //
  83. // hexoct := hexdig hexdig
  84. // 2hexoct := hexoct hexoct
  85. // 4hexoct := 2hexoct 2hexoct
  86. // 6hexoct := 4hexoct 2hexoct
  87. // 12hexoct := 6hexoct 6hexoct
  88. //
  89. // hashlike := 12hexoct
  90. // canonical := 4hexoct '-' 2hexoct '-' 2hexoct '-' 6hexoct
  91. //
  92. // plain := canonical | hashlike
  93. // uuid := canonical | hashlike | braced | urn
  94. //
  95. // braced := '{' plain '}' | '{' hashlike '}'
  96. // urn := URN ':' UUID-NID ':' plain
  97. //
  98. func (u *UUID) UnmarshalText(text []byte) error {
  99. switch len(text) {
  100. case 32:
  101. return u.decodeHashLike(text)
  102. case 34, 38:
  103. return u.decodeBraced(text)
  104. case 36:
  105. return u.decodeCanonical(text)
  106. case 41, 45:
  107. return u.decodeURN(text)
  108. default:
  109. return fmt.Errorf("uuid: incorrect UUID length: %s", text)
  110. }
  111. }
  112. // decodeCanonical decodes UUID strings that are formatted as defined in RFC-4122 (section 3):
  113. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8".
  114. func (u *UUID) decodeCanonical(t []byte) error {
  115. if t[8] != '-' || t[13] != '-' || t[18] != '-' || t[23] != '-' {
  116. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  117. }
  118. src := t
  119. dst := u[:]
  120. for i, byteGroup := range byteGroups {
  121. if i > 0 {
  122. src = src[1:] // skip dash
  123. }
  124. _, err := hex.Decode(dst[:byteGroup/2], src[:byteGroup])
  125. if err != nil {
  126. return err
  127. }
  128. src = src[byteGroup:]
  129. dst = dst[byteGroup/2:]
  130. }
  131. return nil
  132. }
  133. // decodeHashLike decodes UUID strings that are using the following format:
  134. // "6ba7b8109dad11d180b400c04fd430c8".
  135. func (u *UUID) decodeHashLike(t []byte) error {
  136. src := t[:]
  137. dst := u[:]
  138. _, err := hex.Decode(dst, src)
  139. return err
  140. }
  141. // decodeBraced decodes UUID strings that are using the following formats:
  142. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}"
  143. // "{6ba7b8109dad11d180b400c04fd430c8}".
  144. func (u *UUID) decodeBraced(t []byte) error {
  145. l := len(t)
  146. if t[0] != '{' || t[l-1] != '}' {
  147. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  148. }
  149. return u.decodePlain(t[1 : l-1])
  150. }
  151. // decodeURN decodes UUID strings that are using the following formats:
  152. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  153. // "urn:uuid:6ba7b8109dad11d180b400c04fd430c8".
  154. func (u *UUID) decodeURN(t []byte) error {
  155. total := len(t)
  156. urnUUIDPrefix := t[:9]
  157. if !bytes.Equal(urnUUIDPrefix, urnPrefix) {
  158. return fmt.Errorf("uuid: incorrect UUID format: %s", t)
  159. }
  160. return u.decodePlain(t[9:total])
  161. }
  162. // decodePlain decodes UUID strings that are using the following formats:
  163. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in hash-like format
  164. // "6ba7b8109dad11d180b400c04fd430c8".
  165. func (u *UUID) decodePlain(t []byte) error {
  166. switch len(t) {
  167. case 32:
  168. return u.decodeHashLike(t)
  169. case 36:
  170. return u.decodeCanonical(t)
  171. default:
  172. return fmt.Errorf("uuid: incorrect UUID length: %s", t)
  173. }
  174. }
  175. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  176. func (u UUID) MarshalBinary() ([]byte, error) {
  177. return u.Bytes(), nil
  178. }
  179. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  180. // It will return an error if the slice isn't 16 bytes long.
  181. func (u *UUID) UnmarshalBinary(data []byte) error {
  182. if len(data) != Size {
  183. return fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  184. }
  185. copy(u[:], data)
  186. return nil
  187. }