uuid.go 6.1 KB

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