uuid.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 provides implementations of the Universally Unique Identifier
  22. // (UUID), as specified in RFC-4122 and the Peabody RFC Draft (revision 02).
  23. //
  24. // RFC-4122[1] provides the specification for versions 1, 3, 4, and 5. The
  25. // Peabody UUID RFC Draft[2] provides the specification for the new k-sortable
  26. // UUIDs, versions 6 and 7.
  27. //
  28. // DCE 1.1[3] provides the specification for version 2, but version 2 support
  29. // was removed from this package in v4 due to some concerns with the
  30. // specification itself. Reading the spec, it seems that it would result in
  31. // generating UUIDs that aren't very unique. In having read the spec it seemed
  32. // that our implementation did not meet the spec. It also seems to be at-odds
  33. // with RFC 4122, meaning we would need quite a bit of special code to support
  34. // it. Lastly, there were no Version 2 implementations that we could find to
  35. // ensure we were understanding the specification correctly.
  36. //
  37. // [1] https://tools.ietf.org/html/rfc4122
  38. // [2] https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-02
  39. // [3] http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01
  40. package uuid
  41. import (
  42. "encoding/binary"
  43. "encoding/hex"
  44. "fmt"
  45. "io"
  46. "strings"
  47. "time"
  48. )
  49. // Size of a UUID in bytes.
  50. const Size = 16
  51. // UUID is an array type to represent the value of a UUID, as defined in RFC-4122.
  52. type UUID [Size]byte
  53. // UUID versions.
  54. const (
  55. _ byte = iota
  56. V1 // Version 1 (date-time and MAC address)
  57. _ // Version 2 (date-time and MAC address, DCE security version) [removed]
  58. V3 // Version 3 (namespace name-based)
  59. V4 // Version 4 (random)
  60. V5 // Version 5 (namespace name-based)
  61. V6 // Version 6 (k-sortable timestamp and random data) [peabody draft]
  62. V7 // Version 7 (k-sortable timestamp, with configurable precision, and random data) [peabody draft]
  63. _ // Version 8 (k-sortable timestamp, meant for custom implementations) [peabody draft] [not implemented]
  64. )
  65. // UUID layout variants.
  66. const (
  67. VariantNCS byte = iota
  68. VariantRFC4122
  69. VariantMicrosoft
  70. VariantFuture
  71. )
  72. // UUID DCE domains.
  73. const (
  74. DomainPerson = iota
  75. DomainGroup
  76. DomainOrg
  77. )
  78. // Timestamp is the count of 100-nanosecond intervals since 00:00:00.00,
  79. // 15 October 1582 within a V1 UUID. This type has no meaning for other
  80. // UUID versions since they don't have an embedded timestamp.
  81. type Timestamp uint64
  82. const _100nsPerSecond = 10000000
  83. // Time returns the UTC time.Time representation of a Timestamp
  84. func (t Timestamp) Time() (time.Time, error) {
  85. secs := uint64(t) / _100nsPerSecond
  86. nsecs := 100 * (uint64(t) % _100nsPerSecond)
  87. return time.Unix(int64(secs)-(epochStart/_100nsPerSecond), int64(nsecs)), nil
  88. }
  89. // TimestampFromV1 returns the Timestamp embedded within a V1 UUID.
  90. // Returns an error if the UUID is any version other than 1.
  91. func TimestampFromV1(u UUID) (Timestamp, error) {
  92. if u.Version() != 1 {
  93. err := fmt.Errorf("uuid: %s is version %d, not version 1", u, u.Version())
  94. return 0, err
  95. }
  96. low := binary.BigEndian.Uint32(u[0:4])
  97. mid := binary.BigEndian.Uint16(u[4:6])
  98. hi := binary.BigEndian.Uint16(u[6:8]) & 0xfff
  99. return Timestamp(uint64(low) + (uint64(mid) << 32) + (uint64(hi) << 48)), nil
  100. }
  101. // TimestampFromV6 returns the Timestamp embedded within a V6 UUID. This
  102. // function returns an error if the UUID is any version other than 6.
  103. //
  104. // This is implemented based on revision 01 of the Peabody UUID draft, and may
  105. // be subject to change pending further revisions. Until the final specification
  106. // revision is finished, changes required to implement updates to the spec will
  107. // not be considered a breaking change. They will happen as a minor version
  108. // releases until the spec is final.
  109. func TimestampFromV6(u UUID) (Timestamp, error) {
  110. if u.Version() != 6 {
  111. return 0, fmt.Errorf("uuid: %s is version %d, not version 6", u, u.Version())
  112. }
  113. hi := binary.BigEndian.Uint32(u[0:4])
  114. mid := binary.BigEndian.Uint16(u[4:6])
  115. low := binary.BigEndian.Uint16(u[6:8]) & 0xfff
  116. return Timestamp(uint64(low) + (uint64(mid) << 12) + (uint64(hi) << 28)), nil
  117. }
  118. // String parse helpers.
  119. var (
  120. urnPrefix = []byte("urn:uuid:")
  121. byteGroups = []int{8, 4, 4, 4, 12}
  122. )
  123. // Nil is the nil UUID, as specified in RFC-4122, that has all 128 bits set to
  124. // zero.
  125. var Nil = UUID{}
  126. // Predefined namespace UUIDs.
  127. var (
  128. NamespaceDNS = Must(FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
  129. NamespaceURL = Must(FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8"))
  130. NamespaceOID = Must(FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8"))
  131. NamespaceX500 = Must(FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
  132. )
  133. // Version returns the algorithm version used to generate the UUID.
  134. func (u UUID) Version() byte {
  135. return u[6] >> 4
  136. }
  137. // Variant returns the UUID layout variant.
  138. func (u UUID) Variant() byte {
  139. switch {
  140. case (u[8] >> 7) == 0x00:
  141. return VariantNCS
  142. case (u[8] >> 6) == 0x02:
  143. return VariantRFC4122
  144. case (u[8] >> 5) == 0x06:
  145. return VariantMicrosoft
  146. case (u[8] >> 5) == 0x07:
  147. fallthrough
  148. default:
  149. return VariantFuture
  150. }
  151. }
  152. // Bytes returns a byte slice representation of the UUID.
  153. func (u UUID) Bytes() []byte {
  154. return u[:]
  155. }
  156. // String returns a canonical RFC-4122 string representation of the UUID:
  157. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  158. func (u UUID) String() string {
  159. buf := make([]byte, 36)
  160. hex.Encode(buf[0:8], u[0:4])
  161. buf[8] = '-'
  162. hex.Encode(buf[9:13], u[4:6])
  163. buf[13] = '-'
  164. hex.Encode(buf[14:18], u[6:8])
  165. buf[18] = '-'
  166. hex.Encode(buf[19:23], u[8:10])
  167. buf[23] = '-'
  168. hex.Encode(buf[24:], u[10:])
  169. return string(buf)
  170. }
  171. // Format implements fmt.Formatter for UUID values.
  172. //
  173. // The behavior is as follows:
  174. // The 'x' and 'X' verbs output only the hex digits of the UUID, using a-f for 'x' and A-F for 'X'.
  175. // The 'v', '+v', 's' and 'q' verbs return the canonical RFC-4122 string representation.
  176. // The 'S' verb returns the RFC-4122 format, but with capital hex digits.
  177. // The '#v' verb returns the "Go syntax" representation, which is a 16 byte array initializer.
  178. // All other verbs not handled directly by the fmt package (like '%p') are unsupported and will return
  179. // "%!verb(uuid.UUID=value)" as recommended by the fmt package.
  180. func (u UUID) Format(f fmt.State, c rune) {
  181. switch c {
  182. case 'x', 'X':
  183. s := hex.EncodeToString(u.Bytes())
  184. if c == 'X' {
  185. s = strings.Map(toCapitalHexDigits, s)
  186. }
  187. _, _ = io.WriteString(f, s)
  188. case 'v':
  189. var s string
  190. if f.Flag('#') {
  191. s = fmt.Sprintf("%#v", [Size]byte(u))
  192. } else {
  193. s = u.String()
  194. }
  195. _, _ = io.WriteString(f, s)
  196. case 's', 'S':
  197. s := u.String()
  198. if c == 'S' {
  199. s = strings.Map(toCapitalHexDigits, s)
  200. }
  201. _, _ = io.WriteString(f, s)
  202. case 'q':
  203. _, _ = io.WriteString(f, `"`+u.String()+`"`)
  204. default:
  205. // invalid/unsupported format verb
  206. fmt.Fprintf(f, "%%!%c(uuid.UUID=%s)", c, u.String())
  207. }
  208. }
  209. func toCapitalHexDigits(ch rune) rune {
  210. // convert a-f hex digits to A-F
  211. switch ch {
  212. case 'a':
  213. return 'A'
  214. case 'b':
  215. return 'B'
  216. case 'c':
  217. return 'C'
  218. case 'd':
  219. return 'D'
  220. case 'e':
  221. return 'E'
  222. case 'f':
  223. return 'F'
  224. default:
  225. return ch
  226. }
  227. }
  228. // SetVersion sets the version bits.
  229. func (u *UUID) SetVersion(v byte) {
  230. u[6] = (u[6] & 0x0f) | (v << 4)
  231. }
  232. // SetVariant sets the variant bits.
  233. func (u *UUID) SetVariant(v byte) {
  234. switch v {
  235. case VariantNCS:
  236. u[8] = (u[8]&(0xff>>1) | (0x00 << 7))
  237. case VariantRFC4122:
  238. u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
  239. case VariantMicrosoft:
  240. u[8] = (u[8]&(0xff>>3) | (0x06 << 5))
  241. case VariantFuture:
  242. fallthrough
  243. default:
  244. u[8] = (u[8]&(0xff>>3) | (0x07 << 5))
  245. }
  246. }
  247. // Must is a helper that wraps a call to a function returning (UUID, error)
  248. // and panics if the error is non-nil. It is intended for use in variable
  249. // initializations such as
  250. // var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000"))
  251. func Must(u UUID, err error) UUID {
  252. if err != nil {
  253. panic(err)
  254. }
  255. return u
  256. }