uuid.go 5.9 KB

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