uuid.go 5.0 KB

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