blob: 60d26bb50c6a9b967aee035449fa700c26bebcbc [file] [log] [blame]
Prince Pereirac1c21d62021-04-22 08:38:15 +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"
15)
16
17// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
18// 4122.
19type UUID [16]byte
20
21// A Version represents a UUID's version.
22type Version byte
23
24// A Variant represents a UUID's variant.
25type Variant byte
26
27// Constants returned by Variant.
28const (
29 Invalid = Variant(iota) // Invalid UUID
30 RFC4122 // The variant specified in RFC4122
31 Reserved // Reserved, NCS backward compatibility.
32 Microsoft // Reserved, Microsoft Corporation backward compatibility.
33 Future // Reserved for future definition.
34)
35
36var rander = rand.Reader // random function
37
38type invalidLengthError struct{ len int }
39
40func (err invalidLengthError) Error() string {
41 return fmt.Sprintf("invalid UUID length: %d", err.len)
42}
43
44// Parse decodes s into a UUID or returns an error. Both the standard UUID
45// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
46// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
47// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
48// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
49func Parse(s string) (UUID, error) {
50 var uuid UUID
51 switch len(s) {
52 // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
53 case 36:
54
55 // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
56 case 36 + 9:
57 if strings.ToLower(s[:9]) != "urn:uuid:" {
58 return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
59 }
60 s = s[9:]
61
62 // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
63 case 36 + 2:
64 s = s[1:]
65
66 // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
67 case 32:
68 var ok bool
69 for i := range uuid {
70 uuid[i], ok = xtob(s[i*2], s[i*2+1])
71 if !ok {
72 return uuid, errors.New("invalid UUID format")
73 }
74 }
75 return uuid, nil
76 default:
77 return uuid, invalidLengthError{len(s)}
78 }
79 // s is now at least 36 bytes long
80 // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
81 if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
82 return uuid, errors.New("invalid UUID format")
83 }
84 for i, x := range [16]int{
85 0, 2, 4, 6,
86 9, 11,
87 14, 16,
88 19, 21,
89 24, 26, 28, 30, 32, 34} {
90 v, ok := xtob(s[x], s[x+1])
91 if !ok {
92 return uuid, errors.New("invalid UUID format")
93 }
94 uuid[i] = v
95 }
96 return uuid, nil
97}
98
99// ParseBytes is like Parse, except it parses a byte slice instead of a string.
100func ParseBytes(b []byte) (UUID, error) {
101 var uuid UUID
102 switch len(b) {
103 case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
104 case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
105 if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
106 return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
107 }
108 b = b[9:]
109 case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
110 b = b[1:]
111 case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
112 var ok bool
113 for i := 0; i < 32; i += 2 {
114 uuid[i/2], ok = xtob(b[i], b[i+1])
115 if !ok {
116 return uuid, errors.New("invalid UUID format")
117 }
118 }
119 return uuid, nil
120 default:
121 return uuid, invalidLengthError{len(b)}
122 }
123 // s is now at least 36 bytes long
124 // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
125 if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
126 return uuid, errors.New("invalid UUID format")
127 }
128 for i, x := range [16]int{
129 0, 2, 4, 6,
130 9, 11,
131 14, 16,
132 19, 21,
133 24, 26, 28, 30, 32, 34} {
134 v, ok := xtob(b[x], b[x+1])
135 if !ok {
136 return uuid, errors.New("invalid UUID format")
137 }
138 uuid[i] = v
139 }
140 return uuid, nil
141}
142
143// MustParse is like Parse but panics if the string cannot be parsed.
144// It simplifies safe initialization of global variables holding compiled UUIDs.
145func MustParse(s string) UUID {
146 uuid, err := Parse(s)
147 if err != nil {
148 panic(`uuid: Parse(` + s + `): ` + err.Error())
149 }
150 return uuid
151}
152
153// FromBytes creates a new UUID from a byte slice. Returns an error if the slice
154// does not have a length of 16. The bytes are copied from the slice.
155func FromBytes(b []byte) (uuid UUID, err error) {
156 err = uuid.UnmarshalBinary(b)
157 return uuid, err
158}
159
160// Must returns uuid if err is nil and panics otherwise.
161func Must(uuid UUID, err error) UUID {
162 if err != nil {
163 panic(err)
164 }
165 return uuid
166}
167
168// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
169// , or "" if uuid is invalid.
170func (uuid UUID) String() string {
171 var buf [36]byte
172 encodeHex(buf[:], uuid)
173 return string(buf[:])
174}
175
176// URN returns the RFC 2141 URN form of uuid,
177// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
178func (uuid UUID) URN() string {
179 var buf [36 + 9]byte
180 copy(buf[:], "urn:uuid:")
181 encodeHex(buf[9:], uuid)
182 return string(buf[:])
183}
184
185func encodeHex(dst []byte, uuid UUID) {
186 hex.Encode(dst, uuid[:4])
187 dst[8] = '-'
188 hex.Encode(dst[9:13], uuid[4:6])
189 dst[13] = '-'
190 hex.Encode(dst[14:18], uuid[6:8])
191 dst[18] = '-'
192 hex.Encode(dst[19:23], uuid[8:10])
193 dst[23] = '-'
194 hex.Encode(dst[24:], uuid[10:])
195}
196
197// Variant returns the variant encoded in uuid.
198func (uuid UUID) Variant() Variant {
199 switch {
200 case (uuid[8] & 0xc0) == 0x80:
201 return RFC4122
202 case (uuid[8] & 0xe0) == 0xc0:
203 return Microsoft
204 case (uuid[8] & 0xe0) == 0xe0:
205 return Future
206 default:
207 return Reserved
208 }
209}
210
211// Version returns the version of uuid.
212func (uuid UUID) Version() Version {
213 return Version(uuid[6] >> 4)
214}
215
216func (v Version) String() string {
217 if v > 15 {
218 return fmt.Sprintf("BAD_VERSION_%d", v)
219 }
220 return fmt.Sprintf("VERSION_%d", v)
221}
222
223func (v Variant) String() string {
224 switch v {
225 case RFC4122:
226 return "RFC4122"
227 case Reserved:
228 return "Reserved"
229 case Microsoft:
230 return "Microsoft"
231 case Future:
232 return "Future"
233 case Invalid:
234 return "Invalid"
235 }
236 return fmt.Sprintf("BadVariant%d", int(v))
237}
238
239// SetRand sets the random number generator to r, which implements io.Reader.
240// If r.Read returns an error when the package requests random data then
241// a panic will be issued.
242//
243// Calling SetRand with nil sets the random number generator to the default
244// generator.
245func SetRand(r io.Reader) {
246 if r == nil {
247 rander = rand.Reader
248 return
249 }
250 rander = r
251}