uuid.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 uuid
  9. import (
  10. "crypto/rand"
  11. "fmt"
  12. "io"
  13. "net"
  14. "time"
  15. "github.com/tux21b/gocql"
  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. // FromBytes converts a raw byte slice to an UUID. It will panic if the slice
  72. // isn't exactly 16 bytes long.
  73. func FromBytes(input []byte) UUID {
  74. var u UUID
  75. if len(input) != 16 {
  76. panic("UUIDs must be exactly 16 bytes long")
  77. }
  78. copy(u[:], input)
  79. return u
  80. }
  81. // RandomUUID generates a totally random UUID (version 4) as described in
  82. // RFC 4122.
  83. func RandomUUID() UUID {
  84. var u UUID
  85. io.ReadFull(rand.Reader, u[:])
  86. u[6] &= 0x0F // clear version
  87. u[6] |= 0x40 // set version to 4 (random uuid)
  88. u[8] &= 0x3F // clear variant
  89. u[8] |= 0x80 // set to IETF variant
  90. return u
  91. }
  92. var timeBase = time.Date(1582, time.October, 15, 0, 0, 0, 0, time.UTC).Unix()
  93. // TimeUUID generates a new time based UUID (version 1) as described in RFC
  94. // 4122. This UUID contains the MAC address of the node that generated the
  95. // UUID, a timestamp and a sequence number.
  96. func TimeUUID() UUID {
  97. var u UUID
  98. now := time.Now().In(time.UTC)
  99. t := uint64(now.Unix()-timeBase)*10000000 + uint64(now.Nanosecond()/100)
  100. u[0], u[1], u[2], u[3] = byte(t>>24), byte(t>>16), byte(t>>8), byte(t)
  101. u[4], u[5] = byte(t>>40), byte(t>>32)
  102. u[6], u[7] = byte(t>>56)&0x0F, byte(t>>48)
  103. var clockSeq [2]byte
  104. io.ReadFull(rand.Reader, clockSeq[:])
  105. u[8] = clockSeq[1]
  106. u[9] = clockSeq[0]
  107. copy(u[10:], hardwareAddr)
  108. u[6] |= 0x10 // set version to 1 (time based uuid)
  109. u[8] &= 0x3F // clear variant
  110. u[8] |= 0x80 // set to IETF variant
  111. return u
  112. }
  113. // String returns the UUID in it's canonical form, a 32 digit hexadecimal
  114. // number in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  115. func (u UUID) String() string {
  116. return fmt.Sprintf("%x-%x-%x-%x-%x",
  117. u[0:4], u[4:6], u[6:8], u[8:10], u[10:16])
  118. }
  119. // Bytes returns the raw byte slice for this UUID. A UUID is always 128 bits
  120. // (16 bytes) long.
  121. func (u UUID) Bytes() []byte {
  122. return u[:]
  123. }
  124. // Variant returns the variant of this UUID. This package will only generate
  125. // UUIDs in the IETF variant.
  126. func (u UUID) Variant() int {
  127. x := u[8]
  128. if x&0x80 == 0 {
  129. return VariantNCSCompat
  130. }
  131. if x&0x40 == 0 {
  132. return VariantIETF
  133. }
  134. if x&0x20 == 0 {
  135. return VariantMicrosoft
  136. }
  137. return VariantFuture
  138. }
  139. // Version extracts the version of this UUID variant. The RFC 4122 describes
  140. // five kinds of UUIDs.
  141. func (u UUID) Version() int {
  142. return int(u[6] & 0xF0 >> 4)
  143. }
  144. // Node extracts the MAC address of the node who generated this UUID. It will
  145. // return nil if the UUID is not a time based UUID (version 1).
  146. func (u UUID) Node() []byte {
  147. if u.Version() != 1 {
  148. return nil
  149. }
  150. return u[10:]
  151. }
  152. // Timestamp extracts the timestamp information from a time based UUID
  153. // (version 1).
  154. func (u UUID) Timestamp() uint64 {
  155. if u.Version() != 1 {
  156. return 0
  157. }
  158. return uint64(u[0])<<24 + uint64(u[1])<<16 + uint64(u[2])<<8 +
  159. uint64(u[3]) + uint64(u[4])<<40 + uint64(u[5])<<32 +
  160. uint64(u[7])<<48 + uint64(u[6]&0x0F)<<56
  161. }
  162. // Time is like Timestamp, except that it returns a time.Time.
  163. func (u UUID) Time() time.Time {
  164. t := u.Timestamp()
  165. if t == 0 {
  166. return time.Time{}
  167. }
  168. sec := t / 10000000
  169. nsec := t - sec
  170. return time.Unix(int64(sec)+timeBase, int64(nsec))
  171. }
  172. func (u UUID) MarshalCQL(info *gocql.TypeInfo) ([]byte, error) {
  173. switch info.Type {
  174. case gocql.TypeUUID, gocql.TypeTimeUUID:
  175. return u[:], nil
  176. }
  177. return gocql.Marshal(info, u[:])
  178. }
  179. func (u *UUID) UnmarshalCQL(info *gocql.TypeInfo, data []byte) error {
  180. switch info.Type {
  181. case gocql.TypeUUID, gocql.TypeTimeUUID:
  182. *u = FromBytes(data)
  183. return nil
  184. }
  185. var val []byte
  186. if err := gocql.Unmarshal(info, data, &val); err != nil {
  187. return err
  188. }
  189. *u = FromBytes(val)
  190. return nil
  191. }