uuid.go 5.6 KB

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