...
1
2
3
4
5 package uuid
6
7 import (
8 "bytes"
9 "crypto/rand"
10 "encoding/hex"
11 "io"
12
13 guuid "github.com/google/uuid"
14 )
15
16
17 type Array [16]byte
18
19
20 func (uuid Array) UUID() UUID {
21 return uuid[:]
22 }
23
24
25
26 func (uuid Array) String() string {
27 return guuid.UUID(uuid).String()
28 }
29
30
31
32 type UUID []byte
33
34
35 type Version = guuid.Version
36
37
38 type Variant = guuid.Variant
39
40
41 const (
42 Invalid = guuid.Invalid
43 RFC4122 = guuid.RFC4122
44 Reserved = guuid.Reserved
45 Microsoft = guuid.Microsoft
46 Future = guuid.Future
47 )
48
49 var rander = rand.Reader
50
51
52
53 func New() string {
54 return NewRandom().String()
55 }
56
57
58
59 func Parse(s string) UUID {
60 gu, err := guuid.Parse(s)
61 if err == nil {
62 return gu[:]
63 }
64 return nil
65 }
66
67
68 func ParseBytes(b []byte) (UUID, error) {
69 gu, err := guuid.ParseBytes(b)
70 if err == nil {
71 return gu[:], nil
72 }
73 return nil, err
74 }
75
76
77 func Equal(uuid1, uuid2 UUID) bool {
78 return bytes.Equal(uuid1, uuid2)
79 }
80
81
82
83 func (uuid UUID) Array() Array {
84 if len(uuid) != 16 {
85 panic("invalid uuid")
86 }
87 var a Array
88 copy(a[:], uuid)
89 return a
90 }
91
92
93
94 func (uuid UUID) String() string {
95 if len(uuid) != 16 {
96 return ""
97 }
98 var buf [36]byte
99 encodeHex(buf[:], uuid)
100 return string(buf[:])
101 }
102
103
104
105 func (uuid UUID) URN() string {
106 if len(uuid) != 16 {
107 return ""
108 }
109 var buf [36 + 9]byte
110 copy(buf[:], "urn:uuid:")
111 encodeHex(buf[9:], uuid)
112 return string(buf[:])
113 }
114
115 func encodeHex(dst []byte, uuid UUID) {
116 hex.Encode(dst[:], uuid[:4])
117 dst[8] = '-'
118 hex.Encode(dst[9:13], uuid[4:6])
119 dst[13] = '-'
120 hex.Encode(dst[14:18], uuid[6:8])
121 dst[18] = '-'
122 hex.Encode(dst[19:23], uuid[8:10])
123 dst[23] = '-'
124 hex.Encode(dst[24:], uuid[10:])
125 }
126
127
128
129 func (uuid UUID) Variant() Variant {
130 if len(uuid) != 16 {
131 return Invalid
132 }
133 switch {
134 case (uuid[8] & 0xc0) == 0x80:
135 return RFC4122
136 case (uuid[8] & 0xe0) == 0xc0:
137 return Microsoft
138 case (uuid[8] & 0xe0) == 0xe0:
139 return Future
140 default:
141 return Reserved
142 }
143 }
144
145
146
147 func (uuid UUID) Version() (Version, bool) {
148 if len(uuid) != 16 {
149 return 0, false
150 }
151 return Version(uuid[6] >> 4), true
152 }
153
154
155
156
157
158
159
160 func SetRand(r io.Reader) {
161 guuid.SetRand(r)
162 }
163
View as plain text