1
// 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.
18
// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
22
// A Version represents a UUID's version.
25
// A Variant represents a UUID's variant.
28
// Constants returned by Variant.
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.
37
const randPoolSize = 16 * 16
40
rander = rand.Reader // random function
43
poolPos = randPoolSize // protected with poolMu
44
pool [randPoolSize]byte // protected with poolMu
47
type invalidLengthError struct{ len int }
49
func (err invalidLengthError) Error() string {
50
return fmt.Sprintf("invalid UUID length: %d", err.len)
53
// IsInvalidLengthError is matcher function for custom error invalidLengthError
54
func IsInvalidLengthError(err error) bool {
55
_, ok := err.(invalidLengthError)
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.
64
func Parse(s string) (UUID, error) {
67
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
70
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
72
if strings.ToLower(s[:9]) != "urn:uuid:" {
73
return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
77
// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
81
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
85
uuid[i], ok = xtob(s[i*2], s[i*2+1])
87
return uuid, errors.New("invalid UUID format")
92
return uuid, invalidLengthError{len(s)}
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")
99
for i, x := range [16]int{
104
24, 26, 28, 30, 32, 34} {
105
v, ok := xtob(s[x], s[x+1])
107
return uuid, errors.New("invalid UUID format")
114
// ParseBytes is like Parse, except it parses a byte slice instead of a string.
115
func ParseBytes(b []byte) (UUID, error) {
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])
124
case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
126
case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
128
for i := 0; i < 32; i += 2 {
129
uuid[i/2], ok = xtob(b[i], b[i+1])
131
return uuid, errors.New("invalid UUID format")
136
return uuid, invalidLengthError{len(b)}
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")
143
for i, x := range [16]int{
148
24, 26, 28, 30, 32, 34} {
149
v, ok := xtob(b[x], b[x+1])
151
return uuid, errors.New("invalid UUID format")
158
// MustParse is like Parse but panics if the string cannot be parsed.
159
// It simplifies safe initialization of global variables holding compiled UUIDs.
160
func MustParse(s string) UUID {
161
uuid, err := Parse(s)
163
panic(`uuid: Parse(` + s + `): ` + err.Error())
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.
170
func FromBytes(b []byte) (uuid UUID, err error) {
171
err = uuid.UnmarshalBinary(b)
175
// Must returns uuid if err is nil and panics otherwise.
176
func Must(uuid UUID, err error) UUID {
183
// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
184
// , or "" if uuid is invalid.
185
func (uuid UUID) String() string {
187
encodeHex(buf[:], uuid)
188
return string(buf[:])
191
// URN returns the RFC 2141 URN form of uuid,
192
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
193
func (uuid UUID) URN() string {
195
copy(buf[:], "urn:uuid:")
196
encodeHex(buf[9:], uuid)
197
return string(buf[:])
200
func encodeHex(dst []byte, uuid UUID) {
201
hex.Encode(dst, uuid[:4])
203
hex.Encode(dst[9:13], uuid[4:6])
205
hex.Encode(dst[14:18], uuid[6:8])
207
hex.Encode(dst[19:23], uuid[8:10])
209
hex.Encode(dst[24:], uuid[10:])
212
// Variant returns the variant encoded in uuid.
213
func (uuid UUID) Variant() Variant {
215
case (uuid[8] & 0xc0) == 0x80:
217
case (uuid[8] & 0xe0) == 0xc0:
219
case (uuid[8] & 0xe0) == 0xe0:
226
// Version returns the version of uuid.
227
func (uuid UUID) Version() Version {
228
return Version(uuid[6] >> 4)
231
func (v Version) String() string {
233
return fmt.Sprintf("BAD_VERSION_%d", v)
235
return fmt.Sprintf("VERSION_%d", v)
238
func (v Variant) String() string {
251
return fmt.Sprintf("BadVariant%d", int(v))
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.
258
// Calling SetRand with nil sets the random number generator to the default
260
func SetRand(r io.Reader) {
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.
273
// Since the pool is stored on the Go heap, this feature may be a bad fit
274
// for security sensitive applications.
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.
279
func EnableRandPool() {
283
// DisableRandPool disables the randomness pool if it was previously
284
// enabled with EnableRandPool.
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.
289
func DisableRandPool() {
291
defer poolMu.Unlock()
293
poolPos = randPoolSize