This repository has been archived by the owner on Nov 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid.go
273 lines (221 loc) · 5.04 KB
/
id.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
266
267
268
269
270
271
272
273
package tlog
import (
"bytes"
"encoding/hex"
"fmt"
"math/rand"
"sync"
"time"
"github.com/nikandfor/errors"
"github.com/nikandfor/tlog/low"
)
type (
ID [16]byte
// ShortIDError is an ID parsing error.
ShortIDError struct {
Bytes int // Bytes successfully parsed
}
concurrentRand struct {
mu sync.Mutex
r *rand.Rand
}
)
var rnd = &concurrentRand{r: rand.New(rand.NewSource(time.Now().UnixNano()))} //nolint:gosec
// String returns short string representation.
//
// It's not supposed to be able to recover it back to the same value as it was.
func (id ID) String() string {
var b [8]byte
id.FormatTo(b[:], 'v')
return string(b[:])
}
// StringFull returns full id represented as string.
func (id ID) StringFull() string {
var b [32]byte
id.FormatTo(b[:], 'v')
return string(b[:])
}
// IDFromBytes decodes ID from bytes slice.
//
// If byte slice is shorter than type length result is returned as is and ShortIDError as error value.
// You may use result if you expected short ID prefix.
func IDFromBytes(b []byte) (id ID, err error) {
n := copy(id[:], b)
if n < len(id) {
err = ShortIDError{Bytes: n}
}
return
}
// IDFromString parses ID from string.
//
// If parsed string is shorter than type length result is returned as is and ShortIDError as error value.
// You may use result if you expected short ID prefix (profuced by ID.String, for example).
func IDFromString(s string) (id ID, err error) {
if "________________________________"[:len(s)] == s {
return
}
var i int
var c byte
for ; i < len(s); i++ {
switch {
case '0' <= s[i] && s[i] <= '9':
c = s[i] - '0'
case 'a' <= s[i] && s[i] <= 'f':
c = s[i] - 'a' + 10
default:
err = hex.InvalidByteError(s[i])
return
}
if i&1 == 0 {
c <<= 4
}
id[i>>1] |= c
}
if i < 2*len(id) {
err = ShortIDError{Bytes: i / 2}
}
return
}
// IDFromStringAsBytes is the same as IDFromString. It avoids alloc in IDFromString(string(b)).
func IDFromStringAsBytes(s []byte) (id ID, err error) {
if bytes.Equal([]byte("________________________________")[:len(s)], s) {
return
}
n, err := hex.Decode(id[:], s)
if err != nil {
return
}
if n < len(id) {
return id, ShortIDError{Bytes: n}
}
return id, nil
}
// ShouldID wraps IDFrom* call and skips error if any.
func ShouldID(id ID, err error) ID {
return id
}
// MustID wraps IDFrom* call and panics if error occurred.
func MustID(id ID, err error) ID {
if err != nil {
panic(err)
}
return id
}
// Error is an error interface implementation.
func (e ShortIDError) Error() string {
return fmt.Sprintf("too short id: %d bytes, wanted %d", e.Bytes, len(ID{}))
}
// Format is fmt.Formatter interface implementation.
// It supports width. '+' flag sets width to full ID length.
func (id ID) Format(s fmt.State, c rune) {
var buf0 [32]byte
buf := low.NoEscapeBuffer(buf0[:])
w := 8
if W, ok := s.Width(); ok {
w = W
}
if s.Flag('+') {
w = 2 * len(id)
}
id.FormatTo(buf[:w], c)
_, _ = s.Write(buf[:w])
}
// FormatTo is alloc free Format alternative.
func (id ID) FormatTo(b []byte, f rune) {
if id == (ID{}) {
if f == 'v' || f == 'V' {
copy(b, "________________________________")
} else {
copy(b, "00000000000000000000000000000000")
}
return
}
const digitsx = "0123456789abcdef"
const digitsX = "0123456789ABCDEF"
dg := digitsx
if f == 'X' || f == 'V' {
dg = digitsX
}
m := len(b)
if 2*len(id) < m {
m = 2 * len(id)
}
ji := 0
for j := 0; j+1 < m; j += 2 {
b[j] = dg[id[ji]>>4]
b[j+1] = dg[id[ji]&0xf]
ji++
}
if m&1 == 1 {
b[m-1] = dg[id[m>>1]>>4]
}
}
func (id ID) MarshalJSON() ([]byte, error) {
b := make([]byte, len(id)*2+2)
b[0] = '"'
b[len(b)-1] = '"'
id.FormatTo(b[1:], 'x')
return b, nil
}
func (id *ID) UnmarshalJSON(b []byte) error {
if len(b) < 4 {
return errors.New("bad id")
}
if b[0] != '"' || b[len(b)-1] != '"' {
return errors.New("bad id encoding")
}
x, err := IDFromStringAsBytes(b[1 : len(b)-1])
if err != nil {
return err
}
*id = x
return nil
}
func MathRandID() (id ID) {
rnd.mu.Lock()
for id == (ID{}) {
_, _ = rnd.r.Read(id[:])
}
rnd.mu.Unlock()
return
}
func RandIDFromReader(read func(p []byte) (int, error)) func() ID {
return func() (id ID) {
n, err := read(id[:])
if err != nil {
panic(err)
}
if n != len(id) {
panic(n)
}
return id
}
}
/* will repeat at most after 2 ** (32 - 2) ids
func FastRandID() (id ID) {
*(*uint32)(unsafe.Pointer(&id[0])) = fastrand()
*(*uint32)(unsafe.Pointer(&id[4])) = fastrand()
*(*uint32)(unsafe.Pointer(&id[8])) = fastrand()
*(*uint32)(unsafe.Pointer(&id[12])) = fastrand()
return
}
*/
// UUID creates ID generation function.
// read is a random Read method. Function panics on Read error.
// read must be safe for concurrent use.
//
// It's got from github.com/google/uuid.
func UUID(read func(p []byte) (int, error)) func() ID {
return func() (uuid ID) {
n, err := read(uuid[:])
if err != nil {
panic(err)
}
if n != len(uuid) {
panic(n)
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid
}
}