uuid.go 5.0 KB

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