uuid.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 (UUID), as specified in RFC-4122 and DCE 1.1.
  22. //
  23. // RFC-4122[1] provides the specification for versions 1, 3, 4, and 5.
  24. //
  25. // DCE 1.1[2] provides the specification for version 2.
  26. //
  27. // [1] https://tools.ietf.org/html/rfc4122
  28. // [2] http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01
  29. package uuid
  30. import (
  31. "encoding/binary"
  32. "encoding/hex"
  33. "fmt"
  34. "time"
  35. )
  36. // Size of a UUID in bytes.
  37. const Size = 16
  38. // UUID is an array type to represent the value of a UUID, as defined in RFC-4122.
  39. type UUID [Size]byte
  40. // UUID versions.
  41. const (
  42. _ byte = iota
  43. V1 // Version 1 (date-time and MAC address)
  44. V2 // Version 2 (date-time and MAC address, DCE security version)
  45. V3 // Version 3 (namespace name-based)
  46. V4 // Version 4 (random)
  47. V5 // Version 5 (namespace name-based)
  48. )
  49. // UUID layout variants.
  50. const (
  51. VariantNCS byte = iota
  52. VariantRFC4122
  53. VariantMicrosoft
  54. VariantFuture
  55. )
  56. // UUID DCE domains.
  57. const (
  58. DomainPerson = iota
  59. DomainGroup
  60. DomainOrg
  61. )
  62. // Timestamp is the count of 100-nanosecond intervals since 00:00:00.00,
  63. // 15 October 1582 within a V1 UUID. This type has no meaning for V2-V5
  64. // UUIDs since they don't have an embedded timestamp.
  65. type Timestamp uint64
  66. const _100nsPerSecond = 10000000
  67. // Time returns the UTC time.Time representation of a Timestamp
  68. func (t Timestamp) Time() (time.Time, error) {
  69. secs := uint64(t) / _100nsPerSecond
  70. nsecs := 100 * (uint64(t) % _100nsPerSecond)
  71. return time.Unix(int64(secs)-(epochStart/_100nsPerSecond), int64(nsecs)), nil
  72. }
  73. // TimestampFromV1 returns the Timestamp embedded within a V1 UUID.
  74. // Returns an error if the UUID is any version other than 1.
  75. func TimestampFromV1(u UUID) (Timestamp, error) {
  76. if u.Version() != 1 {
  77. err := fmt.Errorf("uuid: %s is version %d, not version 1", u, u.Version())
  78. return 0, err
  79. }
  80. low := binary.BigEndian.Uint32(u[0:4])
  81. mid := binary.BigEndian.Uint16(u[4:6])
  82. hi := binary.BigEndian.Uint16(u[6:8]) & 0xfff
  83. return Timestamp(uint64(low) + (uint64(mid) << 32) + (uint64(hi) << 48)), nil
  84. }
  85. // String parse helpers.
  86. var (
  87. urnPrefix = []byte("urn:uuid:")
  88. byteGroups = []int{8, 4, 4, 4, 12}
  89. )
  90. // Nil is the nil UUID, as specified in RFC-4122, that has all 128 bits set to
  91. // zero.
  92. var Nil = UUID{}
  93. // Predefined namespace UUIDs.
  94. var (
  95. NamespaceDNS = Must(FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
  96. NamespaceURL = Must(FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8"))
  97. NamespaceOID = Must(FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8"))
  98. NamespaceX500 = Must(FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
  99. )
  100. // Version returns the algorithm version used to generate the UUID.
  101. func (u UUID) Version() byte {
  102. return u[6] >> 4
  103. }
  104. // Variant returns the UUID layout variant.
  105. func (u UUID) Variant() byte {
  106. switch {
  107. case (u[8] >> 7) == 0x00:
  108. return VariantNCS
  109. case (u[8] >> 6) == 0x02:
  110. return VariantRFC4122
  111. case (u[8] >> 5) == 0x06:
  112. return VariantMicrosoft
  113. case (u[8] >> 5) == 0x07:
  114. fallthrough
  115. default:
  116. return VariantFuture
  117. }
  118. }
  119. // Bytes returns a byte slice representation of the UUID.
  120. func (u UUID) Bytes() []byte {
  121. return u[:]
  122. }
  123. // String returns a canonical RFC-4122 string representation of the UUID:
  124. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  125. func (u UUID) String() string {
  126. buf := make([]byte, 36)
  127. hex.Encode(buf[0:8], u[0:4])
  128. buf[8] = '-'
  129. hex.Encode(buf[9:13], u[4:6])
  130. buf[13] = '-'
  131. hex.Encode(buf[14:18], u[6:8])
  132. buf[18] = '-'
  133. hex.Encode(buf[19:23], u[8:10])
  134. buf[23] = '-'
  135. hex.Encode(buf[24:], u[10:])
  136. return string(buf)
  137. }
  138. // SetVersion sets the version bits.
  139. func (u *UUID) SetVersion(v byte) {
  140. u[6] = (u[6] & 0x0f) | (v << 4)
  141. }
  142. // SetVariant sets the variant bits.
  143. func (u *UUID) SetVariant(v byte) {
  144. switch v {
  145. case VariantNCS:
  146. u[8] = (u[8]&(0xff>>1) | (0x00 << 7))
  147. case VariantRFC4122:
  148. u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
  149. case VariantMicrosoft:
  150. u[8] = (u[8]&(0xff>>3) | (0x06 << 5))
  151. case VariantFuture:
  152. fallthrough
  153. default:
  154. u[8] = (u[8]&(0xff>>3) | (0x07 << 5))
  155. }
  156. }
  157. // Must is a helper that wraps a call to a function returning (UUID, error)
  158. // and panics if the error is non-nil. It is intended for use in variable
  159. // initializations such as
  160. // var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000"))
  161. func Must(u UUID, err error) UUID {
  162. if err != nil {
  163. panic(err)
  164. }
  165. return u
  166. }