uuid.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. "sync"
  14. )
  15. // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
  16. // 4122.
  17. type UUID [16]byte
  18. // A Version represents a UUID's version.
  19. type Version byte
  20. // A Variant represents a UUID's variant.
  21. type Variant byte
  22. // Constants returned by Variant.
  23. const (
  24. Invalid = Variant(iota) // Invalid UUID
  25. RFC4122 // The variant specified in RFC4122
  26. Reserved // Reserved, NCS backward compatibility.
  27. Microsoft // Reserved, Microsoft Corporation backward compatibility.
  28. Future // Reserved for future definition.
  29. )
  30. const randPoolSize = 16 * 16
  31. var (
  32. rander = rand.Reader // random function
  33. poolEnabled = false
  34. poolMu sync.Mutex
  35. poolPos = randPoolSize // protected with poolMu
  36. pool [randPoolSize]byte // protected with poolMu
  37. )
  38. type invalidLengthError struct{ len int }
  39. func (err invalidLengthError) Error() string {
  40. return fmt.Sprintf("invalid UUID length: %d", err.len)
  41. }
  42. // IsInvalidLengthError is matcher function for custom error invalidLengthError
  43. func IsInvalidLengthError(err error) bool {
  44. _, ok := err.(invalidLengthError)
  45. return ok
  46. }
  47. // Parse decodes s into a UUID or returns an error. Both the standard UUID
  48. // forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
  49. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
  50. // Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
  51. // encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
  52. func Parse(s string) (UUID, error) {
  53. var uuid UUID
  54. switch len(s) {
  55. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  56. case 36:
  57. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  58. case 36 + 9:
  59. if strings.ToLower(s[:9]) != "urn:uuid:" {
  60. return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
  61. }
  62. s = s[9:]
  63. // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  64. case 36 + 2:
  65. s = s[1:]
  66. // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  67. case 32:
  68. var ok bool
  69. for i := range uuid {
  70. uuid[i], ok = xtob(s[i*2], s[i*2+1])
  71. if !ok {
  72. return uuid, errors.New("invalid UUID format")
  73. }
  74. }
  75. return uuid, nil
  76. default:
  77. return uuid, invalidLengthError{len(s)}
  78. }
  79. // s is now at least 36 bytes long
  80. // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  81. if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
  82. return uuid, errors.New("invalid UUID format")
  83. }
  84. for i, x := range [16]int{
  85. 0, 2, 4, 6,
  86. 9, 11,
  87. 14, 16,
  88. 19, 21,
  89. 24, 26, 28, 30, 32, 34} {
  90. v, ok := xtob(s[x], s[x+1])
  91. if !ok {
  92. return uuid, errors.New("invalid UUID format")
  93. }
  94. uuid[i] = v
  95. }
  96. return uuid, nil
  97. }
  98. // ParseBytes is like Parse, except it parses a byte slice instead of a string.
  99. func ParseBytes(b []byte) (UUID, error) {
  100. var uuid UUID
  101. switch len(b) {
  102. case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  103. case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  104. if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
  105. return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
  106. }
  107. b = b[9:]
  108. case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  109. b = b[1:]
  110. case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  111. var ok bool
  112. for i := 0; i < 32; i += 2 {
  113. uuid[i/2], ok = xtob(b[i], b[i+1])
  114. if !ok {
  115. return uuid, errors.New("invalid UUID format")
  116. }
  117. }
  118. return uuid, nil
  119. default:
  120. return uuid, invalidLengthError{len(b)}
  121. }
  122. // s is now at least 36 bytes long
  123. // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  124. if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
  125. return uuid, errors.New("invalid UUID format")
  126. }
  127. for i, x := range [16]int{
  128. 0, 2, 4, 6,
  129. 9, 11,
  130. 14, 16,
  131. 19, 21,
  132. 24, 26, 28, 30, 32, 34} {
  133. v, ok := xtob(b[x], b[x+1])
  134. if !ok {
  135. return uuid, errors.New("invalid UUID format")
  136. }
  137. uuid[i] = v
  138. }
  139. return uuid, nil
  140. }
  141. // MustParse is like Parse but panics if the string cannot be parsed.
  142. // It simplifies safe initialization of global variables holding compiled UUIDs.
  143. func MustParse(s string) UUID {
  144. uuid, err := Parse(s)
  145. if err != nil {
  146. panic(`uuid: Parse(` + s + `): ` + err.Error())
  147. }
  148. return uuid
  149. }
  150. // FromBytes creates a new UUID from a byte slice. Returns an error if the slice
  151. // does not have a length of 16. The bytes are copied from the slice.
  152. func FromBytes(b []byte) (uuid UUID, err error) {
  153. err = uuid.UnmarshalBinary(b)
  154. return uuid, err
  155. }
  156. // Must returns uuid if err is nil and panics otherwise.
  157. func Must(uuid UUID, err error) UUID {
  158. if err != nil {
  159. panic(err)
  160. }
  161. return uuid
  162. }
  163. // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  164. // , or "" if uuid is invalid.
  165. func (uuid UUID) String() string {
  166. var buf [36]byte
  167. encodeHex(buf[:], uuid)
  168. return string(buf[:])
  169. }
  170. // URN returns the RFC 2141 URN form of uuid,
  171. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
  172. func (uuid UUID) URN() string {
  173. var buf [36 + 9]byte
  174. copy(buf[:], "urn:uuid:")
  175. encodeHex(buf[9:], uuid)
  176. return string(buf[:])
  177. }
  178. func encodeHex(dst []byte, uuid UUID) {
  179. hex.Encode(dst, uuid[:4])
  180. dst[8] = '-'
  181. hex.Encode(dst[9:13], uuid[4:6])
  182. dst[13] = '-'
  183. hex.Encode(dst[14:18], uuid[6:8])
  184. dst[18] = '-'
  185. hex.Encode(dst[19:23], uuid[8:10])
  186. dst[23] = '-'
  187. hex.Encode(dst[24:], uuid[10:])
  188. }
  189. // Variant returns the variant encoded in uuid.
  190. func (uuid UUID) Variant() Variant {
  191. switch {
  192. case (uuid[8] & 0xc0) == 0x80:
  193. return RFC4122
  194. case (uuid[8] & 0xe0) == 0xc0:
  195. return Microsoft
  196. case (uuid[8] & 0xe0) == 0xe0:
  197. return Future
  198. default:
  199. return Reserved
  200. }
  201. }
  202. // Version returns the version of uuid.
  203. func (uuid UUID) Version() Version {
  204. return Version(uuid[6] >> 4)
  205. }
  206. func (v Version) String() string {
  207. if v > 15 {
  208. return fmt.Sprintf("BAD_VERSION_%d", v)
  209. }
  210. return fmt.Sprintf("VERSION_%d", v)
  211. }
  212. func (v Variant) String() string {
  213. switch v {
  214. case RFC4122:
  215. return "RFC4122"
  216. case Reserved:
  217. return "Reserved"
  218. case Microsoft:
  219. return "Microsoft"
  220. case Future:
  221. return "Future"
  222. case Invalid:
  223. return "Invalid"
  224. }
  225. return fmt.Sprintf("BadVariant%d", int(v))
  226. }
  227. // SetRand sets the random number generator to r, which implements io.Reader.
  228. // If r.Read returns an error when the package requests random data then
  229. // a panic will be issued.
  230. //
  231. // Calling SetRand with nil sets the random number generator to the default
  232. // generator.
  233. func SetRand(r io.Reader) {
  234. if r == nil {
  235. rander = rand.Reader
  236. return
  237. }
  238. rander = r
  239. }
  240. // EnableRandPool enables internal randomness pool used for Random
  241. // (Version 4) UUID generation. The pool contains random bytes read from
  242. // the random number generator on demand in batches. Enabling the pool
  243. // may improve the UUID generation throughput significantly.
  244. //
  245. // Since the pool is stored on the Go heap, this feature may be a bad fit
  246. // for security sensitive applications.
  247. //
  248. // Both EnableRandPool and DisableRandPool are not thread-safe and should
  249. // only be called when there is no possibility that New or any other
  250. // UUID Version 4 generation function will be called concurrently.
  251. func EnableRandPool() {
  252. poolEnabled = true
  253. }
  254. // DisableRandPool disables the randomness pool if it was previously
  255. // enabled with EnableRandPool.
  256. //
  257. // Both EnableRandPool and DisableRandPool are not thread-safe and should
  258. // only be called when there is no possibility that New or any other
  259. // UUID Version 4 generation function will be called concurrently.
  260. func DisableRandPool() {
  261. poolEnabled = false
  262. defer poolMu.Unlock()
  263. poolMu.Lock()
  264. poolPos = randPoolSize
  265. }