-
Notifications
You must be signed in to change notification settings - Fork 8
/
map.go
395 lines (372 loc) · 9.05 KB
/
map.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package sonnet
import (
"encoding"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
)
type (
mapDecoder func([]byte, *Decoder) (reflect.Value, error)
mapEncoder func(reflect.Value) (string, uint64, bool, error)
)
type (
pair struct {
str string
u64 uint64
neg bool
key reflect.Value
elm reflect.Value
}
)
func compileMapDecoder(typ reflect.Type) decoder {
key, elm := typ.Key(), typ.Elem()
keyFnc := compileMapKeyDecoder(key)
fnc, ok := decs.get(elm)
elmVal := reflect.New(elm).Elem()
// elements get copied when assigning to maps.
// no need to create it each time, just reset it.
rep := func() {
if !ok {
fnc = compileDecoder(elm)
decs.set(elm, fnc)
}
}
var once sync.Once
var atom atomic.Bool
return func(head byte, val reflect.Value, dec *Decoder) error {
const ull = "ull"
if head == 'n' {
part, err := dec.readn(len(ull))
if err != nil {
return err
}
if string(part) != ull {
return dec.buildErrSyntax(head, ull, part)
}
val.SetZero()
return nil
}
if head != '{' || keyFnc == nil {
// invalid keys and token mismatch result in the same error.
return dec.errUnmarshalType(head, val.Type())
}
err := dec.inc()
if err != nil {
return err
}
var assign reflect.Value
if atom.CompareAndSwap(false, true) {
defer atom.Store(false)
assign = elmVal
} else {
assign = reflect.New(elm).Elem()
}
once.Do(rep)
if val.IsNil() {
val.Set(reflect.MakeMap(val.Type()))
}
for {
dec.eatSpaces()
if dec.pos >= len(dec.buf) && !dec.fill() {
return dec.errSyntax("unexpected EOF reading a byte")
}
head = dec.buf[dec.pos]
dec.pos++
if head == '}' && val.Len() == 0 {
dec.dep--
return nil
}
if head != '"' {
return dec.errSyntax("invalid character " + strconv.QuoteRune(rune(head)) + " looking for beginning of object key string")
}
slice, err := dec.readString()
if err != nil {
return err
}
keyVal, err := keyFnc(slice, dec)
if err != nil {
return err
}
dec.eatSpaces()
if dec.pos >= len(dec.buf) && !dec.fill() {
return dec.errSyntax("unexpected EOF reading a byte")
}
head = dec.buf[dec.pos]
dec.pos++
if head != ':' {
return dec.errSyntax("invalid character " + strconv.QuoteRune(rune(head)) + " after object key")
}
dec.eatSpaces()
if dec.pos >= len(dec.buf) && !dec.fill() {
return dec.errSyntax("unexpected EOF reading a byte")
}
head = dec.buf[dec.pos]
dec.pos++
assign.SetZero()
err = fnc(head, assign, dec)
if err != nil {
return err
}
val.SetMapIndex(keyVal, assign)
dec.eatSpaces()
if dec.pos >= len(dec.buf) && !dec.fill() {
return dec.errSyntax("unexpected EOF reading a byte")
}
head = dec.buf[dec.pos]
dec.pos++
if head == '}' {
dec.dep--
return nil
}
if head != ',' {
return dec.errSyntax("invalid character " + strconv.QuoteRune(rune(head)) + " after object key:value pair")
}
}
}
}
func compileMapKeyDecoder(typ reflect.Type) mapDecoder {
const lenInt = 5 // int, int8, int16, int32, int64
const lenUint = 6 // uint, uint8, uint16, uint32, uint64, uintptr
kind := typ.Kind()
ptr := reflect.PointerTo(typ)
if kind != reflect.Pointer && ptr.Implements(textUnmarshaler) {
return func(src []byte, dec *Decoder) (reflect.Value, error) {
val := reflect.New(typ)
unm := val.Interface().(encoding.TextUnmarshaler)
return val.Elem(), unm.UnmarshalText(src)
}
}
if typ.Implements(textUnmarshaler) {
return func(src []byte, dec *Decoder) (reflect.Value, error) {
val := reflect.New(typ).Elem()
if kind == reflect.Pointer && val.IsNil() {
return val, nil
}
unm := val.Interface().(encoding.TextUnmarshaler)
return val, unm.UnmarshalText(src)
}
}
if kind == reflect.String {
return func(src []byte, dec *Decoder) (reflect.Value, error) {
val := reflect.ValueOf(string(src))
if val.Type() != typ {
val = val.Convert(typ)
}
return val, nil
}
}
if kind-reflect.Int < lenInt {
return func(src []byte, dec *Decoder) (reflect.Value, error) {
i64, err := toInt(src)
if err != nil || reflect.Zero(typ).OverflowInt(i64) {
// errors toInt returns are placeholders;
// replace them with actual errors.
err = &UnmarshalTypeError{
Value: "number " + string(src),
Type: typ,
Offset: dec.InputOffset() - int64(len(src)),
}
return reflect.Value{}, err
}
val := reflect.ValueOf(i64)
if val.Type() != typ {
val = val.Convert(typ)
}
return val, nil
}
}
if kind-reflect.Uint < lenUint {
return func(src []byte, dec *Decoder) (reflect.Value, error) {
u64, err := toUint(src)
if err != nil || reflect.Zero(typ).OverflowUint(u64) {
err = &UnmarshalTypeError{
Value: "number " + string(src),
Type: typ,
Offset: dec.InputOffset() - int64(len(src)),
}
return reflect.Value{}, err
}
val := reflect.ValueOf(u64)
if val.Type() != typ {
val = val.Convert(typ)
}
return val, nil
}
}
return nil
}
func compileMapEncoder(typ reflect.Type) encoder {
const lenInt = 5 // int, int8, int16, int32, int64
const lenUint = 6 // uint, uint8, uint16, uint32, uint64, uintptr
key := typ.Key()
elm := typ.Elem()
noesc := key.Kind()-reflect.Int < lenInt+lenUint
noesc = noesc && !key.Implements(textMarshaler)
keyFnc := compileMapKeyEncoder(key)
fnc, ok := encs.get(elm)
rep := func() {
if !ok {
fnc = compileEncoder(elm, true)
encs.set(elm, fnc)
}
}
var cpy []*pair
var atom atomic.Bool
var once sync.Once
return func(dst []byte, val reflect.Value, enc *Encoder) ([]byte, error) {
if val.IsNil() {
return append(dst, "null"...), nil
}
once.Do(rep)
enc.level++
if enc.level > maxCycles {
if enc.seen == nil {
enc.seen = make(map[any]struct{})
}
head := val.Pointer()
if _, ok := enc.seen[head]; ok {
return nil, &UnsupportedValueError{
Value: val,
Str: "encountered a cycle via: " + typ.String(),
}
}
enc.seen[head] = struct{}{}
defer delete(enc.seen, head)
}
rng := val.MapRange()
var prs []*pair
if atom.CompareAndSwap(false, true) {
defer atom.Store(false)
for idx := 0; rng.Next(); idx++ {
if idx >= len(cpy) {
// need to be addressable to use later.
keyVal := reflect.New(key).Elem()
keyVal.Set(rng.Key())
str, u64, neg, err := keyFnc(keyVal)
if err != nil {
return nil, err
}
// the same goes for elements.
elmVal := reflect.New(elm).Elem()
elmVal.Set(rng.Value())
cpy = append(cpy, &pair{
str: str,
u64: u64,
neg: neg,
key: keyVal,
elm: elmVal,
})
continue
}
cpy[idx].key.SetIterKey(rng)
cpy[idx].elm.SetIterValue(rng)
str, u64, neg, err := keyFnc(cpy[idx].key)
if err != nil {
return nil, err
}
cpy[idx].str = str
cpy[idx].u64 = u64
cpy[idx].neg = neg
}
prs = cpy[:val.Len()]
} else {
prs = make([]*pair, val.Len())
for idx := 0; rng.Next(); idx++ {
keyVal := rng.Key()
str, u64, neg, err := keyFnc(keyVal)
if err != nil {
return nil, err
}
prs[idx] = &pair{
str: str,
u64: u64,
neg: neg,
key: keyVal,
elm: rng.Value(),
}
}
}
if noesc {
slices.SortFunc(prs, func(fst, sec *pair) int {
if fst.neg && !sec.neg {
return -1
}
if !fst.neg && sec.neg {
return 1
}
if fst.u64 < sec.u64 {
return -1
}
if fst.u64 > sec.u64 {
return 1
}
return 0
})
} else {
slices.SortFunc(prs, func(fst, sec *pair) int {
return strings.Compare(fst.str, sec.str)
})
}
dst = append(dst, '{')
var mid bool
for _, pr := range prs {
if mid {
dst = append(dst, ',')
}
if noesc {
dst = append(dst, '"')
dst = append(dst, fmtInt(pr.u64, pr.neg)...) // never pr.str!
dst = append(dst, '"')
} else {
dst = appendString(dst, pr.str, enc.html)
}
dst = append(dst, ':')
var err error
dst, err = fnc(dst, pr.elm, enc)
if err != nil {
return nil, err
}
mid = true
}
enc.level--
return append(dst, '}'), nil
}
}
func compileMapKeyEncoder(typ reflect.Type) mapEncoder {
const lenInt = 5 // int, int8, int16, int32, int64
const lenUint = 6 // uint, uint8, uint16, uint32, uint64, uintptr
kind := typ.Kind()
if kind == reflect.String {
return func(val reflect.Value) (string, uint64, bool, error) {
return val.String(), 0, false, nil
}
}
if typ.Implements(textMarshaler) {
return func(val reflect.Value) (string, uint64, bool, error) {
if kind == reflect.Pointer && val.IsNil() {
return "", 0, false, nil
}
src, err := val.Interface().(encoding.TextMarshaler).MarshalText()
return string(src), 0, false, err
}
}
if kind-reflect.Int < lenInt {
return func(val reflect.Value) (string, uint64, bool, error) {
i64 := val.Int()
if i64 < 0 {
return "", uint64(-i64), true, nil
}
return "", uint64(i64), false, nil
}
}
if kind-reflect.Uint < lenUint {
return func(val reflect.Value) (string, uint64, bool, error) {
u64 := val.Uint()
return "", u64, false, nil
}
}
panic("unexpected map key type")
}