uuid.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Copyright 2016 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 UUID form of
  31. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
  32. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.
  33. func Parse(s string) (UUID, error) {
  34. var uuid UUID
  35. if len(s) != 36 {
  36. if len(s) != 36+9 {
  37. return uuid, fmt.Errorf("invalid UUID length: %d", len(s))
  38. }
  39. if strings.ToLower(s[:9]) != "urn:uuid:" {
  40. return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
  41. }
  42. s = s[9:]
  43. }
  44. if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
  45. return uuid, errors.New("invalid UUID format")
  46. }
  47. for i, x := range [16]int{
  48. 0, 2, 4, 6,
  49. 9, 11,
  50. 14, 16,
  51. 19, 21,
  52. 24, 26, 28, 30, 32, 34} {
  53. v, ok := xtob(s[x], s[x+1])
  54. if !ok {
  55. return uuid, errors.New("invalid UUID format")
  56. }
  57. uuid[i] = v
  58. }
  59. return uuid, nil
  60. }
  61. // ParseBytes is like Parse, except it parses a byte slice instead of a string.
  62. func ParseBytes(b []byte) (UUID, error) {
  63. var uuid UUID
  64. if len(b) != 36 {
  65. if len(b) != 36+9 {
  66. return uuid, fmt.Errorf("invalid UUID length: %d", len(b))
  67. }
  68. if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
  69. return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
  70. }
  71. b = b[9:]
  72. }
  73. if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
  74. return uuid, errors.New("invalid UUID format")
  75. }
  76. for i, x := range [16]int{
  77. 0, 2, 4, 6,
  78. 9, 11,
  79. 14, 16,
  80. 19, 21,
  81. 24, 26, 28, 30, 32, 34} {
  82. v, ok := xtob(b[x], b[x+1])
  83. if !ok {
  84. return uuid, errors.New("invalid UUID format")
  85. }
  86. uuid[i] = v
  87. }
  88. return uuid, nil
  89. }
  90. // FromBytes creates a new UUID from a byte slice. Returns an error if the slice
  91. // does not have a length of 16. The bytes are copied from the slice.
  92. func FromBytes(b []byte) (uuid UUID, err error) {
  93. err = uuid.UnmarshalBinary(b)
  94. return uuid, err
  95. }
  96. // Must returns uuid if err is nil and panics otherwise.
  97. func Must(uuid UUID, err error) UUID {
  98. if err != nil {
  99. panic(err)
  100. }
  101. return uuid
  102. }
  103. // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  104. // , or "" if uuid is invalid.
  105. func (uuid UUID) String() string {
  106. var buf [36]byte
  107. encodeHex(buf[:], uuid)
  108. return string(buf[:])
  109. }
  110. // URN returns the RFC 2141 URN form of uuid,
  111. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
  112. func (uuid UUID) URN() string {
  113. var buf [36 + 9]byte
  114. copy(buf[:], "urn:uuid:")
  115. encodeHex(buf[9:], uuid)
  116. return string(buf[:])
  117. }
  118. func encodeHex(dst []byte, uuid UUID) {
  119. hex.Encode(dst[:], uuid[:4])
  120. dst[8] = '-'
  121. hex.Encode(dst[9:13], uuid[4:6])
  122. dst[13] = '-'
  123. hex.Encode(dst[14:18], uuid[6:8])
  124. dst[18] = '-'
  125. hex.Encode(dst[19:23], uuid[8:10])
  126. dst[23] = '-'
  127. hex.Encode(dst[24:], uuid[10:])
  128. }
  129. // Variant returns the variant encoded in uuid.
  130. func (uuid UUID) Variant() Variant {
  131. switch {
  132. case (uuid[8] & 0xc0) == 0x80:
  133. return RFC4122
  134. case (uuid[8] & 0xe0) == 0xc0:
  135. return Microsoft
  136. case (uuid[8] & 0xe0) == 0xe0:
  137. return Future
  138. default:
  139. return Reserved
  140. }
  141. }
  142. // Version returns the version of uuid.
  143. func (uuid UUID) Version() Version {
  144. return Version(uuid[6] >> 4)
  145. }
  146. func (v Version) String() string {
  147. if v > 15 {
  148. return fmt.Sprintf("BAD_VERSION_%d", v)
  149. }
  150. return fmt.Sprintf("VERSION_%d", v)
  151. }
  152. func (v Variant) String() string {
  153. switch v {
  154. case RFC4122:
  155. return "RFC4122"
  156. case Reserved:
  157. return "Reserved"
  158. case Microsoft:
  159. return "Microsoft"
  160. case Future:
  161. return "Future"
  162. case Invalid:
  163. return "Invalid"
  164. }
  165. return fmt.Sprintf("BadVariant%d", int(v))
  166. }
  167. // SetRand sets the random number generator to r, which implements io.Reader.
  168. // If r.Read returns an error when the package requests random data then
  169. // a panic will be issued.
  170. //
  171. // Calling SetRand with nil sets the random number generator to the default
  172. // generator.
  173. func SetRand(r io.Reader) {
  174. if r == nil {
  175. rander = rand.Reader
  176. return
  177. }
  178. rander = r
  179. }