guid.go 6.1 KB

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