-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgt_uuid.go
265 lines (221 loc) · 6.14 KB
/
gt_uuid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package gt
import (
"crypto/rand"
"database/sql/driver"
"encoding/hex"
"fmt"
"io"
)
/*
Creates a random UUID using `gt.ReadUuid` and "crypto/rand". Panics if random
bytes can't be read.
*/
func RandomUuid() Uuid {
val, err := ReadUuid(rand.Reader)
try(err)
return val
}
// Creates a UUID (version 4 variant 1) from bytes from the provided reader.
func ReadUuid(src io.Reader) (val Uuid, err error) {
_, err = io.ReadFull(src, val[:])
if err != nil {
err = fmt.Errorf(`[gt] failed to read random bytes for UUID: %w`, err)
return
}
val.setVersion()
return
}
/*
Shortcut: parses successfully or panics. Should be used only in root scope. When
error handling is relevant, use `.Parse`.
*/
func ParseUuid(src string) (val Uuid) {
try(val.Parse(src))
return
}
/*
Simple UUID implementation. Features:
* Reversible encoding/decoding in text.
* Reversible encoding/decoding in JSON.
* Reversible encoding/decoding in SQL.
* Text encoding uses simplified format without dashes.
* Text decoding supports formats with and without dashes, case-insensitive.
Differences from "github.com/google/uuid".UUID:
* Text encoding uses simplified format without dashes.
* Text decoding supports only simplified and canonical format.
* Supports only version 4 (random except for a few bits).
When dealing with databases, it's highly recommended to use `NullUuid` instead.
*/
type Uuid [UuidLen]byte
var (
_ = Encodable(Uuid{})
_ = Decodable((*Uuid)(nil))
)
// Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.
func (self Uuid) IsZero() bool { return self == Uuid{} }
// Implement `gt.Nullable`. Always `false`.
func (self Uuid) IsNull() bool { return false }
// Implement `gt.Getter`, returning `[16]byte` understood by many DB drivers.
func (self Uuid) Get() any { return [UuidLen]byte(self) }
// Implement `gt.Setter`, using `.Scan`. Panics on error.
func (self *Uuid) Set(src any) { try(self.Scan(src)) }
// Implement `gt.Zeroer`, zeroing the receiver.
func (self *Uuid) Zero() {
if self != nil {
*self = Uuid{}
}
}
/*
Implement `fmt.Stringer`, returning a simplified text representation: lowercase
without dashes.
*/
func (self Uuid) String() string {
return bytesString(self.AppendTo(nil))
}
/*
Implement `gt.Parser`, parsing a valid UUID representation. Supports the short
format without dashes and the canonical format with dashes. Parsing is
case-insensitive.
*/
func (self *Uuid) Parse(src string) (err error) {
defer errParse(&err, src, `UUID`)
switch len(src) {
case 32:
return self.maybeSet(uuidParseSimple(src))
case 36:
return self.maybeSet(uuidParseCanon(src))
default:
return errUnrecLength
}
}
// Implement `gt.AppenderTo`, using the same representation as `.String`.
func (self Uuid) AppendTo(buf []byte) []byte {
buf = append(buf, uuidStrZero[:]...)
hex.Encode(buf[len(buf)-len(uuidStrZero):], self[:])
return buf
}
// Implement `encoding.TextMarhaler`, using the same representation as `.String`.
func (self Uuid) MarshalText() ([]byte, error) {
return self.AppendTo(nil), nil
}
// Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.
func (self *Uuid) UnmarshalText(src []byte) error {
return self.Parse(bytesString(src))
}
// Implement `json.Marshaler`, using the same representation as `.String`.
func (self Uuid) MarshalJSON() ([]byte, error) {
var buf [UuidStrLen + 2]byte
buf[0] = '"'
hex.Encode(buf[1:len(buf)-1], self[:])
buf[len(buf)-1] = '"'
return buf[:], nil
}
// Implement `json.Unmarshaler`, using the same algorithm as `.Parse`.
func (self *Uuid) UnmarshalJSON(src []byte) error {
if isJsonStr(src) {
return self.UnmarshalText(cutJsonStr(src))
}
return errJsonString(src, self)
}
// Implement `driver.Valuer`, using `.Get`.
func (self Uuid) Value() (driver.Value, error) { return self.Get(), nil }
/*
Implement `sql.Scanner`, converting an arbitrary input to `gt.Uuid` and
modifying the receiver. Acceptable inputs:
* `string` -> use `.Parse`
* `[]byte` -> use `.UnmarshalText`
* `[16]byte` -> assign
* `gt.Uuid` -> assign
* `gt.NullUuid` -> assign
* `gt.Getter` -> scan underlying value
*/
func (self *Uuid) Scan(src any) error {
switch src := src.(type) {
case string:
return self.Parse(src)
case []byte:
return self.UnmarshalText(src)
case [UuidLen]byte:
*self = Uuid(src)
return nil
case Uuid:
*self = src
return nil
case NullUuid:
*self = Uuid(src)
return nil
default:
val, ok := get(src)
if ok {
return self.Scan(val)
}
return errScanType(self, src)
}
}
// Equivalent to `a.String() < b.String()`. Useful for sorting.
func (self Uuid) Less(other Uuid) bool {
for ind := range self {
if self[ind] < other[ind] {
return true
}
if self[ind] > other[ind] {
return false
}
}
return false
}
// Reminder: https://en.wikipedia.org/wiki/Universally_unique_identifier
func (self *Uuid) setVersion() {
// Version 4.
(*self)[6] = ((*self)[6] & 0b00001111) | 0b01000000
// Variant 1.
(*self)[8] = ((*self)[8] & 0b00111111) | 0b10000000
}
func (self *Uuid) maybeSet(val Uuid, err error) error {
if err == nil {
*self = val
}
return err
}
func uuidParseSimple(src string) (val Uuid, err error) {
if len(src) != 32 {
err = errLengthMismatch
return
}
_, err = hex.Decode(val[:], stringBytesUnsafe(src))
return
}
func uuidParseCanon(src string) (val Uuid, err error) {
if len(src) != 36 {
err = errLengthMismatch
return
}
if !(src[8] == '-' && src[13] == '-' && src[18] == '-' && src[23] == '-') {
err = errFormatMismatch
return
}
for ind, pair := range uuidGroups {
char, ok := hexDecode(src[pair[0]], src[pair[1]])
if !ok {
err = errInvalidCharAt(src, pair[0])
return
}
val[ind] = char
}
return
}
/*
Implement `fmt.GoStringer`, returning valid Go code that constructs this value.
The rendered code is biased for readability over performance: it parses a
string instead of using a literal constructor.
*/
func (self Uuid) GoString() string {
const fun = `gt.ParseUuid`
var arr [len(fun) + len("(`") + len(uuidStrZero) + len("`)")]byte
buf := arr[:0]
buf = append(buf, fun...)
buf = append(buf, "(`"...)
buf = self.AppendTo(buf)
buf = append(buf, "`)"...)
return string(buf)
}