uuid.go 5.2 KB

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