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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
|
// Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// Some doc comments are
// copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// SPDX-License-Identifier: BSD-3-Clause
package lowmemjson
import (
"bytes"
"encoding"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"unicode/utf16"
"unicode/utf8"
"git.lukeshu.com/go/lowmemjson/internal/base64dec"
"git.lukeshu.com/go/lowmemjson/internal/fastio"
"git.lukeshu.com/go/lowmemjson/internal/jsonparse"
"git.lukeshu.com/go/lowmemjson/internal/jsonstruct"
)
// Decodable is the interface implemented by types that can decode a
// JSON representation of themselves. Decodable is a
// low-memory-overhead replacement for the json.Unmarshaler interface.
//
// On the io.RuneScanner passed to DecodeJSON:
//
// - .UnreadRune() will return ErrInvalidUnreadRune if the last
// operation was not a successful .ReadRune() call.
//
// - .ReadRune() will return io.EOF at the end of the JSON value; it
// is not possible for .ReadRune() to read past the end of the
// value in to another value.
//
// - .ReadRune() will never return invalid JSON; if invalid JSON is
// encountered, it will use a panic-based mechanism to transfer
// control back to the Decoder.
//
// - .ReadRune() never return an error other than io.EOF; if an I/O
// error is encountered, it will use a panic-based mechanism to
// transfer control back to the Decoder.
//
// DecodeJSON is expected to consume the entire scanner until io.EOF
// or another is encountered; if it does not, then the parent Decode
// call will return a *DecodeTypeError.
//
// Implementor's note: "withLimitingScanner" is the thing to search
// for in decode.go if you want to read up on that io.RuneScanner.
type Decodable interface {
DecodeJSON(io.RuneScanner) error
}
type decodeStackItem struct {
par reflect.Type
idx any
}
// A Decoder reads and decodes values from an input stream of JSON
// elements.
//
// Decoder is analogous to, and has a similar API to the standard
// library's encoding/json.Decoder. Differences are:
//
// - lowmemjson.NewDecoder takes an io.RuneScanner, while
// json.NewDecoder takes an io.Reader.
//
// - lowmemjson.Decoder does not have a .Buffered() method, while
// json.Decoder does.
//
// - lowmemjson.Decoder does not have a .Token() method, while
// json.Decoder does.
//
// If something more similar to a json.Decoder is desired,
// lowmemjson/compat/json.NewDecoder takes an io.Reader (and turns it
// into an io.RuneScanner by wrapping it in a bufio.Reader), and
// lowmemjson/compat/json.Decoder has a .Buffered() method; though
// lowmemjson/compat/json.Decoder also lacks the .Token() method.
type Decoder struct {
io runeTypeScanner
// config
disallowUnknownFields bool
useNumber bool
// state
posStack []int64
structStack []decodeStackItem
}
const maxNestingDepth = 10000
// NewDecoder returns a new Decoder that reads from r.
//
// NewDecoder is analogous to the standard library's
// encoding/json.NewDecoder, but takes an io.RuneScanner rather than
// an io.Reader.
func NewDecoder(r io.RuneScanner) *Decoder {
return &Decoder{
io: runeTypeScanner{
inner: r,
parser: jsonparse.Parser{
MaxDepth: maxNestingDepth,
},
},
}
}
// DisallowUnknownFields causes the Decoder to return an error when
// the destination is a struct and the input contains object keys
// which do not match any non-ignored, exported fields in the
// destination.
//
// This is identical to the standard library's
// encoding/json.Decoder.DisallowUnknownFields.
func (dec *Decoder) DisallowUnknownFields() { dec.disallowUnknownFields = true }
// UseNumber causes the Decoder to unmarshal a number into an
// interface{} as a Number instead of as a float64.
//
// This is identical to the standard library's
// encoding/json.Decoder.UseNumber.
func (dec *Decoder) UseNumber() { dec.useNumber = true }
// InputOffset returns the input stream byte offset of the current
// decoder position. The offset gives the location of the rune that
// will be returned from the next call to .ReadRune().
//
// This is identical to the standard library's
// encoding/json.Decoder.InputOffset.
func (dec *Decoder) InputOffset() int64 { return dec.io.InputOffset() }
// More reports whether there is more to the stream of JSON elements,
// or if the Decoder has reached EOF or an error.
//
// More is identical to the standard library's
// encoding/json.Decoder.More.
func (dec *Decoder) More() bool {
dec.io.Reset()
_, _, t, e := dec.io.ReadRuneType()
_ = dec.io.UnreadRune() // best effort
return e == nil && t != jsonparse.RuneTypeEOF
}
func (dec *Decoder) posStackPush() {
dec.posStack = append(dec.posStack, dec.InputOffset())
}
func (dec *Decoder) posStackPop() {
dec.posStack = dec.posStack[:len(dec.posStack)-1]
}
func (dec *Decoder) structStackPush(par reflect.Type, idx any) {
dec.structStack = append(dec.structStack, decodeStackItem{par, idx})
}
func (dec *Decoder) structStackPop() {
dec.structStack = dec.structStack[:len(dec.structStack)-1]
}
func (dec *Decoder) structStackStr() string {
var buf strings.Builder
buf.WriteString("v")
for _, item := range dec.structStack {
fmt.Fprintf(&buf, "[%#v]", item.idx)
}
return buf.String()
}
func (dec *Decoder) structStackParent() string {
last := len(dec.structStack) - 1
if last > 0 && dec.structStack[last].par.Kind() != reflect.Struct && dec.structStack[last-1].par.Kind() == reflect.Struct {
last--
}
if last >= 0 && dec.structStack[last].par.Kind() == reflect.Struct {
return dec.structStack[last].par.Name()
}
return ""
}
func (dec *Decoder) structStackName() string {
if dec.structStackParent() == "" {
return ""
}
var fields []string
for _, elem := range dec.structStack {
if elem.par.Kind() == reflect.Struct {
fields = append(fields, elem.idx.(string))
}
}
return strings.Join(fields, ".")
}
// DecodeThenEOF is like Decode, but emits an error if there is extra
// data after the JSON. A JSON document is specified to be a single
// JSON element; repeated calls to Decoder.Decode will happily decode
// a stream of multiple JSON elements.
func (dec *Decoder) DecodeThenEOF(ptr any) (err error) {
if err := dec.Decode(ptr); err != nil {
return err
}
c, s, t, _ := dec.io.ReadRuneType()
if t != jsonparse.RuneTypeEOF {
panic("should not happen")
}
if s > 0 {
return &DecodeError{
Err: &DecodeSyntaxError{
Err: fmt.Errorf("invalid character %q after top-level value", c),
Offset: dec.InputOffset(),
},
}
}
return nil
}
// Decode reads the next JSON element from the Decoder's input stream
// and stores it in the value pointed to by ptr.
//
// See the [documentation for encoding/json.Unmarshal] for details
// about the conversion of JSON into a Go value; Decode behaves
// identically to that, with the exception that in addition to the
// json.Unmarshaler interface it also checks for the Decodable
// interface.
//
// [documentation for encoding/json.Unmarshal]: https://pkg.go.dev/encoding/json@go1.20#Unmarshal
func (dec *Decoder) Decode(ptr any) (err error) {
ptrVal := reflect.ValueOf(ptr)
if ptrVal.Kind() != reflect.Pointer || ptrVal.IsNil() || !ptrVal.Elem().CanSet() {
return &DecodeArgumentError{
// don't use ptrVal.Type() because ptrVal might be invalid if ptr==nil
Type: reflect.TypeOf(ptr),
}
}
dec.io.Reset()
dec.io.PushReadBarrier()
if err := dec.decode(ptrVal.Elem(), false); err != nil {
return err
}
dec.io.PopReadBarrier()
return nil
}
// io helpers //////////////////////////////////////////////////////////////////////////////////////
type decodeError DecodeError
func (dec *Decoder) newTypeError(jTyp string, gTyp reflect.Type, err error) *DecodeError {
return &DecodeError{
Field: dec.structStackStr(),
FieldParent: dec.structStackParent(),
FieldName: dec.structStackName(),
Err: &DecodeTypeError{
GoType: gTyp,
JSONType: jTyp,
Err: err,
Offset: dec.posStack[len(dec.posStack)-1],
},
}
}
func (dec *Decoder) readRune() (rune, jsonparse.RuneType) {
c, _, t, e := dec.io.ReadRuneType()
if e != nil {
panic(decodeError{
Field: dec.structStackStr(),
FieldParent: dec.structStackParent(),
FieldName: dec.structStackName(),
Err: e,
})
}
return c, t
}
func (dec *Decoder) unreadRune() {
if err := dec.io.UnreadRune(); err != nil {
// .UnreadRune() must succeed if the previous call was
// .ReadRune(), which it always is for this code.
panic("should not happen")
}
}
func (dec *Decoder) peekRuneType() jsonparse.RuneType {
_, t := dec.readRune()
dec.unreadRune()
return t
}
func (dec *Decoder) expectRune(ec rune, et jsonparse.RuneType) {
ac, at := dec.readRune()
if ac != ec || at != et {
panic("should not happen")
}
}
func (dec *Decoder) expectRuneType(ec rune, et jsonparse.RuneType, gt reflect.Type) *DecodeError {
ac, at := dec.readRune()
if ac != ec || at != et {
return dec.newTypeError(at.JSONType(), gt, nil)
}
return nil
}
type decRuneScanner struct {
dec *Decoder
eof bool
}
type scannerPanic *DecodeError
func (sc *decRuneScanner) ReadRune() (rune, int, error) {
if sc.eof {
return 0, 0, io.EOF
}
c, s, t, e := sc.dec.io.ReadRuneType()
if t == jsonparse.RuneTypeEOF {
sc.eof = true
sc.dec.io.PopReadBarrier()
return 0, 0, io.EOF
}
if e != nil {
panic(scannerPanic(&DecodeError{
Field: sc.dec.structStackStr(),
FieldParent: sc.dec.structStackParent(),
FieldName: sc.dec.structStackName(),
Err: e,
}))
}
return c, s, nil
}
func (sc *decRuneScanner) UnreadRune() error {
return sc.dec.io.UnreadRune()
}
func (dec *Decoder) withLimitingScanner(fn func(io.RuneScanner) *DecodeError) (err *DecodeError) {
dec.io.PushReadBarrier()
defer func() {
if r := recover(); r != nil {
if sp, ok := r.(scannerPanic); ok {
err = (*DecodeError)(sp)
} else {
panic(r)
}
}
}()
if err := fn(&decRuneScanner{dec: dec}); err != nil {
return err
}
return nil
}
// decoder main ////////////////////////////////////////////////////////////////////////////////////
var kind2bits = map[reflect.Kind]int{
reflect.Int: int(32 << (^uint(0) >> 63)),
reflect.Int8: 8,
reflect.Int16: 16,
reflect.Int32: 32,
reflect.Int64: 64,
reflect.Uint: int(32 << (^uint(0) >> 63)),
reflect.Uint8: 8,
reflect.Uint16: 16,
reflect.Uint32: 32,
reflect.Uint64: 64,
reflect.Uintptr: int(32 << (^uintptr(0) >> 63)),
reflect.Float32: 32,
reflect.Float64: 64,
}
func (dec *Decoder) decode(val reflect.Value, nullOK bool) (_err *DecodeError) {
defer func() {
if r := recover(); r != nil {
if de, ok := r.(decodeError); ok {
pub := DecodeError(de)
_err = &pub
} else {
panic(r)
}
}
}()
dec.posStackPush()
defer dec.posStackPop()
typ := val.Type()
switch {
case val.CanAddr() && reflect.PointerTo(typ) == rawMessagePtrType:
t := dec.peekRuneType()
var buf bytes.Buffer
if err := dec.scan(&buf); err != nil {
return err
}
if err := val.Addr().Interface().(*RawMessage).UnmarshalJSON(buf.Bytes()); err != nil {
return dec.newTypeError(t.JSONType(), reflect.PointerTo(typ), err)
}
case val.CanAddr() && reflect.PointerTo(typ).Implements(decodableType):
t := dec.peekRuneType()
obj := val.Addr().Interface().(Decodable)
return dec.withLimitingScanner(func(l io.RuneScanner) *DecodeError {
if err := obj.DecodeJSON(l); err != nil {
return dec.newTypeError(t.JSONType(), reflect.PointerTo(typ), err)
}
if _, _, err := l.ReadRune(); err != io.EOF {
return dec.newTypeError(t.JSONType(), reflect.PointerTo(typ), fmt.Errorf("did not consume entire %s", t.JSONType()))
}
return nil
})
case val.CanAddr() && reflect.PointerTo(typ).Implements(jsonUnmarshalerType):
t := dec.peekRuneType()
var buf bytes.Buffer
if err := dec.scan(&buf); err != nil {
return err
}
obj := val.Addr().Interface().(jsonUnmarshaler)
if err := obj.UnmarshalJSON(buf.Bytes()); err != nil {
return dec.newTypeError(t.JSONType(), reflect.PointerTo(typ), err)
}
case val.CanAddr() && reflect.PointerTo(typ).Implements(textUnmarshalerType):
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
var buf bytes.Buffer
if err := dec.decodeString(reflect.PointerTo(typ), &buf); err != nil {
return err
}
obj := val.Addr().Interface().(encoding.TextUnmarshaler)
if err := obj.UnmarshalText(buf.Bytes()); err != nil {
return dec.newTypeError("string", reflect.PointerTo(typ), err)
}
default:
switch kind := typ.Kind(); kind {
case reflect.Bool:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
b, err := dec.decodeBool(typ)
if err != nil {
return err
}
val.SetBool(b)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
var buf strings.Builder
if err := dec.scanNumber(typ, &buf); err != nil {
return err
}
n, err := strconv.ParseInt(buf.String(), 10, kind2bits[kind])
if err != nil {
return dec.newTypeError("number "+buf.String(), typ, err)
}
val.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
var buf strings.Builder
if err := dec.scanNumber(typ, &buf); err != nil {
return err
}
n, err := strconv.ParseUint(buf.String(), 10, kind2bits[kind])
if err != nil {
return dec.newTypeError("number "+buf.String(), typ, err)
}
val.SetUint(n)
case reflect.Float32, reflect.Float64:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
var buf strings.Builder
if err := dec.scanNumber(typ, &buf); err != nil {
return err
}
n, err := strconv.ParseFloat(buf.String(), kind2bits[kind])
if err != nil {
return dec.newTypeError("number "+buf.String(), typ, err)
}
val.SetFloat(n)
case reflect.String:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
var buf strings.Builder
if typ == numberType {
t := dec.peekRuneType()
if err := dec.scan(&buf); err != nil {
return err
}
if !t.IsNumber() {
return dec.newTypeError(t.JSONType(), typ,
fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number",
buf.String()))
}
val.SetString(buf.String())
} else {
if err := dec.decodeString(typ, &buf); err != nil {
return err
}
val.SetString(buf.String())
}
case reflect.Interface:
if typ.NumMethod() > 0 {
return dec.newTypeError(dec.peekRuneType().JSONType(), typ, ErrDecodeNonEmptyInterface)
}
// If the interface stores a pointer, try to use the type information of the pointer.
if !val.IsNil() && val.Elem().Kind() == reflect.Pointer {
// Follow a chain of pointers until we find the first settable
// pointer (if any).
ptr := val.Elem()
for {
if ptr.CanSet() || ptr.IsNil() || ptr.Elem().Kind() != reflect.Pointer {
// We've reached the end of the line, good or bad.
break
}
ptr = ptr.Elem()
}
// ptr.Elem() != val
//
// Avoid the loop of an interface storing a pointer to its own
// address. We only need to worry about this at the leaf (and not
// in the loop) because the only way it's possible is if there's
// an interface in there, which'd break from the loop on its own.
//
// ptr.CanSet() || dec.peekRuneType() != jsonparse.RuneTypeNullN
//
// We only need the pointer itself to be settable if we're
// decoding null.
if ptr.Elem() != val && (ptr.CanSet() || dec.peekRuneType() != jsonparse.RuneTypeNullN) {
if err := dec.decode(ptr, false); err != nil {
return err
}
break
}
}
// Couldn't get type information from a pointer; fall back to untyped mode.
switch dec.peekRuneType() {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
val.Set(reflect.Zero(typ))
default:
v, err := dec.decodeAny()
if err != nil {
return err
}
val.Set(reflect.ValueOf(v))
}
case reflect.Struct:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
index := jsonstruct.IndexStruct(typ)
var nameBuf strings.Builder
return dec.decodeObject(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
nameBuf.Reset()
return dec.decodeString(nil, &nameBuf)
}, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
name := nameBuf.String()
dec.structStackPush(typ, name)
defer dec.structStackPop()
idx, ok := index.ByName[name]
if !ok {
for oidx := range index.ByPos {
if strings.EqualFold(name, index.ByPos[oidx].Name) {
idx = oidx
ok = true
break
}
}
}
if !ok {
if dec.disallowUnknownFields {
return dec.newTypeError("", typ, fmt.Errorf("json: unknown field %q", name))
}
return dec.scan(fastio.Discard)
}
field := index.ByPos[idx]
fVal := val
for _, idx := range field.Path {
if fVal.Kind() == reflect.Pointer {
if fVal.IsNil() && !fVal.CanSet() { // https://golang.org/issue/21357
return dec.newTypeError("", fVal.Type().Elem(),
fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v",
fVal.Type().Elem()))
}
if dec.peekRuneType() != jsonparse.RuneTypeNullN {
if fVal.IsNil() {
fVal.Set(reflect.New(fVal.Type().Elem()))
}
fVal = fVal.Elem()
}
}
fVal = fVal.Field(idx)
}
if field.Quote {
switch t := dec.peekRuneType(); t {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
switch fVal.Kind() {
// XXX: I can't justify this list, other than "it's what encoding/json
// does, but I don't understand their rationale".
case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
fVal.Set(reflect.Zero(fVal.Type()))
default:
// do nothing???
}
case jsonparse.RuneTypeStringBeg:
// TODO: Figure out how to do this without buffering, have correct offsets.
var buf bytes.Buffer
if err := dec.decodeString(nil, &buf); err != nil {
return err
}
if err := NewDecoder(bytes.NewReader(buf.Bytes())).Decode(fVal.Addr().Interface()); err != nil {
if str := buf.String(); str != "null" {
return dec.newTypeError("", fVal.Type(),
fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v",
str, fVal.Type()))
}
}
default:
return dec.newTypeError(t.JSONType(), fVal.Type(),
fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v",
fVal.Type()))
}
return nil
} else {
return dec.decode(fVal, true)
}
})
case reflect.Map:
switch t := dec.peekRuneType(); t {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
val.Set(reflect.Zero(typ))
case jsonparse.RuneTypeObjectBeg:
if val.IsNil() {
val.Set(reflect.MakeMap(typ))
}
var nameBuf bytes.Buffer
var nameValPtr reflect.Value
return dec.decodeObject(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
nameBuf.Reset()
if err := dec.decodeString(nil, &nameBuf); err != nil {
return err
}
nameValTyp := typ.Key()
nameValPtr = reflect.New(nameValTyp)
switch {
case reflect.PointerTo(nameValTyp).Implements(textUnmarshalerType):
obj := nameValPtr.Interface().(encoding.TextUnmarshaler)
if err := obj.UnmarshalText(nameBuf.Bytes()); err != nil {
return dec.newTypeError("string", reflect.PointerTo(nameValTyp), err)
}
default:
switch nameValTyp.Kind() {
case reflect.String:
nameValPtr.Elem().SetString(nameBuf.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(nameBuf.String(), 10, kind2bits[nameValTyp.Kind()])
if err != nil {
return dec.newTypeError("number "+nameBuf.String(), nameValTyp, err)
}
nameValPtr.Elem().SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
n, err := strconv.ParseUint(nameBuf.String(), 10, kind2bits[nameValTyp.Kind()])
if err != nil {
return dec.newTypeError("number "+nameBuf.String(), nameValTyp, err)
}
nameValPtr.Elem().SetUint(n)
default:
return dec.newTypeError("object", typ, &DecodeArgumentError{Type: nameValTyp})
}
}
return nil
}, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
dec.structStackPush(typ, nameValPtr.Elem())
defer dec.structStackPop()
fValPtr := reflect.New(typ.Elem())
if err := dec.decode(fValPtr.Elem(), false); err != nil {
return err
}
val.SetMapIndex(nameValPtr.Elem(), fValPtr.Elem())
return nil
})
default:
return dec.newTypeError(t.JSONType(), typ, nil)
}
case reflect.Slice:
switch {
case typ.Elem().Kind() == reflect.Uint8 && !(dec.peekRuneType() == jsonparse.RuneTypeArrayBeg && (false ||
reflect.PointerTo(typ.Elem()).Implements(decodableType) ||
reflect.PointerTo(typ.Elem()).Implements(jsonUnmarshalerType) ||
reflect.PointerTo(typ.Elem()).Implements(textUnmarshalerType))):
switch t := dec.peekRuneType(); t {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
val.Set(reflect.Zero(typ))
case jsonparse.RuneTypeStringBeg:
if typ.Elem() == byteType {
var buf bytes.Buffer
if err := dec.decodeString(typ, base64dec.NewBase64Decoder(&buf)); err != nil {
return err
}
val.Set(reflect.ValueOf(buf.Bytes()))
} else {
// TODO: Surely there's a better way. At the very least, we should
// avoid buffering.
var buf bytes.Buffer
if err := dec.decodeString(typ, base64dec.NewBase64Decoder(&buf)); err != nil {
return err
}
bs := buf.Bytes()
val.Set(reflect.MakeSlice(typ, len(bs), len(bs)))
for i := 0; i < len(bs); i++ {
val.Index(i).Set(reflect.ValueOf(bs[i]).Convert(typ.Elem()))
}
}
default:
return dec.newTypeError(t.JSONType(), typ, nil)
}
default:
switch t := dec.peekRuneType(); t {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
val.Set(reflect.Zero(typ))
case jsonparse.RuneTypeArrayBeg:
if val.IsNil() {
val.Set(reflect.MakeSlice(typ, 0, 0))
}
if val.Len() > 0 {
val.Set(val.Slice(0, 0))
}
i := 0
return dec.decodeArray(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
dec.structStackPush(typ, i)
defer dec.structStackPop()
mValPtr := reflect.New(typ.Elem())
if err := dec.decode(mValPtr.Elem(), false); err != nil {
return err
}
val.Set(reflect.Append(val, mValPtr.Elem()))
i++
return nil
})
default:
return dec.newTypeError(t.JSONType(), typ, nil)
}
}
case reflect.Array:
if nullOK && dec.peekRuneType() == jsonparse.RuneTypeNullN {
return dec.decodeNull()
}
i := 0
n := val.Len()
if err := dec.decodeArray(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
dec.structStackPush(typ, i)
defer dec.structStackPop()
if i < n {
mValPtr := reflect.New(typ.Elem())
if err := dec.decode(mValPtr.Elem(), false); err != nil {
return err
}
val.Index(i).Set(mValPtr.Elem())
} else {
if err := dec.scan(fastio.Discard); err != nil {
return err
}
}
i++
return nil
}); err != nil {
return err
}
for ; i < n; i++ {
val.Index(i).Set(reflect.Zero(typ.Elem()))
}
case reflect.Pointer:
switch dec.peekRuneType() {
case jsonparse.RuneTypeNullN:
if err := dec.decodeNull(); err != nil {
return err
}
val.Set(reflect.Zero(typ))
default:
if val.IsNil() {
val.Set(reflect.New(typ.Elem()))
}
return dec.decode(val.Elem(), false)
}
default:
return dec.newTypeError("", typ, fmt.Errorf("unsupported type (kind=%v)", typ.Kind()))
}
}
return nil
}
func (dec *Decoder) scan(out fastio.RuneWriter) *DecodeError {
dec.io.PushReadBarrier()
for {
c, t := dec.readRune()
if t == jsonparse.RuneTypeEOF {
break
}
_, _ = out.WriteRune(c)
}
dec.io.PopReadBarrier()
return nil
}
func (dec *Decoder) scanNumber(gTyp reflect.Type, out fastio.RuneWriter) *DecodeError {
if t := dec.peekRuneType(); !t.IsNumber() {
return dec.newTypeError(t.JSONType(), gTyp, nil)
}
return dec.scan(out)
}
func (dec *Decoder) decodeAny() (any, *DecodeError) {
c, _ := dec.readRune()
dec.unreadRune()
switch c {
case '{':
ret := make(map[string]any)
typ := reflect.TypeOf(ret)
var nameBuf strings.Builder
if err := dec.decodeObject(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
nameBuf.Reset()
return dec.decodeString(nil, &nameBuf)
}, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
name := nameBuf.String()
dec.structStackPush(typ, name)
defer dec.structStackPop()
v, err := dec.decodeAny()
if err != nil {
return err
}
ret[name] = v
return nil
}); err != nil {
return nil, err
}
return ret, nil
case '[':
ret := []any{}
typ := reflect.TypeOf(ret)
if err := dec.decodeArray(typ, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
dec.structStackPush(typ, len(ret))
defer dec.structStackPop()
v, err := dec.decodeAny()
if err != nil {
return err
}
ret = append(ret, v)
return nil
}); err != nil {
return nil, err
}
return ret, nil
case '"':
var buf strings.Builder
if err := dec.decodeString(nil, &buf); err != nil {
return nil, err
}
return buf.String(), nil
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
var buf strings.Builder
if err := dec.scan(&buf); err != nil {
return nil, err
}
num := Number(buf.String())
if dec.useNumber {
return num, nil
}
f64, err := num.Float64()
if err != nil {
return nil, dec.newTypeError("number "+buf.String(), float64Type, err)
}
return f64, nil
case 't', 'f':
return dec.decodeBool(nil)
case 'n':
return nil, dec.decodeNull()
default:
panic("should not happen")
}
}
// DecodeObject is a helper function to ease implementing the
// Decodable interface; allowing the lowmemjson package to handle
// decoding the object syntax, while the Decodable only needs to
// handle decoding the keys and values within the object.
//
// Outside of implementing Decodable.DecodeJSON methods, callers
// should instead simply use NewDecoder(r).Decode(&val) rather than
// attempting to call DecodeObject directly.
func DecodeObject(r io.RuneScanner, decodeKey, decodeVal func(io.RuneScanner) error) (err error) {
defer func() {
if r := recover(); r != nil {
if de, ok := r.(decodeError); ok {
pub := DecodeError(de)
err = &pub
} else {
panic(r)
}
}
}()
var dec *Decoder
if dr, ok := r.(*decRuneScanner); ok {
dec = dr.dec
} else {
dec = NewDecoder(r)
}
dec.posStackPush()
defer dec.posStackPop()
if err := dec.decodeObject(nil,
func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
return dec.withLimitingScanner(func(l io.RuneScanner) *DecodeError {
if err := decodeKey(l); err != nil {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError("string", nil, err)
}
if _, _, err := l.ReadRune(); err != io.EOF {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError("string", nil, fmt.Errorf("did not consume entire string"))
}
return nil
})
},
func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
t := dec.peekRuneType()
return dec.withLimitingScanner(func(l io.RuneScanner) *DecodeError {
if err := decodeVal(l); err != nil {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError(t.JSONType(), nil, err)
}
if _, _, err := l.ReadRune(); err != io.EOF {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError(t.JSONType(), nil, fmt.Errorf("did not consume entire %s", t.JSONType()))
}
return nil
})
}); err != nil {
return err
}
return nil
}
func (dec *Decoder) decodeObject(gTyp reflect.Type, decodeKey, decodeVal func() *DecodeError) *DecodeError {
if err := dec.expectRuneType('{', jsonparse.RuneTypeObjectBeg, gTyp); err != nil {
return err
}
_, t := dec.readRune()
switch t {
case jsonparse.RuneTypeObjectEnd:
return nil
case jsonparse.RuneTypeStringBeg:
decodeMember:
dec.unreadRune()
if err := decodeKey(); err != nil {
return err
}
dec.expectRune(':', jsonparse.RuneTypeObjectColon)
if err := decodeVal(); err != nil {
return err
}
_, t := dec.readRune()
switch t {
case jsonparse.RuneTypeObjectComma:
dec.expectRune('"', jsonparse.RuneTypeStringBeg)
goto decodeMember
case jsonparse.RuneTypeObjectEnd:
return nil
default:
panic("should not happen")
}
default:
panic("should not happen")
}
}
// DecodeArray is a helper function to ease implementing the Decoder
// interface; allowing the lowmemjson package to handle decoding the
// array syntax, while the Decodable only needs to handle decoding
// members within the array.
//
// Outside of implementing Decodable.DecodeJSON methods, callers
// should instead simply use NewDecoder(r).Decode(&val) rather than
// attempting to call DecodeArray directly.
func DecodeArray(r io.RuneScanner, decodeMember func(r io.RuneScanner) error) (err error) {
defer func() {
if r := recover(); r != nil {
if de, ok := r.(decodeError); ok {
pub := DecodeError(de)
err = &pub
} else {
panic(r)
}
}
}()
var dec *Decoder
if dr, ok := r.(*decRuneScanner); ok {
dec = dr.dec
} else {
dec = NewDecoder(r)
}
dec.posStackPush()
defer dec.posStackPop()
if err := dec.decodeArray(nil, func() *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
t := dec.peekRuneType()
return dec.withLimitingScanner(func(l io.RuneScanner) *DecodeError {
if err := decodeMember(l); err != nil {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError(t.JSONType(), nil, err)
}
if _, _, err := l.ReadRune(); err != io.EOF {
// TODO: Find a better Go type to use than `nil`.
return dec.newTypeError(t.JSONType(), nil, fmt.Errorf("did not consume entire %s", t.JSONType()))
}
return nil
})
}); err != nil {
return err
}
return nil
}
func (dec *Decoder) decodeArray(gTyp reflect.Type, decodeMember func() *DecodeError) *DecodeError {
if err := dec.expectRuneType('[', jsonparse.RuneTypeArrayBeg, gTyp); err != nil {
return err
}
_, t := dec.readRune()
switch t {
case jsonparse.RuneTypeArrayEnd:
return nil
default:
dec.unreadRune()
decodeNextMember:
if err := decodeMember(); err != nil {
return err
}
_, t := dec.readRune()
switch t {
case jsonparse.RuneTypeArrayComma:
goto decodeNextMember
case jsonparse.RuneTypeArrayEnd:
return nil
default:
panic("should not happen")
}
}
}
func (dec *Decoder) decodeString(gTyp reflect.Type, out fastio.RuneWriter) *DecodeError {
if err := dec.expectRuneType('"', jsonparse.RuneTypeStringBeg, gTyp); err != nil {
return err
}
var uhex [4]byte
for {
c, t := dec.readRune()
switch t {
case jsonparse.RuneTypeStringChar:
_, _ = out.WriteRune(c)
case jsonparse.RuneTypeStringEsc, jsonparse.RuneTypeStringEscU:
// do nothing
case jsonparse.RuneTypeStringEsc1:
switch c {
case '"':
_, _ = out.WriteRune('"')
case '\\':
_, _ = out.WriteRune('\\')
case '/':
_, _ = out.WriteRune('/')
case 'b':
_, _ = out.WriteRune('\b')
case 'f':
_, _ = out.WriteRune('\f')
case 'n':
_, _ = out.WriteRune('\n')
case 'r':
_, _ = out.WriteRune('\r')
case 't':
_, _ = out.WriteRune('\t')
default:
panic("should not happen")
}
case jsonparse.RuneTypeStringEscUA:
uhex[0], _ = jsonparse.HexToInt(c)
case jsonparse.RuneTypeStringEscUB:
uhex[1], _ = jsonparse.HexToInt(c)
case jsonparse.RuneTypeStringEscUC:
uhex[2], _ = jsonparse.HexToInt(c)
case jsonparse.RuneTypeStringEscUD:
uhex[3], _ = jsonparse.HexToInt(c)
c = 0 |
rune(uhex[0])<<12 |
rune(uhex[1])<<8 |
rune(uhex[2])<<4 |
rune(uhex[3])<<0
handleUnicode:
if utf16.IsSurrogate(c) {
if dec.peekRuneType() != jsonparse.RuneTypeStringEsc {
_, _ = out.WriteRune(utf8.RuneError)
break
}
dec.expectRune('\\', jsonparse.RuneTypeStringEsc)
if dec.peekRuneType() != jsonparse.RuneTypeStringEscU {
_, _ = out.WriteRune(utf8.RuneError)
break
}
dec.expectRune('u', jsonparse.RuneTypeStringEscU)
b, _ := dec.readRune()
uhex[0], _ = jsonparse.HexToInt(b)
b, _ = dec.readRune()
uhex[1], _ = jsonparse.HexToInt(b)
b, _ = dec.readRune()
uhex[2], _ = jsonparse.HexToInt(b)
b, _ = dec.readRune()
uhex[3], _ = jsonparse.HexToInt(b)
c2 := 0 |
rune(uhex[0])<<12 |
rune(uhex[1])<<8 |
rune(uhex[2])<<4 |
rune(uhex[3])<<0
d := utf16.DecodeRune(c, c2)
if d == utf8.RuneError {
_, _ = out.WriteRune(utf8.RuneError)
c = c2
goto handleUnicode
}
_, _ = out.WriteRune(d)
} else {
_, _ = out.WriteRune(c)
}
case jsonparse.RuneTypeStringEnd:
return nil
default:
panic("should not happen")
}
}
}
func (dec *Decoder) decodeBool(gTyp reflect.Type) (bool, *DecodeError) {
c, t := dec.readRune()
switch c {
case 't':
dec.expectRune('r', jsonparse.RuneTypeTrueR)
dec.expectRune('u', jsonparse.RuneTypeTrueU)
dec.expectRune('e', jsonparse.RuneTypeTrueE)
return true, nil
case 'f':
dec.expectRune('a', jsonparse.RuneTypeFalseA)
dec.expectRune('l', jsonparse.RuneTypeFalseL)
dec.expectRune('s', jsonparse.RuneTypeFalseS)
dec.expectRune('e', jsonparse.RuneTypeFalseE)
return false, nil
default:
return false, dec.newTypeError(t.JSONType(), gTyp, nil)
}
}
func (dec *Decoder) decodeNull() *DecodeError {
dec.expectRune('n', jsonparse.RuneTypeNullN)
dec.expectRune('u', jsonparse.RuneTypeNullU)
dec.expectRune('l', jsonparse.RuneTypeNullL1)
dec.expectRune('l', jsonparse.RuneTypeNullL2)
return nil
}
|