-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjscandec.go
2897 lines (2619 loc) · 78.1 KB
/
jscandec.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
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
package jscandec
import (
"bytes"
"encoding"
"encoding/json"
"errors"
"math"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/romshark/jscan-experimental-decoder/internal/atoi"
"github.com/romshark/jscan-experimental-decoder/internal/jsonnum"
"github.com/romshark/jscan-experimental-decoder/internal/unescape"
"github.com/romshark/jscan/v2"
)
var (
ErrStringTagOptionOnUnsupportedType = errors.New(
"invalid use of the `string` tag option on unsupported type",
)
ErrNilDest = errors.New("decoding to nil pointer")
ErrUnexpectedValue = errors.New("unexpected value")
ErrUnknownField = errors.New("unknown field")
ErrIntegerOverflow = errors.New("integer overflow")
)
// Number represents a JSON number literal.
type Number string
// String returns the literal text of the number.
func (n Number) String() string { return string(n) }
// Float64 returns the number as a float64.
func (n Number) Float64() (float64, error) {
return strconv.ParseFloat(string(n), 64)
}
// Int64 returns the number as an int64.
func (n Number) Int64() (int64, error) {
return strconv.ParseInt(string(n), 10, 64)
}
var tpNumber = reflect.TypeOf(Number(""))
type ExpectType int8
const (
_ ExpectType = iota
// ExpectTypeNumber is the type `jscandec.Number`
ExpectTypeNumber
// ExpectTypeJSONUnmarshaler is any type that implements
// the encoding/json.Unmarshaler interface
ExpectTypeJSONUnmarshaler
// ExpectTypeTextUnmarshaler is any type that implements
// the encoding.TextUnmarshaler interface
ExpectTypeTextUnmarshaler
// ExpectTypePtr is any pointer type
ExpectTypePtr
// ExpectTypePtrRecur is any recursive pointer type (used for recursive struct fields)
ExpectTypePtrRecur
// ExpectTypeAny is type `any`
ExpectTypeAny
// ExpectTypeMap is any map type
ExpectTypeMap
// ExpectTypeMapStringString is `map[string]string`
ExpectTypeMapStringString
// ExpectTypeMapRecur is any recursive map type (used for recursive struct fields)
ExpectTypeMapRecur
// ExpectTypeArray is any array type except zero-length array
ExpectTypeArray
// ExpectTypeArrayLen0 is any zero-length array type (like [0]int)
ExpectTypeArrayLen0
// ExpectTypeSlice is any slice type
ExpectTypeSlice
// ExpectTypeSliceRecur is a recursive slice type (used for recursive struct fields)
ExpectTypeSliceRecur
// ExpectTypeSliceEmptyStruct is type `[]struct{}`
ExpectTypeSliceEmptyStruct
// ExpectTypeSliceBool is type `[]bool`
ExpectTypeSliceBool
// ExpectTypeSliceString is type `[]string`
ExpectTypeSliceString
// ExpectTypeSliceInt is type `[]int`
ExpectTypeSliceInt
// ExpectTypeSliceInt8 is type `[]int8`
ExpectTypeSliceInt8
// ExpectTypeSliceInt16 is type `[]int16`
ExpectTypeSliceInt16
// ExpectTypeSliceInt32 is type `[]int32`
ExpectTypeSliceInt32
// ExpectTypeSliceInt64 is type `[]int64`
ExpectTypeSliceInt64
// ExpectTypeSliceUint is type `[]uint`
ExpectTypeSliceUint
// ExpectTypeSliceUint8 is type `[]uint8`
ExpectTypeSliceUint8
// ExpectTypeSliceUint16 is type `[]uint16`
ExpectTypeSliceUint16
// ExpectTypeSliceUint32 is type `[]uint32`
ExpectTypeSliceUint32
// ExpectTypeSliceUint64 is type `[]uint64`
ExpectTypeSliceUint64
// ExpectTypeSliceFloat32 is type `[]float32`
ExpectTypeSliceFloat32
// ExpectTypeSliceFloat64 is type `[]float64`
ExpectTypeSliceFloat64
// ExpectTypeStruct is any struct type except `struct{}`
ExpectTypeStruct
// ExpectTypeStruct is any recursive struct type
ExpectTypeStructRecur
// ExpectTypeEmptyStruct is type `struct{}`
ExpectTypeEmptyStruct
// ExpectTypeBool is type `bool`
ExpectTypeBool
// ExpectTypeStr is type `string`
ExpectTypeStr
// ExpectTypeFloat32 is type `float32`
ExpectTypeFloat32
// ExpectTypeFloat64 is type `float64`
ExpectTypeFloat64
// ExpectTypeInt is type `int`
ExpectTypeInt
// ExpectTypeInt8 is type `int8`
ExpectTypeInt8
// ExpectTypeInt16 is type `int16`
ExpectTypeInt16
// ExpectTypeInt32 is type `int32`
ExpectTypeInt32
// ExpectTypeInt64 is type `int64`
ExpectTypeInt64
// ExpectTypeUint is type `uint`
ExpectTypeUint
// ExpectTypeUint8 is type `uint8`
ExpectTypeUint8
// ExpectTypeUint16 is type `uint16`
ExpectTypeUint16
// ExpectTypeUint32 is type `uint32`
ExpectTypeUint32
// ExpectTypeUint64 is type `uint64`
ExpectTypeUint64
// ExpectTypeBoolString is type `bool` with `json:",string"` tag
ExpectTypeBoolString
// ExpectTypeStrString is type `string` with `json:",string"` tag
ExpectTypeStrString
// ExpectTypeFloat32String is type `float32` with `json:",string"` tag
ExpectTypeFloat32String
// ExpectTypeFloat64String is type `float32` with `json:",string"` tag
ExpectTypeFloat64String
// ExpectTypeIntString is type `int` with `json:",string"` tag
ExpectTypeIntString
// ExpectTypeInt8String is type `int8` with `json:",string"` tag
ExpectTypeInt8String
// ExpectTypeInt16String is type `int16` with `json:",string"` tag
ExpectTypeInt16String
// ExpectTypeInt32String is type `int32` with `json:",string"` tag
ExpectTypeInt32String
// ExpectTypeInt64String is type `int64` with `json:",string"` tag
ExpectTypeInt64String
// ExpectTypeUintString is type `uint` with `json:",string"` tag
ExpectTypeUintString
// ExpectTypeUint8String is type `uint8` with `json:",string"` tag
ExpectTypeUint8String
// ExpectTypeUint16String is type `uint16` with `json:",string"` tag
ExpectTypeUint16String
// ExpectTypeUint32String is type `uint32` with `json:",string"` tag
ExpectTypeUint32String
// ExpectTypeUint64String is type `uint64` with `json:",string"` tag
ExpectTypeUint64String
)
func (t ExpectType) String() string {
switch t {
case ExpectTypeNumber:
return "jscandec.Number"
case ExpectTypeJSONUnmarshaler:
return "interface{UnmarshalJSON([]byte)error}"
case ExpectTypeTextUnmarshaler:
return "interface{UnmarshalText([]byte)error}"
case ExpectTypePtr:
return "*"
case ExpectTypePtrRecur:
return "*⟲"
case ExpectTypeAny:
return "any"
case ExpectTypeMap:
return "map"
case ExpectTypeMapStringString:
return "map[string]string"
case ExpectTypeMapRecur:
return "map⟲"
case ExpectTypeArray:
return "array"
case ExpectTypeArrayLen0:
return "[0]array"
case ExpectTypeSlice:
return "slice"
case ExpectTypeSliceRecur:
return "slice⟲"
case ExpectTypeSliceEmptyStruct:
return "[]struct{}"
case ExpectTypeSliceBool:
return "[]bool"
case ExpectTypeSliceString:
return "[]string"
case ExpectTypeSliceInt:
return "[]int"
case ExpectTypeSliceInt8:
return "[]int8"
case ExpectTypeSliceInt16:
return "[]int16"
case ExpectTypeSliceInt32:
return "[]int32"
case ExpectTypeSliceInt64:
return "[]int64"
case ExpectTypeSliceUint:
return "[]uint"
case ExpectTypeSliceUint8:
return "[]uint8"
case ExpectTypeSliceUint16:
return "[]uint16"
case ExpectTypeSliceUint32:
return "[]uint32"
case ExpectTypeSliceUint64:
return "[]uint64"
case ExpectTypeSliceFloat32:
return "[]float32"
case ExpectTypeSliceFloat64:
return "[]float64"
case ExpectTypeStruct:
return "struct"
case ExpectTypeStructRecur:
return "struct⟲"
case ExpectTypeEmptyStruct:
return "struct{}"
case ExpectTypeBool:
return "boolean"
case ExpectTypeStr:
return "string"
case ExpectTypeFloat32:
return "float32"
case ExpectTypeFloat64:
return "float64"
case ExpectTypeInt:
return "int"
case ExpectTypeInt8:
return "int8"
case ExpectTypeInt16:
return "int16"
case ExpectTypeInt32:
return "int32"
case ExpectTypeInt64:
return "int64"
case ExpectTypeUint:
return "uint"
case ExpectTypeUint8:
return "uint8"
case ExpectTypeUint16:
return "uint16"
case ExpectTypeUint32:
return "uint32"
case ExpectTypeUint64:
return "uint64"
case ExpectTypeBoolString:
return "string(boolean)"
case ExpectTypeStrString:
return "string(string)"
case ExpectTypeFloat32String:
return "string(float32)"
case ExpectTypeFloat64String:
return "string(float64)"
case ExpectTypeIntString:
return "string(int)"
case ExpectTypeInt8String:
return "string(int8)"
case ExpectTypeInt16String:
return "string(int16)"
case ExpectTypeInt32String:
return "string(int32)"
case ExpectTypeInt64String:
return "string(int64)"
case ExpectTypeUintString:
return "string(uint)"
case ExpectTypeUint8String:
return "string(uint8)"
case ExpectTypeUint16String:
return "string(uint16)"
case ExpectTypeUint32String:
return "string(uint32)"
case ExpectTypeUint64String:
return "string(uint64)"
}
return ""
}
// isElemComposite returns false for non-composite slice item types,
// otherwise returns true.
func (t ExpectType) isElemComposite() bool {
switch t {
case ExpectTypePtr,
ExpectTypeArrayLen0, // Zero-length arrays require no memory
ExpectTypeEmptyStruct,
ExpectTypeBool,
ExpectTypeStr,
ExpectTypeFloat32,
ExpectTypeFloat64,
ExpectTypeInt,
ExpectTypeInt8,
ExpectTypeInt16,
ExpectTypeInt32,
ExpectTypeInt64,
ExpectTypeUint,
ExpectTypeUint8,
ExpectTypeUint16,
ExpectTypeUint32,
ExpectTypeUint64:
return false
// Types such as `ExpectTypeBoolString` will never be used for slice items.
}
return true
}
// fieldStackFrame identifies a field within a struct frame.
type fieldStackFrame struct {
// FrameIndex defines the stack index of the field's value frame.
FrameIndex uint32
// Name defines either the name of the field in the struct
// or the json struct tag if any.
Name string
}
type recursionStackFrame struct {
// Dest stores the destination pointer for the recursive frame to be reset to.
Dest unsafe.Pointer
// Offset stores the offset for the recursive frame to be reset to.
Offset uintptr
// ContainerFrame stores the index of the recursive container frame.
ContainerFrame uint32
}
type stackFrame[S []byte | string] struct {
// Fields is only relevant to structs.
// For every other type Fields is always nil.
Fields []fieldStackFrame
// RType is relevant to JSONUnmarshaler frames only.
RType reflect.Type
// Typ is relevant to maps and slices only
Typ *typ
// MapValueType is relevant to map frames only.
MapValueType *typ
// Size defines the number of bytes the data would occupy in memory.
// Size caches reflect.Type.Size() for faster access.
Size uintptr
// RecursionStack is only relevant to ExpectTypeStructRecur and
// keeps track of its recursion through pointers/maps/slices.
RecursionStack []recursionStackFrame
// Cap defines the capacity of the parent array for array item frames.
Cap int
// RecurFrame defines the index of the recursive ExpectTypeStructRecur frame and
// is relevant to ExpectTypePtrRecur, ExpectTypeMapRecur and ExpectTypeSliceRecur.
RecurFrame int
// Len is relevant to array frames only and defines their current length.
Len int // Overwritten at runtime
// Dest defines the destination memory to write the data to.
// Dest is set at runtime and must be reset on every call to Decode
// to avoid keeping a pointer to the allocated data and allow the GC
// to clean it up if necessary.
Dest unsafe.Pointer // Overwritten at runtime
// Offset is used at runtime for pointer arithmetics if the decoder is
// currently inside of an array or slice.
// For struct fields however, Offset is assigned statically at decoder init time.
Offset uintptr // Overwritten at runtime
// ParentFrameIndex defines either the index of the composite parent object
// in the stack, or noParentFrame.
ParentFrameIndex uint32
// Type defines what data type is expected at this frame.
// Same as Size, Type kind could be taken from reflect.Type but it's
// slower than storing it here.
Type ExpectType
// MapCanUseAssignFaststr is only relevant to map frames and indicates whether
// mapassign_faststr can be used instead of mapassign.
MapCanUseAssignFaststr bool
}
// noParentFrame uses math.MaxUint32 because the length of the decoder stack
// is very unlikely to reach 4_294_967_295.
const noParentFrame = uint32(math.MaxUint32)
// DefaultInitOptions are to be used by default. DO NOT MUTATE.
var DefaultInitOptions = &InitOptions{
DisallowStringTagOptOnUnsupportedTypes: false,
}
// DefaultOptions are to be used by default. DO NOT MUTATE.
var DefaultOptions = &DecodeOptions{
DisallowUnknownFields: false,
}
// Unmarshal dynamically allocates new decoder and tokenizer instances and
// unmarshals the JSON contents of s into t.
// Unmarshal is primarily a drop-in replacement for the standard encoding/json.Unmarshal
// and behaves identically except for error messages. To significantly improve
// performance by avoiding dynamic decoder and tokenizer allocation and reflection at
// runtime create a reusable decoder instance using NewDecoder.
func Unmarshal[S []byte | string, T any](s S, t *T) error {
if t == nil {
return ErrNilDest
}
stack := make([]stackFrame[S], 0, 4)
var err error
stack, err = appendTypeToStack(stack, reflect.TypeOf(*t), DefaultInitOptions)
if err != nil {
return err
}
tokenizer := jscan.NewTokenizer[S](
len(stack)+1, len(s)/2,
)
d := Decoder[S, T]{tokenizer: tokenizer, stackExp: stack}
d.init()
if _, err := d.Decode(s, t, DefaultOptions); err != nil &&
err != ErrStringTagOptionOnUnsupportedType {
return err
}
return nil
}
// Decoder is a reusable decoder instance.
type Decoder[S []byte | string, T any] struct {
tokenizer *jscan.Tokenizer[S]
stackExp []stackFrame[S]
parseInt func(s S) (int, error)
parseUint func(s S) (uint, error)
parseFloat32 func(s S) (float32, error)
parseFloat64 func(s S) (float64, error)
}
// NewDecoder creates a new reusable decoder instance.
// In case there are multiple decoder instances for different types of T,
// tokenizer is recommended to be shared across them, yet the decoders must
// not be used concurrently!
func NewDecoder[S []byte | string, T any](
tokenizer *jscan.Tokenizer[S],
options *InitOptions,
) (*Decoder[S, T], error) {
d := &Decoder[S, T]{
tokenizer: tokenizer,
stackExp: make([]stackFrame[S], 0, 4),
}
var z T
var err error
d.stackExp, err = appendTypeToStack(d.stackExp, reflect.TypeOf(z), options)
if err != nil {
return nil, err
}
d.init()
return d, nil
}
func (d *Decoder[S, T]) init() {
// 64-bit system
d.parseInt = func(s S) (int, error) {
i, overflow := atoi.I64(s)
if overflow {
return 0, ErrIntegerOverflow
}
return int(i), nil
}
d.parseUint = func(s S) (uint, error) {
i, overflow := atoi.U64(s)
if overflow {
return 0, ErrIntegerOverflow
}
return uint(i), nil
}
if unsafe.Sizeof(int(0)) != 8 {
// 32-bit system
d.parseInt = func(s S) (int, error) {
i, overflow := atoi.I32(s)
if overflow {
return 0, ErrIntegerOverflow
}
return int(i), nil
}
d.parseUint = func(s S) (uint, error) {
i, overflow := atoi.U32(s)
if overflow {
return 0, ErrIntegerOverflow
}
return uint(i), nil
}
}
d.parseFloat32 = func(s S) (float32, error) {
v, err := strconv.ParseFloat(string(s), 32)
if err != nil {
return 0, err
}
return float32(v), nil
}
d.parseFloat64 = func(s S) (float64, error) {
v, err := strconv.ParseFloat(string(s), 64)
if err != nil {
return 0, err
}
return v, nil
}
var sz S
if _, ok := any(sz).([]byte); ok {
// Avoid copying the slice data
d.parseFloat32 = func(s S) (float32, error) {
su := unsafe.String(unsafe.SliceData([]byte(s)), len(s))
v, err := strconv.ParseFloat(su, 32)
if err != nil {
return 0, err
}
return float32(v), nil
}
d.parseFloat64 = func(s S) (float64, error) {
su := unsafe.String(unsafe.SliceData([]byte(s)), len(s))
v, err := strconv.ParseFloat(su, 64)
if err != nil {
return 0, err
}
return v, nil
}
}
}
var (
tpJSONUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
tpTextUnmarshaler = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
)
type (
interfaceSupport uint8
)
const (
interfaceSupportNone interfaceSupport = iota
interfaceSupportCopy
interfaceSupportPtr
)
// determineJSONUnmarshalerSupport returns:
//
// - jsonUnmarshalerSupportNone if t doesn't implement encoding/json.Unmarshaler
// - jsonUnmarshalerSupportCopy if t implements encoding/json.Unmarshaler
// - jsonUnmarshalerSupportPtr if pointer to t implements encoding/json.Unmarshaler.
func determineJSONUnmarshalerSupport(t reflect.Type) interfaceSupport {
if t.AssignableTo(tpJSONUnmarshaler) {
return interfaceSupportCopy
}
if t.Kind() != reflect.Ptr && reflect.PointerTo(t).AssignableTo(tpJSONUnmarshaler) {
return interfaceSupportPtr
}
return interfaceSupportNone
}
// determineTextUnmarshalerSupport returns:
//
// - textUnmarshalerSupportNone if t doesn't implement encoding/json.Unmarshaler
// - textUnmarshalerSupportCopy if t implements encoding/json.Unmarshaler
// - textUnmarshalerSupportPtr if pointer to t implements encoding/json.Unmarshaler.
func determineTextUnmarshalerSupport(t reflect.Type) interfaceSupport {
if t.AssignableTo(tpTextUnmarshaler) {
return interfaceSupportCopy
}
if t.Kind() != reflect.Ptr && reflect.PointerTo(t).AssignableTo(tpTextUnmarshaler) {
return interfaceSupportPtr
}
return interfaceSupportNone
}
// InitOptions are options for the constructor function NewDecoder[S, T].
type InitOptions struct {
// DisallowStringTagOptOnUnsupportedTypes will make NewDecoder return
// ErrStringTagOptionOnUnsupportedType if a `json:",string"` struct tag option is
// used on an unsupported type.
DisallowStringTagOptOnUnsupportedTypes bool
}
// DecodeOptions are options for the method *Decoder[S, T].Decode.
type DecodeOptions struct {
// DisallowUnknownFields will make Decode return ErrUnknownField
// when encountering an unknown struct field.
DisallowUnknownFields bool
// DisableFieldNameUnescaping disables unescaping of struct field names
// before matching which is enabled by default as a backward-compatibility feature
// of encoding/json.
//
// For example, the following JSON input:
//
// `{ "\u0069\u0064": "value" }`
//
// will match field ID in the following type:
//
// struct { ID string `json:"id"` }
//
// because "\u0069\u0064" is first unescaped to "id" before matching.
// DisableFieldNameUnescaping=true disables this behavior and will treat
// property "\u0069\u0064" as an unknown field instead.
DisableFieldNameUnescaping bool
// DisableCaseInsensitiveMatching will disable case-insensitive struct field
// matching that's enabled by default as a backward-compatibility feature
// of encoding/json.
//
// For example, the following JSON input:
//
// `{ "A": 42 }`
//
// will match field A in the following type:
//
// struct { A int `json:"a"` }
//
// DisableCaseInsensitiveMatching=true disables this behavior and will treat
// property "A" as an unknown field instead.
DisableCaseInsensitiveMatching bool
}
// Decode unmarshals the JSON contents of s into t.
// When S is string the decoder will not copy string values and will instead refer
// to the source string instead since Go strings are guaranteed to be immutable.
// When S is []byte all strings are copied.
//
// Tip: To improve performance reducing dynamic memory allocations define
// options as a variable and pass the pointer. Don't initialize it like this:
//
// d.Decode(input, &v, &jscandec.DecodeOptions{DisallowUnknownFields: true})
//
// allocate the options to a variable and pass the variable instead:
//
// d.Decode(input, &v, predefinedOptions)
func (d *Decoder[S, T]) Decode(
s S, t *T, options *DecodeOptions,
) (errIndex int, err error) {
defer func() {
for i := range d.stackExp {
d.stackExp[i].Dest = nil
}
}()
if t == nil {
return 0, ErrNilDest
}
si := uint32(0)
d.stackExp[0].Dest = unsafe.Pointer(t)
errTok := d.tokenizer.Tokenize(s, func(tokens []jscan.Token[S]) (exit bool) {
// ti stands for the token index and points at the current token
for ti := 0; ti < len(tokens); {
switch tokens[ti].Type {
case jscan.TokenTypeFalse, jscan.TokenTypeTrue:
switch d.stackExp[si].Type {
case ExpectTypeAny:
p := unsafe.Pointer(
uintptr(d.stackExp[si].Dest) + d.stackExp[si].Offset,
)
v := tokens[ti].Type == jscan.TokenTypeTrue
*(*any)(p) = v
case ExpectTypeBool:
p := unsafe.Pointer(
uintptr(d.stackExp[si].Dest) + d.stackExp[si].Offset,
)
*(*bool)(p) = tokens[ti].Type == jscan.TokenTypeTrue
case ExpectTypePtr:
goto ON_PTR
case ExpectTypeJSONUnmarshaler:
goto ON_JSON_UNMARSHALER
default:
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
ti++
goto ON_VAL_END
case jscan.TokenTypeInteger:
p := unsafe.Pointer(
uintptr(d.stackExp[si].Dest) + d.stackExp[si].Offset,
)
switch d.stackExp[si].Type {
case ExpectTypeAny:
tv := s[tokens[ti].Index:tokens[ti].End]
var sz S
var su string
switch any(sz).(type) {
case []byte:
su = unsafe.String(unsafe.SliceData([]byte(tv)), len(tv))
case string:
su = string(tv)
}
v, errParse := strconv.ParseFloat(su, 64)
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*any)(p) = v
case ExpectTypeUint:
if s[tokens[ti].Index] == '-' {
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
if i, e := d.parseUint(s[tokens[ti].Index:tokens[ti].End]); e != nil {
// Invalid unsigned integer
errIndex, err = tokens[ti].Index, e
return true
} else {
*(*uint)(p) = i
}
case ExpectTypeInt:
if i, e := d.parseInt(s[tokens[ti].Index:tokens[ti].End]); e != nil {
// Invalid signed integer
errIndex, err = tokens[ti].Index, e
return true
} else {
*(*int)(p) = i
}
case ExpectTypeUint8:
if s[tokens[ti].Index] == '-' {
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
v, overflow := atoi.U8(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 8-bit unsigned integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*uint8)(p) = v
case ExpectTypeUint16:
if s[tokens[ti].Index] == '-' {
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
v, overflow := atoi.U16(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 16-bit unsigned integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*uint16)(p) = v
case ExpectTypeUint32:
if s[tokens[ti].Index] == '-' {
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
v, overflow := atoi.U32(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 32-bit unsigned integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*uint32)(p) = v
case ExpectTypeUint64:
if s[tokens[ti].Index] == '-' {
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
v, overflow := atoi.U64(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 64-bit unsigned integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*uint64)(p) = v
case ExpectTypeInt8:
v, overflow := atoi.I8(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 8-bit signed integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*int8)(p) = v
case ExpectTypeInt16:
v, overflow := atoi.I16(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 16-bit signed integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*int16)(p) = v
case ExpectTypeInt32:
v, overflow := atoi.I32(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 32-bit signed integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*int32)(p) = v
case ExpectTypeInt64:
v, overflow := atoi.I64(s[tokens[ti].Index:tokens[ti].End])
if overflow {
// Invalid 64-bit signed integer
errIndex, err = tokens[ti].Index, ErrIntegerOverflow
return true
}
*(*int64)(p) = v
case ExpectTypeFloat32:
if tokens[ti].End-tokens[ti].Index < len("16777216") {
// Numbers below this length are guaranteed to be smaller 1<<24
// And float32(i32) is faster than calling parseFloat32
i32, errParse := tokens[ti].Int32(s)
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float32)(p) = float32(i32)
} else {
v, errParse := d.parseFloat32(s[tokens[ti].Index:tokens[ti].End])
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float32)(p) = v
}
case ExpectTypeFloat64:
if tokens[ti].End-tokens[ti].Index < len("9007199254740992") {
// Numbers below this length are guaranteed to be smaller 1<<53
// And float64(i64) is faster than calling parseFloat64
i64, errParse := tokens[ti].Int64(s)
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float64)(p) = float64(i64)
} else {
v, errParse := d.parseFloat64(s[tokens[ti].Index:tokens[ti].End])
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float64)(p) = v
}
case ExpectTypeNumber:
*(*Number)(p) = Number(s[tokens[ti].Index:tokens[ti].End])
case ExpectTypePtr:
goto ON_PTR
case ExpectTypeJSONUnmarshaler:
goto ON_JSON_UNMARSHALER
default:
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
ti++
goto ON_VAL_END
case jscan.TokenTypeNumber:
p := unsafe.Pointer(
uintptr(d.stackExp[si].Dest) + d.stackExp[si].Offset,
)
switch d.stackExp[si].Type {
case ExpectTypeAny:
tv := s[tokens[ti].Index:tokens[ti].End]
var sz S
var su string
switch any(sz).(type) {
case []byte:
su = unsafe.String(unsafe.SliceData([]byte(tv)), len(tv))
case string:
su = string(tv)
}
v, errParse := strconv.ParseFloat(su, 64)
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*any)(p) = v
case ExpectTypeFloat32:
v, errParse := d.parseFloat32(s[tokens[ti].Index:tokens[ti].End])
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float32)(p) = v
case ExpectTypeFloat64:
v, errParse := d.parseFloat64(s[tokens[ti].Index:tokens[ti].End])
if errParse != nil {
errIndex, err = tokens[ti].Index, errParse
return true
}
*(*float64)(p) = v
case ExpectTypeNumber:
*(*Number)(p) = Number(s[tokens[ti].Index:tokens[ti].End])
case ExpectTypePtr:
goto ON_PTR
case ExpectTypeJSONUnmarshaler:
goto ON_JSON_UNMARSHALER
default:
errIndex, err = tokens[ti].Index, ErrUnexpectedValue
return true
}
ti++
goto ON_VAL_END
case jscan.TokenTypeString:
p := unsafe.Pointer(
uintptr(d.stackExp[si].Dest) + d.stackExp[si].Offset,
)
switch d.stackExp[si].Type {
case ExpectTypeTextUnmarshaler: