uuid.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Copyright (c) 2012 by Christoph Hack <christoph@tux21b.org>
  2. // All rights reserved. Distributed under the Simplified BSD License.
  3. // The uuid package can be used to generate and parse universally unique
  4. // identifiers, a standardized format in the form of a 128 bit number.
  5. //
  6. // http://tools.ietf.org/html/rfc4122
  7. package uuid
  8. import (
  9. "crypto/rand"
  10. "fmt"
  11. "io"
  12. "net"
  13. "time"
  14. )
  15. type UUID [16]byte
  16. var hardwareAddr []byte
  17. const (
  18. VariantNCSCompat = 0
  19. VariantIETF = 2
  20. VariantMicrosoft = 6
  21. VariantFuture = 7
  22. )
  23. func init() {
  24. if interfaces, err := net.Interfaces(); err == nil {
  25. for _, i := range interfaces {
  26. if i.Flags&net.FlagLoopback == 0 && len(i.HardwareAddr) > 0 {
  27. hardwareAddr = i.HardwareAddr
  28. break
  29. }
  30. }
  31. }
  32. if hardwareAddr == nil {
  33. // If we failed to obtain the MAC address of the current computer,
  34. // we will use a randomly generated 6 byte sequence instead and set
  35. // the multicast bit as recommended in RFC 4122.
  36. hardwareAddr = make([]byte, 6)
  37. _, err := io.ReadFull(rand.Reader, hardwareAddr)
  38. if err != nil {
  39. panic(err)
  40. }
  41. hardwareAddr[0] = hardwareAddr[0] | 0x01
  42. }
  43. }
  44. // ParseUUID parses a 32 digit hexadecimal number (that might contain hypens)
  45. // represanting an UUID.
  46. func ParseUUID(input string) (UUID, error) {
  47. var u UUID
  48. j := 0
  49. for _, r := range input {
  50. switch {
  51. case r == '-' && j&1 == 0:
  52. continue
  53. case r >= '0' && r <= '9' && j < 32:
  54. u[j/2] |= byte(r-'0') << uint(4-j&1*4)
  55. case r >= 'a' && r <= 'f' && j < 32:
  56. u[j/2] |= byte(r-'a'+10) << uint(4-j&1*4)
  57. case r >= 'A' && r <= 'F' && j < 32:
  58. u[j/2] |= byte(r-'A'+10) << uint(4-j&1*4)
  59. default:
  60. return UUID{}, fmt.Errorf("invalid UUID %q", input)
  61. }
  62. j += 1
  63. }
  64. if j != 32 {
  65. return UUID{}, fmt.Errorf("invalid UUID %q", input)
  66. }
  67. return u, nil
  68. }
  69. // FromBytes converts a raw byte slice to an UUID. It will panic if the slice
  70. // isn't exactly 16 bytes long.
  71. func FromBytes(input []byte) UUID {
  72. var u UUID
  73. if len(input) != 16 {
  74. panic("UUIDs must be exactly 16 bytes long")
  75. }
  76. copy(u[:], input)
  77. return u
  78. }
  79. // RandomUUID generates a totally random UUID (version 4) as described in
  80. // RFC 4122.
  81. func RandomUUID() UUID {
  82. var u UUID
  83. io.ReadFull(rand.Reader, u[:])
  84. u[6] &= 0x0F // clear version
  85. u[6] |= 0x40 // set version to 4 (random uuid)
  86. u[8] &= 0x3F // clear variant
  87. u[8] |= 0x80 // set to IETF variant
  88. return u
  89. }
  90. var timeBase = time.Date(1582, time.October, 15, 0, 0, 0, 0, time.UTC).Unix()
  91. // TimeUUID generates a new time based UUID (version 1) as described in RFC
  92. // 4122. This UUID contains the MAC address of the node that generated the
  93. // UUID, a timestamp and a sequence number.
  94. func TimeUUID() UUID {
  95. var u UUID
  96. now := time.Now().In(time.UTC)
  97. t := uint64(now.Unix()-timeBase)*10000000 + uint64(now.Nanosecond()/100)
  98. u[0], u[1], u[2], u[3] = byte(t>>24), byte(t>>16), byte(t>>8), byte(t)
  99. u[4], u[5] = byte(t>>40), byte(t>>32)
  100. u[6], u[7] = byte(t>>56)&0x0F, byte(t>>48)
  101. var clockSeq [2]byte
  102. io.ReadFull(rand.Reader, clockSeq[:])
  103. u[8] = clockSeq[1]
  104. u[9] = clockSeq[0]
  105. copy(u[10:], hardwareAddr)
  106. u[6] |= 0x10 // set version to 1 (time based uuid)
  107. u[8] &= 0x3F // clear variant
  108. u[8] |= 0x80 // set to IETF variant
  109. return u
  110. }
  111. // String returns the UUID in it's canonical form, a 32 digit hexadecimal
  112. // number in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  113. func (u UUID) String() string {
  114. return fmt.Sprintf("%x-%x-%x-%x-%x",
  115. u[0:4], u[4:6], u[6:8], u[8:10], u[10:16])
  116. }
  117. // Bytes returns the raw byte slice for this UUID. A UUID is always 128 bits
  118. // (16 bytes) long.
  119. func (u UUID) Bytes() []byte {
  120. return u[:]
  121. }
  122. // Variant returns the variant of this UUID. This package will only generate
  123. // UUIDs in the IETF variant.
  124. func (u UUID) Variant() int {
  125. x := u[8]
  126. if x&0x80 == 0 {
  127. return VariantNCSCompat
  128. }
  129. if x&0x40 == 0 {
  130. return VariantIETF
  131. }
  132. if x&0x20 == 0 {
  133. return VariantMicrosoft
  134. }
  135. return VariantFuture
  136. }
  137. // Version extracts the version of this UUID variant. The RFC 4122 describes
  138. // five kinds of UUIDs.
  139. func (u UUID) Version() int {
  140. return int(u[6] & 0xF0 >> 4)
  141. }
  142. // Node extracts the MAC address of the node who generated this UUID. It will
  143. // return nil if the UUID is not a time based UUID (version 1).
  144. func (u UUID) Node() []byte {
  145. if u.Version() != 1 {
  146. return nil
  147. }
  148. return u[10:]
  149. }
  150. // Timestamp extracts the timestamp information from a time based UUID
  151. // (version 1).
  152. func (u UUID) Timestamp() uint64 {
  153. if u.Version() != 1 {
  154. return 0
  155. }
  156. return uint64(u[0])<<24 + uint64(u[1])<<16 + uint64(u[2])<<8 +
  157. uint64(u[3]) + uint64(u[4])<<40 + uint64(u[5])<<32 +
  158. uint64(u[7])<<48 + uint64(u[6]&0x0F)<<56
  159. }
  160. // Time is like Timestamp, except that it returns a time.Time.
  161. func (u UUID) Time() time.Time {
  162. t := u.Timestamp()
  163. if t == 0 {
  164. return time.Time{}
  165. }
  166. sec := t / 10000000
  167. nsec := t - sec
  168. return time.Unix(int64(sec)+timeBase, int64(nsec))
  169. }