uuid.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright 2018 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package uuid
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "encoding/hex"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "strings"
  13. )
  14. // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
  15. // 4122.
  16. type UUID [16]byte
  17. // A Version represents a UUID's version.
  18. type Version byte
  19. // A Variant represents a UUID's variant.
  20. type Variant byte
  21. // Constants returned by Variant.
  22. const (
  23. Invalid = Variant(iota) // Invalid UUID
  24. RFC4122 // The variant specified in RFC4122
  25. Reserved // Reserved, NCS backward compatibility.
  26. Microsoft // Reserved, Microsoft Corporation backward compatibility.
  27. Future // Reserved for future definition.
  28. )
  29. var rander = rand.Reader // random function
  30. // Parse decodes s into a UUID or returns an error. Both the standard UUID
  31. // forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
  32. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
  33. // Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
  34. // encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
  35. func Parse(s string) (UUID, error) {
  36. var uuid UUID
  37. switch len(s) {
  38. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  39. case 36:
  40. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  41. case 36 + 9:
  42. if strings.ToLower(s[:9]) != "urn:uuid:" {
  43. return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
  44. }
  45. s = s[9:]
  46. // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  47. case 36 + 2:
  48. s = s[1:]
  49. // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  50. case 32:
  51. var ok bool
  52. for i := range uuid {
  53. uuid[i], ok = xtob(s[i*2], s[i*2+1])
  54. if !ok {
  55. return uuid, errors.New("invalid UUID format")
  56. }
  57. }
  58. return uuid, nil
  59. default:
  60. return uuid, fmt.Errorf("invalid UUID length: %d", len(s))
  61. }
  62. // s is now at least 36 bytes long
  63. // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  64. if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
  65. return uuid, errors.New("invalid UUID format")
  66. }
  67. for i, x := range [16]int{
  68. 0, 2, 4, 6,
  69. 9, 11,
  70. 14, 16,
  71. 19, 21,
  72. 24, 26, 28, 30, 32, 34} {
  73. v, ok := xtob(s[x], s[x+1])
  74. if !ok {
  75. return uuid, errors.New("invalid UUID format")
  76. }
  77. uuid[i] = v
  78. }
  79. return uuid, nil
  80. }
  81. // ParseBytes is like Parse, except it parses a byte slice instead of a string.
  82. func ParseBytes(b []byte) (UUID, error) {
  83. var uuid UUID
  84. switch len(b) {
  85. case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  86. case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  87. if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
  88. return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
  89. }
  90. b = b[9:]
  91. case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  92. b = b[1:]
  93. case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  94. var ok bool
  95. for i := 0; i < 32; i += 2 {
  96. uuid[i/2], ok = xtob(b[i], b[i+1])
  97. if !ok {
  98. return uuid, errors.New("invalid UUID format")
  99. }
  100. }
  101. return uuid, nil
  102. default:
  103. return uuid, fmt.Errorf("invalid UUID length: %d", len(b))
  104. }
  105. // s is now at least 36 bytes long
  106. // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  107. if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
  108. return uuid, errors.New("invalid UUID format")
  109. }
  110. for i, x := range [16]int{
  111. 0, 2, 4, 6,
  112. 9, 11,
  113. 14, 16,
  114. 19, 21,
  115. 24, 26, 28, 30, 32, 34} {
  116. v, ok := xtob(b[x], b[x+1])
  117. if !ok {
  118. return uuid, errors.New("invalid UUID format")
  119. }
  120. uuid[i] = v
  121. }
  122. return uuid, nil
  123. }
  124. // MustParse is like Parse but panics if the string cannot be parsed.
  125. // It simplifies safe initialization of global variables holding compiled UUIDs.
  126. func MustParse(s string) UUID {
  127. uuid, err := Parse(s)
  128. if err != nil {
  129. panic(`uuid: Parse(` + s + `): ` + err.Error())
  130. }
  131. return uuid
  132. }
  133. // FromBytes creates a new UUID from a byte slice. Returns an error if the slice
  134. // does not have a length of 16. The bytes are copied from the slice.
  135. func FromBytes(b []byte) (uuid UUID, err error) {
  136. err = uuid.UnmarshalBinary(b)
  137. return uuid, err
  138. }
  139. // Must returns uuid if err is nil and panics otherwise.
  140. func Must(uuid UUID, err error) UUID {
  141. if err != nil {
  142. panic(err)
  143. }
  144. return uuid
  145. }
  146. // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  147. // , or "" if uuid is invalid.
  148. func (uuid UUID) String() string {
  149. var buf [36]byte
  150. encodeHex(buf[:], uuid)
  151. return string(buf[:])
  152. }
  153. // URN returns the RFC 2141 URN form of uuid,
  154. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
  155. func (uuid UUID) URN() string {
  156. var buf [36 + 9]byte
  157. copy(buf[:], "urn:uuid:")
  158. encodeHex(buf[9:], uuid)
  159. return string(buf[:])
  160. }
  161. func encodeHex(dst []byte, uuid UUID) {
  162. hex.Encode(dst, uuid[:4])
  163. dst[8] = '-'
  164. hex.Encode(dst[9:13], uuid[4:6])
  165. dst[13] = '-'
  166. hex.Encode(dst[14:18], uuid[6:8])
  167. dst[18] = '-'
  168. hex.Encode(dst[19:23], uuid[8:10])
  169. dst[23] = '-'
  170. hex.Encode(dst[24:], uuid[10:])
  171. }
  172. // Variant returns the variant encoded in uuid.
  173. func (uuid UUID) Variant() Variant {
  174. switch {
  175. case (uuid[8] & 0xc0) == 0x80:
  176. return RFC4122
  177. case (uuid[8] & 0xe0) == 0xc0:
  178. return Microsoft
  179. case (uuid[8] & 0xe0) == 0xe0:
  180. return Future
  181. default:
  182. return Reserved
  183. }
  184. }
  185. // Version returns the version of uuid.
  186. func (uuid UUID) Version() Version {
  187. return Version(uuid[6] >> 4)
  188. }
  189. func (v Version) String() string {
  190. if v > 15 {
  191. return fmt.Sprintf("BAD_VERSION_%d", v)
  192. }
  193. return fmt.Sprintf("VERSION_%d", v)
  194. }
  195. func (v Variant) String() string {
  196. switch v {
  197. case RFC4122:
  198. return "RFC4122"
  199. case Reserved:
  200. return "Reserved"
  201. case Microsoft:
  202. return "Microsoft"
  203. case Future:
  204. return "Future"
  205. case Invalid:
  206. return "Invalid"
  207. }
  208. return fmt.Sprintf("BadVariant%d", int(v))
  209. }
  210. // SetRand sets the random number generator to r, which implements io.Reader.
  211. // If r.Read returns an error when the package requests random data then
  212. // a panic will be issued.
  213. //
  214. // Calling SetRand with nil sets the random number generator to the default
  215. // generator.
  216. func SetRand(r io.Reader) {
  217. if r == nil {
  218. rander = rand.Reader
  219. return
  220. }
  221. rander = r
  222. }