uuid.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. // representing 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. // getTimestamp converts time to UUID (version 1) timestamp.
  103. // It must be an interval of 100-nanoseconds since timeBase.
  104. func getTimestamp(t time.Time) int64 {
  105. utcTime := t.In(time.UTC)
  106. ts := int64(utcTime.Unix()-timeBase)*10000000 + int64(utcTime.Nanosecond()/100)
  107. return ts
  108. }
  109. // TimeUUID generates a new time based UUID (version 1) using the current
  110. // time as the timestamp.
  111. func TimeUUID() UUID {
  112. return UUIDFromTime(time.Now())
  113. }
  114. // The min and max clock values for a UUID.
  115. //
  116. // Cassandra's TimeUUIDType compares the lsb parts as signed byte arrays.
  117. // Thus, the min value for each byte is -128 and the max is +127.
  118. const (
  119. minClock = 0x8080
  120. maxClock = 0x7f7f
  121. )
  122. // The min and max node values for a UUID.
  123. //
  124. // See explanation about Cassandra's TimeUUIDType comparison logic above.
  125. var (
  126. minNode = []byte{0x80, 0x80, 0x80, 0x80, 0x80, 0x80}
  127. maxNode = []byte{0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f}
  128. )
  129. // MinTimeUUID generates a "fake" time based UUID (version 1) which will be
  130. // the smallest possible UUID generated for the provided timestamp.
  131. //
  132. // UUIDs generated by this function are not unique and are mostly suitable only
  133. // in queries to select a time range of a Cassandra's TimeUUID column.
  134. func MinTimeUUID(t time.Time) UUID {
  135. return TimeUUIDWith(getTimestamp(t), minClock, minNode)
  136. }
  137. // MaxTimeUUID generates a "fake" time based UUID (version 1) which will be
  138. // the biggest possible UUID generated for the provided timestamp.
  139. //
  140. // UUIDs generated by this function are not unique and are mostly suitable only
  141. // in queries to select a time range of a Cassandra's TimeUUID column.
  142. func MaxTimeUUID(t time.Time) UUID {
  143. return TimeUUIDWith(getTimestamp(t), maxClock, maxNode)
  144. }
  145. // UUIDFromTime generates a new time based UUID (version 1) as described in
  146. // RFC 4122. This UUID contains the MAC address of the node that generated
  147. // the UUID, the given timestamp and a sequence number.
  148. func UUIDFromTime(t time.Time) UUID {
  149. ts := getTimestamp(t)
  150. clock := atomic.AddUint32(&clockSeq, 1)
  151. return TimeUUIDWith(ts, clock, hardwareAddr)
  152. }
  153. // TimeUUIDWith generates a new time based UUID (version 1) as described in
  154. // RFC4122 with given parameters. t is the number of 100's of nanoseconds
  155. // since 15 Oct 1582 (60bits). clock is the number of clock sequence (14bits).
  156. // node is a slice to gurarantee the uniqueness of the UUID (up to 6bytes).
  157. // Note: calling this function does not increment the static clock sequence.
  158. func TimeUUIDWith(t int64, clock uint32, node []byte) UUID {
  159. var u UUID
  160. u[0], u[1], u[2], u[3] = byte(t>>24), byte(t>>16), byte(t>>8), byte(t)
  161. u[4], u[5] = byte(t>>40), byte(t>>32)
  162. u[6], u[7] = byte(t>>56)&0x0F, byte(t>>48)
  163. u[8] = byte(clock >> 8)
  164. u[9] = byte(clock)
  165. copy(u[10:], node)
  166. u[6] |= 0x10 // set version to 1 (time based uuid)
  167. u[8] &= 0x3F // clear variant
  168. u[8] |= 0x80 // set to IETF variant
  169. return u
  170. }
  171. // String returns the UUID in it's canonical form, a 32 digit hexadecimal
  172. // number in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  173. func (u UUID) String() string {
  174. var offsets = [...]int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34}
  175. const hexString = "0123456789abcdef"
  176. r := make([]byte, 36)
  177. for i, b := range u {
  178. r[offsets[i]] = hexString[b>>4]
  179. r[offsets[i]+1] = hexString[b&0xF]
  180. }
  181. r[8] = '-'
  182. r[13] = '-'
  183. r[18] = '-'
  184. r[23] = '-'
  185. return string(r)
  186. }
  187. // Bytes returns the raw byte slice for this UUID. A UUID is always 128 bits
  188. // (16 bytes) long.
  189. func (u UUID) Bytes() []byte {
  190. return u[:]
  191. }
  192. // Variant returns the variant of this UUID. This package will only generate
  193. // UUIDs in the IETF variant.
  194. func (u UUID) Variant() int {
  195. x := u[8]
  196. if x&0x80 == 0 {
  197. return VariantNCSCompat
  198. }
  199. if x&0x40 == 0 {
  200. return VariantIETF
  201. }
  202. if x&0x20 == 0 {
  203. return VariantMicrosoft
  204. }
  205. return VariantFuture
  206. }
  207. // Version extracts the version of this UUID variant. The RFC 4122 describes
  208. // five kinds of UUIDs.
  209. func (u UUID) Version() int {
  210. return int(u[6] & 0xF0 >> 4)
  211. }
  212. // Node extracts the MAC address of the node who generated this UUID. It will
  213. // return nil if the UUID is not a time based UUID (version 1).
  214. func (u UUID) Node() []byte {
  215. if u.Version() != 1 {
  216. return nil
  217. }
  218. return u[10:]
  219. }
  220. // Clock extracts the clock sequence of this UUID. It will return zero if the
  221. // UUID is not a time based UUID (version 1).
  222. func (u UUID) Clock() uint32 {
  223. if u.Version() != 1 {
  224. return 0
  225. }
  226. // Clock sequence is the lower 14bits of u[8:10]
  227. return uint32(u[8]&0x3F)<<8 | uint32(u[9])
  228. }
  229. // Timestamp extracts the timestamp information from a time based UUID
  230. // (version 1).
  231. func (u UUID) Timestamp() int64 {
  232. if u.Version() != 1 {
  233. return 0
  234. }
  235. return int64(uint64(u[0])<<24|uint64(u[1])<<16|
  236. uint64(u[2])<<8|uint64(u[3])) +
  237. int64(uint64(u[4])<<40|uint64(u[5])<<32) +
  238. int64(uint64(u[6]&0x0F)<<56|uint64(u[7])<<48)
  239. }
  240. // Time is like Timestamp, except that it returns a time.Time.
  241. func (u UUID) Time() time.Time {
  242. if u.Version() != 1 {
  243. return time.Time{}
  244. }
  245. t := u.Timestamp()
  246. sec := t / 1e7
  247. nsec := (t % 1e7) * 100
  248. return time.Unix(sec+timeBase, nsec).UTC()
  249. }
  250. // Marshaling for JSON
  251. func (u UUID) MarshalJSON() ([]byte, error) {
  252. return []byte(`"` + u.String() + `"`), nil
  253. }
  254. // Unmarshaling for JSON
  255. func (u *UUID) UnmarshalJSON(data []byte) error {
  256. str := strings.Trim(string(data), `"`)
  257. if len(str) > 36 {
  258. return fmt.Errorf("invalid JSON UUID %s", str)
  259. }
  260. parsed, err := ParseUUID(str)
  261. if err == nil {
  262. copy(u[:], parsed[:])
  263. }
  264. return err
  265. }
  266. func (u UUID) MarshalText() ([]byte, error) {
  267. return []byte(u.String()), nil
  268. }
  269. func (u *UUID) UnmarshalText(text []byte) (err error) {
  270. *u, err = ParseUUID(string(text))
  271. return
  272. }