Debian Codegraph @

uuid.go

raw
1 // This package provides RFC4122 and DCE 1.1 UUIDs.
2 //
3 // Use NewV1, NewV2, NewV3, NewV4, NewV5, for generating new UUIDs.
4 //
5 // Use New([]byte), NewHex(string), and Parse(string) for
6 // creating UUIDs from existing data.
7 //
8 // If you have a []byte you can simply cast it to the Uuid type.
9 //
10 // The original version was from Krzysztof Kowalik <[email protected]>
11 // Unfortunately, that version was non compliant with RFC4122.
12 //
13 // The package has since been redesigned.
14 //
15 // The example code in the specification was also used as reference
16 // for design.
17 //
18 // Copyright (C) 2016 [email protected] 2016 MIT licence
19 package uuid
20
21 import (
22 "bytes"
23 "crypto/md5"
24 "crypto/sha1"
25 "encoding/binary"
26 "encoding/hex"
27 "errors"
28 "hash"
29 "log"
30 "regexp"
31 )
32
33 const (
34 Nil Immutable = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
35
36 // The following standard UUIDs are for use with V3 or V5 UUIDs.
37 NameSpaceDNS Immutable = "k\xa7\xb8\x10\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8"
38 NameSpaceURL Immutable = "k\xa7\xb8\x11\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8"
39 NameSpaceOID Immutable = "k\xa7\xb8\x12\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8"
40 NameSpaceX500 Immutable = "k\xa7\xb8\x14\x9d\xad\x11р\xb4\x00\xc0O\xd40\xc8"
41 )
42
43 type Domain uint8
44
45 const (
46 DomainUser Domain = iota + 1
47 DomainGroup
48 )
49
50 // UUID is the common interface implemented by all UUIDs
51 type UUID interface {
52
53 // Bytes retrieves the bytes from the underlying UUID
54 Bytes() []byte
55
56 // Size is the length of the underlying UUID implementation
57 Size() int
58
59 // String should return the canonical UUID representation, or the a
60 // given uuid.Format
61 String() string
62
63 // Variant returns the UUID implementation variant
64 Variant() uint8
65
66 // Version returns the version number of the algorithm used to generate
67 // the UUID.
68 Version() Version
69 }
70
71 // New creates a UUID from a slice of bytes.
72 func New(pData []byte) Uuid {
73 o := array{}
74 o.unmarshal(pData)
75 return o[:]
76 }
77
78 // NewHex creates a UUID from a hex string
79 // Will panic if hex string is invalid use Parse otherwise.
80 func NewHex(pUuid string) Uuid {
81 return Uuid(fromHex(pUuid))
82 }
83
84 const (
85 // Pattern used to parse string representation of the UUID.
86 // Current one allows to parse string where only one opening
87 // or closing bracket or any of the hyphens are optional.
88 // It is only used to extract the main bytes to create a UUID,
89 // so these imperfections are of no consequence.
90 hexPattern = `^(urn\:uuid\:)?[\{\(\[]?([[:xdigit:]]{8})-?([[:xdigit:]]{4})-?([1-5][[:xdigit:]]{3})-?([[:xdigit:]]{4})-?([[:xdigit:]]{12})[\]\}\)]?$`
91 )
92
93 var (
94 parseUUIDRegex = regexp.MustCompile(hexPattern)
95 )
96
97 // Parse creates a UUID from a valid string representation.
98 // Accepts UUID string in following formats:
99 // 6ba7b8149dad11d180b400c04fd430c8
100 // 6ba7b814-9dad-11d1-80b4-00c04fd430c8
101 // {6ba7b814-9dad-11d1-80b4-00c04fd430c8}
102 // urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8
103 // [6ba7b814-9dad-11d1-80b4-00c04fd430c8]
104 // (6ba7b814-9dad-11d1-80b4-00c04fd430c8)
105 //
106 func Parse(pUuid string) (Uuid, error) {
107 id, err := parse(pUuid)
108 return Uuid(id), err
109 }
110
111 func parse(pUuid string) ([]byte, error) {
112 md := parseUUIDRegex.FindStringSubmatch(pUuid)
113 if md == nil {
114 return nil, errors.New("uuid.Parse: invalid string format this is probably not a UUID")
115 }
116 return fromHex(md[2] + md[3] + md[4] + md[5] + md[6]), nil
117 }
118
119 func fromHex(pUuid string) []byte {
120 bytes, err := hex.DecodeString(pUuid)
121 if err != nil {
122 panic(err)
123 }
124 return bytes
125 }
126
127 // NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and
128 // node ID.
129 func NewV1() Uuid {
130 return generator.NewV1()
131 }
132
133 // NewV2 generates a new DCE Security version UUID based on a 60 bit timestamp,
134 // node id and POSIX UID.
135 func NewV2(pDomain Domain) Uuid {
136 return generator.NewV2(pDomain)
137 }
138
139 // NewV3 generates a new RFC4122 version 3 UUID based on the MD5 hash on a
140 // namespace UUID and any type which implements the UniqueName interface
141 // for the name. For strings and slices cast to a Name type
142 func NewV3(pNamespace UUID, pNames ...UniqueName) Uuid {
143 o := array{}
144 copy(o[:], digest(md5.New(), pNamespace.Bytes(), pNames...))
145 o.setRFC4122Version(3)
146 return o[:]
147 }
148
149 // NewV4 generates a new RFC4122 version 4 UUID a cryptographically secure
150 // random UUID.
151 func NewV4() Uuid {
152 o, err := v4()
153 if err == nil {
154 return o[:]
155 }
156 generator.err = err
157 log.Printf("uuid.V4: There was an error getting random bytes [%s]\n", err)
158 if ok := generator.HandleError(err); ok {
159 o, err = v4()
160 if err == nil {
161 return o[:]
162 }
163 generator.err = err
164 }
165 return nil
166 }
167
168 func v4() (o array, err error) {
169 generator.err = nil
170 _, err = generator.Random(o[:])
171 o.setRFC4122Version(4)
172 return
173 }
174
175 // NewV5 generates an RFC4122 version 5 UUID based on the SHA-1 hash of a
176 // namespace UUID and a unique name.
177 func NewV5(pNamespace UUID, pNames ...UniqueName) Uuid {
178 o := array{}
179 copy(o[:], digest(sha1.New(), pNamespace.Bytes(), pNames...))
180 o.setRFC4122Version(5)
181 return o[:]
182 }
183
184 func digest(pHash hash.Hash, pName []byte, pNames ...UniqueName) []byte {
185 for _, v := range pNames {
186 pName = append(pName, v.String()...)
187 }
188 pHash.Write(pName)
189 return pHash.Sum(nil)
190 }
191
192 // Compare returns an integer comparing two UUIDs lexicographically.
193 // The result will be 0 if pId==pId2, -1 if pId < pId2, and +1 if pId > pId2.
194 // A nil argument is equivalent to the Nil UUID.
195 func Compare(pId, pId2 UUID) int {
196
197 var b1, b2 []byte
198
199 if pId == nil {
200 b1 = []byte(Nil)
201 } else {
202 b1 = pId.Bytes()
203 }
204
205 if pId2 == nil {
206 b2 = []byte(Nil)
207 } else {
208 b2 = pId2.Bytes()
209 }
210
211 tl1 := binary.BigEndian.Uint32(b1[:4])
212 tl2 := binary.BigEndian.Uint32(b2[:4])
213
214 if tl1 != tl2 {
215 if tl1 < tl2 {
216 return -1
217 } else {
218 return 1
219 }
220 }
221
222 m1 := binary.BigEndian.Uint16(b1[4:6])
223 m2 := binary.BigEndian.Uint16(b2[4:6])
224
225 if m1 != m2 {
226 if m1 < m2 {
227 return -1
228 } else {
229 return 1
230 }
231 }
232
233 m1 = binary.BigEndian.Uint16(b1[6:8])
234 m2 = binary.BigEndian.Uint16(b2[6:8])
235
236 if m1 != m2 {
237 if m1 < m2 {
238 return -1
239 } else {
240 return 1
241 }
242 }
243
244 return bytes.Compare(b1[8:], b2[8:])
245 }
246
247 // Compares whether each UUID is the same
248 func Equal(p1, p2 UUID) bool {
249 return bytes.Equal(p1.Bytes(), p2.Bytes())
250 }
251
252 // Name is a string which implements UniqueName and satisfies the Stringer
253 // interface. V3 and V5 UUIDs use this for hashing values together to produce
254 // UUIDs based on a NameSpace.
255 type Name string
256
257 // String returns the uuid.Name as a string.
258 func (o Name) String() string {
259 return string(o)
260 }
261
262 // UniqueName is a Stinger interface made for easy passing of any Stringer type
263 // into a Hashable UUID.
264 type UniqueName interface {
265 // Many go types implement this method for use with printing
266 // Will convert the current type to its native string format
267 String() string
268 }