-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid.go
226 lines (178 loc) · 4.37 KB
/
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
package uuid
import (
"bytes"
"crypto/rand"
"database/sql/driver"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
)
type UUID [16]byte
type Version int
const (
V1 Version = 1
V3 Version = 3
V4 Version = 4
V5 Version = 5
V6 Version = 6
V7 Version = 7
V8 Version = 8
)
var (
Nil = UUID{}
Max = UUID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
)
var (
ErrInvalidFormat = errors.New("invalid uuid format")
ErrUnsupportedVersion = errors.New("unsupported uuid version")
)
func Generate(v Version) (UUID, error) {
var id UUID
if err := id.Generate(v); err != nil {
return UUID{}, err
}
return id, nil
}
func (pId *UUID) Generate(v Version) error {
var id UUID
if v == V4 || v == V7 {
if _, err := rand.Read(id[:]); err != nil {
return fmt.Errorf("cannot read random data: %w", err)
}
}
switch v {
case V4:
id[6] = (id[6] & 0x0f) | 0x40 // Version 4
id[8] = (id[8] & 0x3f) | 0x80 // Variant b10
case V7:
var tsdata [8]byte
binary.BigEndian.PutUint64(tsdata[:], uint64(time.Now().UnixMilli()))
copy(id[0:6], tsdata[2:8])
id[6] = (id[6] & 0x0f) | 0x70 // Version 7
id[8] = (id[8] & 0x3f) | 0x80 // Variant b10
default:
return ErrUnsupportedVersion
}
*pId = id
return nil
}
func MustGenerate(v Version) (id UUID) {
if err := id.Generate(v); err != nil {
panic(fmt.Sprintf("cannot generate uuid v%d: %v", v, err))
}
return
}
func (id1 UUID) Equal(id2 UUID) bool {
return bytes.Equal(id1.Bytes(), id2.Bytes())
}
func (id UUID) String() string {
data, _ := id.MarshalText()
return string(data)
}
func (id UUID) Bytes() []byte {
return id[:]
}
func (pId *UUID) Parse(s string) error {
return pId.UnmarshalText([]byte(s))
}
func MustParse(s string) (id UUID) {
if err := id.Parse(s); err != nil {
panic(fmt.Sprintf("invalid uuid %q", s))
}
return id
}
func (id UUID) IsNil() bool {
return bytes.Compare(id.Bytes(), Nil.Bytes()) == 0
}
// encoding.TextMarshaler
func (id UUID) MarshalText() ([]byte, error) {
data := make([]byte, 36)
hex.Encode(data[0:8], id[0:4])
data[8] = '-'
hex.Encode(data[9:13], id[4:6])
data[13] = '-'
hex.Encode(data[14:18], id[6:8])
data[18] = '-'
hex.Encode(data[19:23], id[8:10])
data[23] = '-'
hex.Encode(data[24:36], id[10:16])
return data, nil
}
// encoding.TextUnmarshaler
func (pId *UUID) UnmarshalText(data []byte) error {
var err error
var id UUID
if len(data) != 36 {
return ErrInvalidFormat
}
_, err = hex.Decode(id[0:4], data[0:8])
_, err = hex.Decode(id[4:6], data[9:13])
_, err = hex.Decode(id[6:8], data[14:18])
_, err = hex.Decode(id[8:10], data[19:23])
_, err = hex.Decode(id[10:16], data[24:36])
if err != nil || data[8] != '-' || data[13] != '-' ||
data[18] != '-' || data[23] != '-' {
return ErrInvalidFormat
}
*pId = id
return nil
}
// json.Marshaler
func (id UUID) MarshalJSON() ([]byte, error) {
return json.Marshal(id.String())
}
// json.Unmarshaler
func (pId *UUID) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return ErrInvalidFormat
}
return pId.Parse(s)
}
// database/sql/driver.Valuer
func (id UUID) Value() (driver.Value, error) {
// It is tempting to return a byte slice, but database/sql is a generic
// SQL client. Most developers use text columns to store UUIDs so we
// maximize compatibility.
return id.String(), nil
}
// database/sql.Scanner
func (id *UUID) Scan(value interface{}) error {
switch v := value.(type) {
case string:
return id.Parse(v)
case []byte:
if len(v) != 16 {
return ErrInvalidFormat
}
copy((*id)[:], v)
return nil
default:
return fmt.Errorf("invalid uuid value %#v", v)
}
}
func GenerateV7Zero(t time.Time) UUID {
var id UUID
id.GenerateV7Zero(t)
return id
}
func (id *UUID) GenerateV7Zero(t time.Time) {
// This function generates a UUID v7 with a known time field and all random
// fields set to zero. This is useful to filter ids by time.
*id = [16]byte{}
var tsdata [8]byte
binary.BigEndian.PutUint64(tsdata[:], uint64(t.UnixMilli()))
copy(id[0:6], tsdata[2:8])
id[6] = (id[6] & 0x0f) | 0x70 // Version 7
id[8] = (id[8] & 0x3f) | 0x80 // Variant b10
}
func (id UUID) V7Time() time.Time {
// Casting from uint64 to int64 is safe, the timestamp only uses 6 bytes
var tsdata [8]byte
copy(tsdata[2:8], id[0:6])
return time.UnixMilli(int64(binary.BigEndian.Uint64(tsdata[:])))
}