You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

guid.go 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Package guid provides a GUID type. The backing structure for a GUID is
  2. // identical to that used by the golang.org/x/sys/windows GUID type.
  3. // There are two main binary encodings used for a GUID, the big-endian encoding,
  4. // and the Windows (mixed-endian) encoding. See here for details:
  5. // https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding
  6. package guid
  7. import (
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding"
  11. "encoding/binary"
  12. "fmt"
  13. "strconv"
  14. "golang.org/x/sys/windows"
  15. )
  16. // Variant specifies which GUID variant (or "type") of the GUID. It determines
  17. // how the entirety of the rest of the GUID is interpreted.
  18. type Variant uint8
  19. // The variants specified by RFC 4122.
  20. const (
  21. // VariantUnknown specifies a GUID variant which does not conform to one of
  22. // the variant encodings specified in RFC 4122.
  23. VariantUnknown Variant = iota
  24. VariantNCS
  25. VariantRFC4122
  26. VariantMicrosoft
  27. VariantFuture
  28. )
  29. // Version specifies how the bits in the GUID were generated. For instance, a
  30. // version 4 GUID is randomly generated, and a version 5 is generated from the
  31. // hash of an input string.
  32. type Version uint8
  33. var _ = (encoding.TextMarshaler)(GUID{})
  34. var _ = (encoding.TextUnmarshaler)(&GUID{})
  35. // GUID represents a GUID/UUID. It has the same structure as
  36. // golang.org/x/sys/windows.GUID so that it can be used with functions expecting
  37. // that type. It is defined as its own type so that stringification and
  38. // marshaling can be supported. The representation matches that used by native
  39. // Windows code.
  40. type GUID windows.GUID
  41. // NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122.
  42. func NewV4() (GUID, error) {
  43. var b [16]byte
  44. if _, err := rand.Read(b[:]); err != nil {
  45. return GUID{}, err
  46. }
  47. g := FromArray(b)
  48. g.setVersion(4) // Version 4 means randomly generated.
  49. g.setVariant(VariantRFC4122)
  50. return g, nil
  51. }
  52. // NewV5 returns a new version 5 (generated from a string via SHA-1 hashing)
  53. // GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name,
  54. // and the sample code treats it as a series of bytes, so we do the same here.
  55. //
  56. // Some implementations, such as those found on Windows, treat the name as a
  57. // big-endian UTF16 stream of bytes. If that is desired, the string can be
  58. // encoded as such before being passed to this function.
  59. func NewV5(namespace GUID, name []byte) (GUID, error) {
  60. b := sha1.New()
  61. namespaceBytes := namespace.ToArray()
  62. b.Write(namespaceBytes[:])
  63. b.Write(name)
  64. a := [16]byte{}
  65. copy(a[:], b.Sum(nil))
  66. g := FromArray(a)
  67. g.setVersion(5) // Version 5 means generated from a string.
  68. g.setVariant(VariantRFC4122)
  69. return g, nil
  70. }
  71. func fromArray(b [16]byte, order binary.ByteOrder) GUID {
  72. var g GUID
  73. g.Data1 = order.Uint32(b[0:4])
  74. g.Data2 = order.Uint16(b[4:6])
  75. g.Data3 = order.Uint16(b[6:8])
  76. copy(g.Data4[:], b[8:16])
  77. return g
  78. }
  79. func (g GUID) toArray(order binary.ByteOrder) [16]byte {
  80. b := [16]byte{}
  81. order.PutUint32(b[0:4], g.Data1)
  82. order.PutUint16(b[4:6], g.Data2)
  83. order.PutUint16(b[6:8], g.Data3)
  84. copy(b[8:16], g.Data4[:])
  85. return b
  86. }
  87. // FromArray constructs a GUID from a big-endian encoding array of 16 bytes.
  88. func FromArray(b [16]byte) GUID {
  89. return fromArray(b, binary.BigEndian)
  90. }
  91. // ToArray returns an array of 16 bytes representing the GUID in big-endian
  92. // encoding.
  93. func (g GUID) ToArray() [16]byte {
  94. return g.toArray(binary.BigEndian)
  95. }
  96. // FromWindowsArray constructs a GUID from a Windows encoding array of bytes.
  97. func FromWindowsArray(b [16]byte) GUID {
  98. return fromArray(b, binary.LittleEndian)
  99. }
  100. // ToWindowsArray returns an array of 16 bytes representing the GUID in Windows
  101. // encoding.
  102. func (g GUID) ToWindowsArray() [16]byte {
  103. return g.toArray(binary.LittleEndian)
  104. }
  105. func (g GUID) String() string {
  106. return fmt.Sprintf(
  107. "%08x-%04x-%04x-%04x-%012x",
  108. g.Data1,
  109. g.Data2,
  110. g.Data3,
  111. g.Data4[:2],
  112. g.Data4[2:])
  113. }
  114. // FromString parses a string containing a GUID and returns the GUID. The only
  115. // format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
  116. // format.
  117. func FromString(s string) (GUID, error) {
  118. if len(s) != 36 {
  119. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  120. }
  121. if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
  122. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  123. }
  124. var g GUID
  125. data1, err := strconv.ParseUint(s[0:8], 16, 32)
  126. if err != nil {
  127. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  128. }
  129. g.Data1 = uint32(data1)
  130. data2, err := strconv.ParseUint(s[9:13], 16, 16)
  131. if err != nil {
  132. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  133. }
  134. g.Data2 = uint16(data2)
  135. data3, err := strconv.ParseUint(s[14:18], 16, 16)
  136. if err != nil {
  137. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  138. }
  139. g.Data3 = uint16(data3)
  140. for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} {
  141. v, err := strconv.ParseUint(s[x:x+2], 16, 8)
  142. if err != nil {
  143. return GUID{}, fmt.Errorf("invalid GUID %q", s)
  144. }
  145. g.Data4[i] = uint8(v)
  146. }
  147. return g, nil
  148. }
  149. func (g *GUID) setVariant(v Variant) {
  150. d := g.Data4[0]
  151. switch v {
  152. case VariantNCS:
  153. d = (d & 0x7f)
  154. case VariantRFC4122:
  155. d = (d & 0x3f) | 0x80
  156. case VariantMicrosoft:
  157. d = (d & 0x1f) | 0xc0
  158. case VariantFuture:
  159. d = (d & 0x0f) | 0xe0
  160. case VariantUnknown:
  161. fallthrough
  162. default:
  163. panic(fmt.Sprintf("invalid variant: %d", v))
  164. }
  165. g.Data4[0] = d
  166. }
  167. // Variant returns the GUID variant, as defined in RFC 4122.
  168. func (g GUID) Variant() Variant {
  169. b := g.Data4[0]
  170. if b&0x80 == 0 {
  171. return VariantNCS
  172. } else if b&0xc0 == 0x80 {
  173. return VariantRFC4122
  174. } else if b&0xe0 == 0xc0 {
  175. return VariantMicrosoft
  176. } else if b&0xe0 == 0xe0 {
  177. return VariantFuture
  178. }
  179. return VariantUnknown
  180. }
  181. func (g *GUID) setVersion(v Version) {
  182. g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12)
  183. }
  184. // Version returns the GUID version, as defined in RFC 4122.
  185. func (g GUID) Version() Version {
  186. return Version((g.Data3 & 0xF000) >> 12)
  187. }
  188. // MarshalText returns the textual representation of the GUID.
  189. func (g GUID) MarshalText() ([]byte, error) {
  190. return []byte(g.String()), nil
  191. }
  192. // UnmarshalText takes the textual representation of a GUID, and unmarhals it
  193. // into this GUID.
  194. func (g *GUID) UnmarshalText(text []byte) error {
  195. g2, err := FromString(string(text))
  196. if err != nil {
  197. return err
  198. }
  199. *g = g2
  200. return nil
  201. }