uuid.go 4.8 KB

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