blob: a57207aeb6fd844cc3265727d406a3986ec5d6ff [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001// Copyright 2018 Google Inc. 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
5package uuid
6
7import (
8 "bytes"
9 "crypto/rand"
10 "encoding/hex"
11 "errors"
12 "fmt"
13 "io"
14 "strings"
khenaidoo7d3c5582021-08-11 18:09:44 -040015 "sync"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000016)
17
18// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
19// 4122.
20type UUID [16]byte
21
22// A Version represents a UUID's version.
23type Version byte
24
25// A Variant represents a UUID's variant.
26type Variant byte
27
28// Constants returned by Variant.
29const (
30 Invalid = Variant(iota) // Invalid UUID
31 RFC4122 // The variant specified in RFC4122
32 Reserved // Reserved, NCS backward compatibility.
33 Microsoft // Reserved, Microsoft Corporation backward compatibility.
34 Future // Reserved for future definition.
35)
36
khenaidoo7d3c5582021-08-11 18:09:44 -040037const randPoolSize = 16 * 16
38
39var (
40 rander = rand.Reader // random function
41 poolEnabled = false
42 poolMu sync.Mutex
43 poolPos = randPoolSize // protected with poolMu
44 pool [randPoolSize]byte // protected with poolMu
45)
46
47type invalidLengthError struct{ len int }
48
49func (err invalidLengthError) Error() string {
50 return fmt.Sprintf("invalid UUID length: %d", err.len)
51}
52
53// IsInvalidLengthError is matcher function for custom error invalidLengthError
54func IsInvalidLengthError(err error) bool {
55 _, ok := err.(invalidLengthError)
56 return ok
57}
Holger Hildebrandtfa074992020-03-27 15:42:06 +000058
59// Parse decodes s into a UUID or returns an error. Both the standard UUID
60// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
61// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
62// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
63// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
64func Parse(s string) (UUID, error) {
65 var uuid UUID
66 switch len(s) {
67 // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
68 case 36:
69
70 // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
71 case 36 + 9:
72 if strings.ToLower(s[:9]) != "urn:uuid:" {
73 return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
74 }
75 s = s[9:]
76
77 // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
78 case 36 + 2:
79 s = s[1:]
80
81 // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
82 case 32:
83 var ok bool
84 for i := range uuid {
85 uuid[i], ok = xtob(s[i*2], s[i*2+1])
86 if !ok {
87 return uuid, errors.New("invalid UUID format")
88 }
89 }
90 return uuid, nil
91 default:
khenaidoo7d3c5582021-08-11 18:09:44 -040092 return uuid, invalidLengthError{len(s)}
Holger Hildebrandtfa074992020-03-27 15:42:06 +000093 }
94 // s is now at least 36 bytes long
95 // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
96 if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
97 return uuid, errors.New("invalid UUID format")
98 }
99 for i, x := range [16]int{
100 0, 2, 4, 6,
101 9, 11,
102 14, 16,
103 19, 21,
104 24, 26, 28, 30, 32, 34} {
105 v, ok := xtob(s[x], s[x+1])
106 if !ok {
107 return uuid, errors.New("invalid UUID format")
108 }
109 uuid[i] = v
110 }
111 return uuid, nil
112}
113
114// ParseBytes is like Parse, except it parses a byte slice instead of a string.
115func ParseBytes(b []byte) (UUID, error) {
116 var uuid UUID
117 switch len(b) {
118 case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
119 case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
120 if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
121 return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
122 }
123 b = b[9:]
124 case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
125 b = b[1:]
126 case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
127 var ok bool
128 for i := 0; i < 32; i += 2 {
129 uuid[i/2], ok = xtob(b[i], b[i+1])
130 if !ok {
131 return uuid, errors.New("invalid UUID format")
132 }
133 }
134 return uuid, nil
135 default:
khenaidoo7d3c5582021-08-11 18:09:44 -0400136 return uuid, invalidLengthError{len(b)}
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000137 }
138 // s is now at least 36 bytes long
139 // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
140 if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
141 return uuid, errors.New("invalid UUID format")
142 }
143 for i, x := range [16]int{
144 0, 2, 4, 6,
145 9, 11,
146 14, 16,
147 19, 21,
148 24, 26, 28, 30, 32, 34} {
149 v, ok := xtob(b[x], b[x+1])
150 if !ok {
151 return uuid, errors.New("invalid UUID format")
152 }
153 uuid[i] = v
154 }
155 return uuid, nil
156}
157
158// MustParse is like Parse but panics if the string cannot be parsed.
159// It simplifies safe initialization of global variables holding compiled UUIDs.
160func MustParse(s string) UUID {
161 uuid, err := Parse(s)
162 if err != nil {
163 panic(`uuid: Parse(` + s + `): ` + err.Error())
164 }
165 return uuid
166}
167
168// FromBytes creates a new UUID from a byte slice. Returns an error if the slice
169// does not have a length of 16. The bytes are copied from the slice.
170func FromBytes(b []byte) (uuid UUID, err error) {
171 err = uuid.UnmarshalBinary(b)
172 return uuid, err
173}
174
175// Must returns uuid if err is nil and panics otherwise.
176func Must(uuid UUID, err error) UUID {
177 if err != nil {
178 panic(err)
179 }
180 return uuid
181}
182
183// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
184// , or "" if uuid is invalid.
185func (uuid UUID) String() string {
186 var buf [36]byte
187 encodeHex(buf[:], uuid)
188 return string(buf[:])
189}
190
191// URN returns the RFC 2141 URN form of uuid,
192// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
193func (uuid UUID) URN() string {
194 var buf [36 + 9]byte
195 copy(buf[:], "urn:uuid:")
196 encodeHex(buf[9:], uuid)
197 return string(buf[:])
198}
199
200func encodeHex(dst []byte, uuid UUID) {
201 hex.Encode(dst, uuid[:4])
202 dst[8] = '-'
203 hex.Encode(dst[9:13], uuid[4:6])
204 dst[13] = '-'
205 hex.Encode(dst[14:18], uuid[6:8])
206 dst[18] = '-'
207 hex.Encode(dst[19:23], uuid[8:10])
208 dst[23] = '-'
209 hex.Encode(dst[24:], uuid[10:])
210}
211
212// Variant returns the variant encoded in uuid.
213func (uuid UUID) Variant() Variant {
214 switch {
215 case (uuid[8] & 0xc0) == 0x80:
216 return RFC4122
217 case (uuid[8] & 0xe0) == 0xc0:
218 return Microsoft
219 case (uuid[8] & 0xe0) == 0xe0:
220 return Future
221 default:
222 return Reserved
223 }
224}
225
226// Version returns the version of uuid.
227func (uuid UUID) Version() Version {
228 return Version(uuid[6] >> 4)
229}
230
231func (v Version) String() string {
232 if v > 15 {
233 return fmt.Sprintf("BAD_VERSION_%d", v)
234 }
235 return fmt.Sprintf("VERSION_%d", v)
236}
237
238func (v Variant) String() string {
239 switch v {
240 case RFC4122:
241 return "RFC4122"
242 case Reserved:
243 return "Reserved"
244 case Microsoft:
245 return "Microsoft"
246 case Future:
247 return "Future"
248 case Invalid:
249 return "Invalid"
250 }
251 return fmt.Sprintf("BadVariant%d", int(v))
252}
253
254// SetRand sets the random number generator to r, which implements io.Reader.
255// If r.Read returns an error when the package requests random data then
256// a panic will be issued.
257//
258// Calling SetRand with nil sets the random number generator to the default
259// generator.
260func SetRand(r io.Reader) {
261 if r == nil {
262 rander = rand.Reader
263 return
264 }
265 rander = r
266}
khenaidoo7d3c5582021-08-11 18:09:44 -0400267
268// EnableRandPool enables internal randomness pool used for Random
269// (Version 4) UUID generation. The pool contains random bytes read from
270// the random number generator on demand in batches. Enabling the pool
271// may improve the UUID generation throughput significantly.
272//
273// Since the pool is stored on the Go heap, this feature may be a bad fit
274// for security sensitive applications.
275//
276// Both EnableRandPool and DisableRandPool are not thread-safe and should
277// only be called when there is no possibility that New or any other
278// UUID Version 4 generation function will be called concurrently.
279func EnableRandPool() {
280 poolEnabled = true
281}
282
283// DisableRandPool disables the randomness pool if it was previously
284// enabled with EnableRandPool.
285//
286// Both EnableRandPool and DisableRandPool are not thread-safe and should
287// only be called when there is no possibility that New or any other
288// UUID Version 4 generation function will be called concurrently.
289func DisableRandPool() {
290 poolEnabled = false
291 defer poolMu.Unlock()
292 poolMu.Lock()
293 poolPos = randPoolSize
294}