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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
|
// 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(fmt.Errorf("should not happen: .ReadRuneType returned non-EOF after decode without .Reset being called: %v", t))
}
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 //////////////////////////////////////////////////////////////////////////////////////
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, *DecodeError) {
c, _, t, e := dec.io.ReadRuneType()
if e != nil {
return 0, 0, &DecodeError{
Field: dec.structStackStr(),
FieldParent: dec.structStackParent(),
FieldName: dec.structStackName(),
Err: e,
}
}
return c, t, nil
}
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(fmt.Errorf("should not happen: UnreadRune: %w", err))
}
}
func (dec *Decoder) peekRuneType() (jsonparse.RuneType, *DecodeError) {
_, t, err := dec.readRune()
if err != nil {
return 0, err
}
dec.unreadRune()
return t, nil
}
func (dec *Decoder) expectRune(ec rune, et jsonparse.RuneType) *DecodeError {
ac, at, err := dec.readRune()
if err != nil {
return err
}
if ac != ec || at != et {
panic(fmt.Errorf("should not happen: expected %q/%v but got %q/%v", ec, et, ac, at))
}
return nil
}
func (dec *Decoder) expectRuneType(ec rune, et jsonparse.RuneType, gt reflect.Type) *DecodeError {
ac, at, err := dec.readRune()
if err != nil {
return err
}
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) *DecodeError {
dec.posStackPush()
defer dec.posStackPop()
typ := val.Type()
switch {
case val.CanAddr() && reflect.PointerTo(typ) == rawMessagePtrType:
t, err := dec.peekRuneType()
if err != nil {
return err
}
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, err := dec.peekRuneType()
if err != nil {
return err
}
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, err := dec.peekRuneType()
if err != nil {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
var buf strings.Builder
if typ == numberType {
t, err := dec.peekRuneType()
if err != nil {
return err
}
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:
t, err := dec.peekRuneType()
if err != nil {
return err
}
if typ.NumMethod() > 0 {
return dec.newTypeError(t.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() || t != jsonparse.RuneTypeNullN
//
// We only need the pointer itself to be settable if we're
// decoding null.
if ptr.Elem() != val && (ptr.CanSet() || t != 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 t {
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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()))
}
t, err := dec.peekRuneType()
if err != nil {
return err
}
if t != jsonparse.RuneTypeNullN {
if fVal.IsNil() {
fVal.Set(reflect.New(fVal.Type().Elem()))
}
fVal = fVal.Elem()
}
}
fVal = fVal.Field(idx)
}
if field.Quote {
t, err := dec.peekRuneType()
if err != nil {
return err
}
switch 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:
t, err := dec.peekRuneType()
if err != nil {
return err
}
switch 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:
t, err := dec.peekRuneType()
if err != nil {
return err
}
switch {
case typ.Elem().Kind() == reflect.Uint8 && !(t == jsonparse.RuneTypeArrayBeg && (false ||
reflect.PointerTo(typ.Elem()).Implements(decodableType) ||
reflect.PointerTo(typ.Elem()).Implements(jsonUnmarshalerType) ||
reflect.PointerTo(typ.Elem()).Implements(textUnmarshalerType))):
switch 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 {
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 ok, err := dec.maybeDecodeNull(nullOK); ok {
return err
}
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:
t, err := dec.peekRuneType()
if err != nil {
return err
}
switch t {
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, err := dec.readRune()
if err != nil {
return err
}
if t == jsonparse.RuneTypeEOF {
break
}
_, _ = out.WriteRune(c)
}
dec.io.PopReadBarrier()
return nil
}
func (dec *Decoder) scanNumber(gTyp reflect.Type, out fastio.RuneWriter) *DecodeError {
t, err := dec.peekRuneType()
if err != nil {
return err
}
if !t.IsNumber() {
return dec.newTypeError(t.JSONType(), gTyp, nil)
}
return dec.scan(out)
}
func (dec *Decoder) decodeAny() (any, *DecodeError) {
t, err := dec.peekRuneType()
if err != nil {
return nil, err
}
switch t {
case jsonparse.RuneTypeObjectBeg:
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 jsonparse.RuneTypeArrayBeg:
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 jsonparse.RuneTypeStringBeg:
var buf strings.Builder
if err := dec.decodeString(nil, &buf); err != nil {
return nil, err
}
return buf.String(), nil
case jsonparse.RuneTypeNumberIntNeg, jsonparse.RuneTypeNumberIntZero, jsonparse.RuneTypeNumberIntDig:
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 jsonparse.RuneTypeTrueT, jsonparse.RuneTypeFalseF:
return dec.decodeBool(nil)
case jsonparse.RuneTypeNullN:
return nil, dec.decodeNull()
default:
panic(fmt.Errorf("should not happen: unexpected runeType at beginning of value: %v", t))
}
}
// 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) error {
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, err := dec.peekRuneType()
if err != nil {
return err
}
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, err := dec.readRune()
if err != nil {
return err
}
switch t {
case jsonparse.RuneTypeObjectEnd:
return nil
case jsonparse.RuneTypeStringBeg:
decodeMember:
dec.unreadRune()
if err := decodeKey(); err != nil {
return err
}
if err := dec.expectRune(':', jsonparse.RuneTypeObjectColon); err != nil {
return err
}
if err := decodeVal(); err != nil {
return err
}
_, t, err := dec.readRune()
if err != nil {
return err
}
switch t {
case jsonparse.RuneTypeObjectComma:
if err := dec.expectRune('"', jsonparse.RuneTypeStringBeg); err != nil {
return err
}
goto decodeMember
case jsonparse.RuneTypeObjectEnd:
return nil
default:
panic(fmt.Errorf("should not happen: unexpected runeType after k/v pair in object: %v", t))
}
default:
panic(fmt.Errorf("should not happen: unexpected runeType after opening '{' of object: %v", t))
}
}
// 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) error {
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, err := dec.peekRuneType()
if err != nil {
return err
}
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, err := dec.readRune()
if err != nil {
return err
}
switch t {
case jsonparse.RuneTypeArrayEnd:
return nil
default:
dec.unreadRune()
decodeNextMember:
if err := decodeMember(); err != nil {
return err
}
_, t, err := dec.readRune()
if err != nil {
return err
}
switch t {
case jsonparse.RuneTypeArrayComma:
goto decodeNextMember
case jsonparse.RuneTypeArrayEnd:
return nil
default:
panic(fmt.Errorf("should not happen: unexpected runeType after array item: %v", t))
}
}
}
func (dec *Decoder) decodeString(gTyp reflect.Type, out fastio.RuneWriter) *DecodeError {
if err := dec.expectRuneType('"', jsonparse.RuneTypeStringBeg, gTyp); err != nil {
return err
}
var uhex [3]byte
for {
c, t, err := dec.readRune()
if err != nil {
return err
}
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(fmt.Errorf("should not happen: unexpected rune after backslash: %q", c))
}
case jsonparse.RuneTypeStringEscUA:
uhex[0] = byte(c)
case jsonparse.RuneTypeStringEscUB:
uhex[1] = byte(c)
case jsonparse.RuneTypeStringEscUC:
uhex[2] = byte(c)
case jsonparse.RuneTypeStringEscUD:
c = hexToRune(uhex[0], uhex[1], uhex[2], byte(c))
handleUnicode:
if utf16.IsSurrogate(c) {
t, err := dec.peekRuneType()
if err != nil {
return err
}
if t != jsonparse.RuneTypeStringEsc {
_, _ = out.WriteRune(utf8.RuneError)
break
}
if err := dec.expectRune('\\', jsonparse.RuneTypeStringEsc); err != nil {
return err
}
t, err = dec.peekRuneType()
if err != nil {
return err
}
if t != jsonparse.RuneTypeStringEscU {
_, _ = out.WriteRune(utf8.RuneError)
break
}
if err := dec.expectRune('u', jsonparse.RuneTypeStringEscU); err != nil {
return err
}
b, _, err := dec.readRune()
if err != nil {
return err
}
uhex[0] = byte(b)
b, _, err = dec.readRune()
if err != nil {
return err
}
uhex[1] = byte(b)
b, _, err = dec.readRune()
if err != nil {
return err
}
uhex[2] = byte(b)
b, _, err = dec.readRune()
if err != nil {
return err
}
c2 := hexToRune(uhex[0], uhex[1], uhex[2], byte(b))
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(fmt.Errorf("should not happen: unexpected runeType in string: %v", t))
}
}
}
func (dec *Decoder) decodeBool(gTyp reflect.Type) (bool, *DecodeError) {
c, t, err := dec.readRune()
if err != nil {
return false, err
}
switch c {
case 't':
if err := dec.expectRune('r', jsonparse.RuneTypeTrueR); err != nil {
return false, err
}
if err := dec.expectRune('u', jsonparse.RuneTypeTrueU); err != nil {
return false, err
}
if err := dec.expectRune('e', jsonparse.RuneTypeTrueE); err != nil {
return false, err
}
return true, nil
case 'f':
if err := dec.expectRune('a', jsonparse.RuneTypeFalseA); err != nil {
return false, err
}
if err := dec.expectRune('l', jsonparse.RuneTypeFalseL); err != nil {
return false, err
}
if err := dec.expectRune('s', jsonparse.RuneTypeFalseS); err != nil {
return false, err
}
if err := dec.expectRune('e', jsonparse.RuneTypeFalseE); err != nil {
return false, err
}
return false, nil
default:
return false, dec.newTypeError(t.JSONType(), gTyp, nil)
}
}
func (dec *Decoder) decodeNull() *DecodeError {
if err := dec.expectRune('n', jsonparse.RuneTypeNullN); err != nil {
return err
}
if err := dec.expectRune('u', jsonparse.RuneTypeNullU); err != nil {
return err
}
if err := dec.expectRune('l', jsonparse.RuneTypeNullL1); err != nil {
return err
}
if err := dec.expectRune('l', jsonparse.RuneTypeNullL2); err != nil {
return err
}
return nil
}
func (dec *Decoder) maybeDecodeNull(nullOK bool) (ok bool, err *DecodeError) {
if nullOK {
t, err := dec.peekRuneType()
if err != nil {
return true, err
}
if t == jsonparse.RuneTypeNullN {
return true, dec.decodeNull()
}
}
return false, nil
}
|