codec.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. //
  66. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  67. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  68. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  69. // "6ba7b8109dad11d180b400c04fd430c8"
  70. //
  71. // ABNF for supported UUID text representation follows:
  72. //
  73. // uuid := canonical | hashlike | braced | urn
  74. // plain := canonical | hashlike
  75. // canonical := 4hexoct '-' 2hexoct '-' 2hexoct '-' 6hexoct
  76. // hashlike := 12hexoct
  77. // braced := '{' plain '}'
  78. // urn := URN ':' UUID-NID ':' plain
  79. // URN := 'urn'
  80. // UUID-NID := 'uuid'
  81. // 12hexoct := 6hexoct 6hexoct
  82. // 6hexoct := 4hexoct 2hexoct
  83. // 4hexoct := 2hexoct 2hexoct
  84. // 2hexoct := hexoct hexoct
  85. // hexoct := hexdig hexdig
  86. // hexdig := '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
  87. // 'a' | 'b' | 'c' | 'd' | 'e' | 'f' |
  88. // 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
  89. func (u *UUID) UnmarshalText(text []byte) (err error) {
  90. switch len(text) {
  91. case 32:
  92. return u.decodeHashLike(text)
  93. case 36:
  94. return u.decodeCanonical(text)
  95. case 38:
  96. return u.decodeBraced(text)
  97. case 41:
  98. fallthrough
  99. case 45:
  100. return u.decodeURN(text)
  101. default:
  102. return fmt.Errorf("uuid: incorrect UUID length: %s", text)
  103. }
  104. }
  105. // decodeCanonical decodes UUID string in format
  106. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8".
  107. func (u *UUID) decodeCanonical(t []byte) (err error) {
  108. if t[8] != '-' || t[13] != '-' || t[18] != '-' || t[23] != '-' {
  109. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  110. }
  111. src := t[:]
  112. dst := u[:]
  113. for i, byteGroup := range byteGroups {
  114. if i > 0 {
  115. src = src[1:] // skip dash
  116. }
  117. _, err = hex.Decode(dst[:byteGroup/2], src[:byteGroup])
  118. if err != nil {
  119. return
  120. }
  121. src = src[byteGroup:]
  122. dst = dst[byteGroup/2:]
  123. }
  124. return
  125. }
  126. // decodeHashLike decodes UUID string in format
  127. // "6ba7b8109dad11d180b400c04fd430c8".
  128. func (u *UUID) decodeHashLike(t []byte) (err error) {
  129. src := t[:]
  130. dst := u[:]
  131. if _, err = hex.Decode(dst, src); err != nil {
  132. return err
  133. }
  134. return
  135. }
  136. // decodeBraced decodes UUID string in format
  137. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" or in format
  138. // "{6ba7b8109dad11d180b400c04fd430c8}".
  139. func (u *UUID) decodeBraced(t []byte) (err error) {
  140. l := len(t)
  141. if t[0] != '{' || t[l-1] != '}' {
  142. return fmt.Errorf("uuid: incorrect UUID format %s", t)
  143. }
  144. return u.decodePlain(t[1 : l-1])
  145. }
  146. // decodeURN decodes UUID string in format
  147. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in format
  148. // "urn:uuid:6ba7b8109dad11d180b400c04fd430c8".
  149. func (u *UUID) decodeURN(t []byte) (err error) {
  150. total := len(t)
  151. urn_uuid_prefix := t[:9]
  152. if !bytes.Equal(urn_uuid_prefix, urnPrefix) {
  153. return fmt.Errorf("uuid: incorrect UUID format: %s", t)
  154. }
  155. return u.decodePlain(t[9:total])
  156. }
  157. // decodePlain decodes UUID string in canonical format
  158. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8" or in hash-like format
  159. // "6ba7b8109dad11d180b400c04fd430c8".
  160. func (u *UUID) decodePlain(t []byte) (err error) {
  161. switch len(t) {
  162. case 32:
  163. return u.decodeHashLike(t)
  164. case 36:
  165. return u.decodeCanonical(t)
  166. default:
  167. return fmt.Errorf("uuid: incorrrect UUID length: %s", t)
  168. }
  169. }
  170. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  171. func (u UUID) MarshalBinary() (data []byte, err error) {
  172. data = u.Bytes()
  173. return
  174. }
  175. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  176. // It will return error if the slice isn't 16 bytes long.
  177. func (u *UUID) UnmarshalBinary(data []byte) (err error) {
  178. if len(data) != Size {
  179. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  180. return
  181. }
  182. copy(u[:], data)
  183. return
  184. }