1
2
3
4
5
6
7
8 package json
9
10 import (
11 "encoding"
12 "encoding/base64"
13 "fmt"
14 "reflect"
15 "strconv"
16 "strings"
17 "unicode"
18 "unicode/utf16"
19 "unicode/utf8"
20 _ "unsafe"
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 func Unmarshal(data []byte, v any) error {
98
99
100
101 var d decodeState
102 err := checkValid(data, &d.scan)
103 if err != nil {
104 return err
105 }
106
107 d.init(data)
108 return d.unmarshal(v)
109 }
110
111
112
113
114
115
116
117
118
119 type Unmarshaler interface {
120 UnmarshalJSON([]byte) error
121 }
122
123
124
125 type UnmarshalTypeError struct {
126 Value string
127 Type reflect.Type
128 Offset int64
129 Struct string
130 Field string
131 }
132
133 func (e *UnmarshalTypeError) Error() string {
134 if e.Struct != "" || e.Field != "" {
135 return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String()
136 }
137 return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
138 }
139
140
141
142
143
144 type UnmarshalFieldError struct {
145 Key string
146 Type reflect.Type
147 Field reflect.StructField
148 }
149
150 func (e *UnmarshalFieldError) Error() string {
151 return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
152 }
153
154
155
156 type InvalidUnmarshalError struct {
157 Type reflect.Type
158 }
159
160 func (e *InvalidUnmarshalError) Error() string {
161 if e.Type == nil {
162 return "json: Unmarshal(nil)"
163 }
164
165 if e.Type.Kind() != reflect.Pointer {
166 return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
167 }
168 return "json: Unmarshal(nil " + e.Type.String() + ")"
169 }
170
171 func (d *decodeState) unmarshal(v any) error {
172 rv := reflect.ValueOf(v)
173 if rv.Kind() != reflect.Pointer || rv.IsNil() {
174 return &InvalidUnmarshalError{reflect.TypeOf(v)}
175 }
176
177 d.scan.reset()
178 d.scanWhile(scanSkipSpace)
179
180
181 err := d.value(rv)
182 if err != nil {
183 return d.addErrorContext(err)
184 }
185 return d.savedError
186 }
187
188
189 type Number string
190
191
192 func (n Number) String() string { return string(n) }
193
194
195 func (n Number) Float64() (float64, error) {
196 return strconv.ParseFloat(string(n), 64)
197 }
198
199
200 func (n Number) Int64() (int64, error) {
201 return strconv.ParseInt(string(n), 10, 64)
202 }
203
204
205 type errorContext struct {
206 Struct reflect.Type
207 FieldStack []string
208 }
209
210
211 type decodeState struct {
212 data []byte
213 off int
214 opcode int
215 scan scanner
216 errorContext *errorContext
217 savedError error
218 useNumber bool
219 disallowUnknownFields bool
220 }
221
222
223 func (d *decodeState) readIndex() int {
224 return d.off - 1
225 }
226
227
228
229
230 const phasePanicMsg = "JSON decoder out of sync - data changing underfoot?"
231
232 func (d *decodeState) init(data []byte) *decodeState {
233 d.data = data
234 d.off = 0
235 d.savedError = nil
236 if d.errorContext != nil {
237 d.errorContext.Struct = nil
238
239 d.errorContext.FieldStack = d.errorContext.FieldStack[:0]
240 }
241 return d
242 }
243
244
245
246 func (d *decodeState) saveError(err error) {
247 if d.savedError == nil {
248 d.savedError = d.addErrorContext(err)
249 }
250 }
251
252
253 func (d *decodeState) addErrorContext(err error) error {
254 if d.errorContext != nil && (d.errorContext.Struct != nil || len(d.errorContext.FieldStack) > 0) {
255 switch err := err.(type) {
256 case *UnmarshalTypeError:
257 err.Struct = d.errorContext.Struct.Name()
258 fieldStack := d.errorContext.FieldStack
259 if err.Field != "" {
260 fieldStack = append(fieldStack, err.Field)
261 }
262 err.Field = strings.Join(fieldStack, ".")
263 }
264 }
265 return err
266 }
267
268
269 func (d *decodeState) skip() {
270 s, data, i := &d.scan, d.data, d.off
271 depth := len(s.parseState)
272 for {
273 op := s.step(s, data[i])
274 i++
275 if len(s.parseState) < depth {
276 d.off = i
277 d.opcode = op
278 return
279 }
280 }
281 }
282
283
284 func (d *decodeState) scanNext() {
285 if d.off < len(d.data) {
286 d.opcode = d.scan.step(&d.scan, d.data[d.off])
287 d.off++
288 } else {
289 d.opcode = d.scan.eof()
290 d.off = len(d.data) + 1
291 }
292 }
293
294
295
296 func (d *decodeState) scanWhile(op int) {
297 s, data, i := &d.scan, d.data, d.off
298 for i < len(data) {
299 newOp := s.step(s, data[i])
300 i++
301 if newOp != op {
302 d.opcode = newOp
303 d.off = i
304 return
305 }
306 }
307
308 d.off = len(data) + 1
309 d.opcode = d.scan.eof()
310 }
311
312
313
314
315
316
317
318
319
320 func (d *decodeState) rescanLiteral() {
321 data, i := d.data, d.off
322 Switch:
323 switch data[i-1] {
324 case '"':
325 for ; i < len(data); i++ {
326 switch data[i] {
327 case '\\':
328 i++
329 case '"':
330 i++
331 break Switch
332 }
333 }
334 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
335 for ; i < len(data); i++ {
336 switch data[i] {
337 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
338 '.', 'e', 'E', '+', '-':
339 default:
340 break Switch
341 }
342 }
343 case 't':
344 i += len("rue")
345 case 'f':
346 i += len("alse")
347 case 'n':
348 i += len("ull")
349 }
350 if i < len(data) {
351 d.opcode = stateEndValue(&d.scan, data[i])
352 } else {
353 d.opcode = scanEnd
354 }
355 d.off = i + 1
356 }
357
358
359
360
361 func (d *decodeState) value(v reflect.Value) error {
362 switch d.opcode {
363 default:
364 panic(phasePanicMsg)
365
366 case scanBeginArray:
367 if v.IsValid() {
368 if err := d.array(v); err != nil {
369 return err
370 }
371 } else {
372 d.skip()
373 }
374 d.scanNext()
375
376 case scanBeginObject:
377 if v.IsValid() {
378 if err := d.object(v); err != nil {
379 return err
380 }
381 } else {
382 d.skip()
383 }
384 d.scanNext()
385
386 case scanBeginLiteral:
387
388 start := d.readIndex()
389 d.rescanLiteral()
390
391 if v.IsValid() {
392 if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil {
393 return err
394 }
395 }
396 }
397 return nil
398 }
399
400 type unquotedValue struct{}
401
402
403
404
405
406 func (d *decodeState) valueQuoted() any {
407 switch d.opcode {
408 default:
409 panic(phasePanicMsg)
410
411 case scanBeginArray, scanBeginObject:
412 d.skip()
413 d.scanNext()
414
415 case scanBeginLiteral:
416 v := d.literalInterface()
417 switch v.(type) {
418 case nil, string:
419 return v
420 }
421 }
422 return unquotedValue{}
423 }
424
425
426
427
428
429
430 func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
431
432
433
434
435
436
437
438
439
440
441
442 v0 := v
443 haveAddr := false
444
445
446
447
448 if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() {
449 haveAddr = true
450 v = v.Addr()
451 }
452 for {
453
454
455 if v.Kind() == reflect.Interface && !v.IsNil() {
456 e := v.Elem()
457 if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) {
458 haveAddr = false
459 v = e
460 continue
461 }
462 }
463
464 if v.Kind() != reflect.Pointer {
465 break
466 }
467
468 if decodingNull && v.CanSet() {
469 break
470 }
471
472
473
474
475 if v.Elem().Kind() == reflect.Interface && v.Elem().Elem().Equal(v) {
476 v = v.Elem()
477 break
478 }
479 if v.IsNil() {
480 v.Set(reflect.New(v.Type().Elem()))
481 }
482 if v.Type().NumMethod() > 0 && v.CanInterface() {
483 if u, ok := v.Interface().(Unmarshaler); ok {
484 return u, nil, reflect.Value{}
485 }
486 if !decodingNull {
487 if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
488 return nil, u, reflect.Value{}
489 }
490 }
491 }
492
493 if haveAddr {
494 v = v0
495 haveAddr = false
496 } else {
497 v = v.Elem()
498 }
499 }
500 return nil, nil, v
501 }
502
503
504
505 func (d *decodeState) array(v reflect.Value) error {
506
507 u, ut, pv := indirect(v, false)
508 if u != nil {
509 start := d.readIndex()
510 d.skip()
511 return u.UnmarshalJSON(d.data[start:d.off])
512 }
513 if ut != nil {
514 d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
515 d.skip()
516 return nil
517 }
518 v = pv
519
520
521 switch v.Kind() {
522 case reflect.Interface:
523 if v.NumMethod() == 0 {
524
525 ai := d.arrayInterface()
526 v.Set(reflect.ValueOf(ai))
527 return nil
528 }
529
530 fallthrough
531 default:
532 d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
533 d.skip()
534 return nil
535 case reflect.Array, reflect.Slice:
536 break
537 }
538
539 i := 0
540 for {
541
542 d.scanWhile(scanSkipSpace)
543 if d.opcode == scanEndArray {
544 break
545 }
546
547
548 if v.Kind() == reflect.Slice {
549 if i >= v.Cap() {
550 v.Grow(1)
551 }
552 if i >= v.Len() {
553 v.SetLen(i + 1)
554 }
555 }
556
557 if i < v.Len() {
558
559 if err := d.value(v.Index(i)); err != nil {
560 return err
561 }
562 } else {
563
564 if err := d.value(reflect.Value{}); err != nil {
565 return err
566 }
567 }
568 i++
569
570
571 if d.opcode == scanSkipSpace {
572 d.scanWhile(scanSkipSpace)
573 }
574 if d.opcode == scanEndArray {
575 break
576 }
577 if d.opcode != scanArrayValue {
578 panic(phasePanicMsg)
579 }
580 }
581
582 if i < v.Len() {
583 if v.Kind() == reflect.Array {
584 for ; i < v.Len(); i++ {
585 v.Index(i).SetZero()
586 }
587 } else {
588 v.SetLen(i)
589 }
590 }
591 if i == 0 && v.Kind() == reflect.Slice {
592 v.Set(reflect.MakeSlice(v.Type(), 0, 0))
593 }
594 return nil
595 }
596
597 var nullLiteral = []byte("null")
598 var textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
599
600
601
602 func (d *decodeState) object(v reflect.Value) error {
603
604 u, ut, pv := indirect(v, false)
605 if u != nil {
606 start := d.readIndex()
607 d.skip()
608 return u.UnmarshalJSON(d.data[start:d.off])
609 }
610 if ut != nil {
611 d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
612 d.skip()
613 return nil
614 }
615 v = pv
616 t := v.Type()
617
618
619 if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
620 oi := d.objectInterface()
621 v.Set(reflect.ValueOf(oi))
622 return nil
623 }
624
625 var fields structFields
626
627
628
629
630
631 switch v.Kind() {
632 case reflect.Map:
633
634
635 switch t.Key().Kind() {
636 case reflect.String,
637 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
638 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
639 default:
640 if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) {
641 d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
642 d.skip()
643 return nil
644 }
645 }
646 if v.IsNil() {
647 v.Set(reflect.MakeMap(t))
648 }
649 case reflect.Struct:
650 fields = cachedTypeFields(t)
651
652 default:
653 d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
654 d.skip()
655 return nil
656 }
657
658 var mapElem reflect.Value
659 var origErrorContext errorContext
660 if d.errorContext != nil {
661 origErrorContext = *d.errorContext
662 }
663
664 for {
665
666 d.scanWhile(scanSkipSpace)
667 if d.opcode == scanEndObject {
668
669 break
670 }
671 if d.opcode != scanBeginLiteral {
672 panic(phasePanicMsg)
673 }
674
675
676 start := d.readIndex()
677 d.rescanLiteral()
678 item := d.data[start:d.readIndex()]
679 key, ok := unquoteBytes(item)
680 if !ok {
681 panic(phasePanicMsg)
682 }
683
684
685 var subv reflect.Value
686 destring := false
687
688 if v.Kind() == reflect.Map {
689 elemType := t.Elem()
690 if !mapElem.IsValid() {
691 mapElem = reflect.New(elemType).Elem()
692 } else {
693 mapElem.SetZero()
694 }
695 subv = mapElem
696 } else {
697 f := fields.byExactName[string(key)]
698 if f == nil {
699 f = fields.byFoldedName[string(foldName(key))]
700 }
701 if f != nil {
702 subv = v
703 destring = f.quoted
704 if d.errorContext == nil {
705 d.errorContext = new(errorContext)
706 }
707 for i, ind := range f.index {
708 if subv.Kind() == reflect.Pointer {
709 if subv.IsNil() {
710
711
712
713
714
715 if !subv.CanSet() {
716 d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem()))
717
718
719 subv = reflect.Value{}
720 destring = false
721 break
722 }
723 subv.Set(reflect.New(subv.Type().Elem()))
724 }
725 subv = subv.Elem()
726 }
727 if i < len(f.index)-1 {
728 d.errorContext.FieldStack = append(
729 d.errorContext.FieldStack,
730 subv.Type().Field(ind).Name,
731 )
732 }
733 subv = subv.Field(ind)
734 }
735 d.errorContext.Struct = t
736 d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name)
737 } else if d.disallowUnknownFields {
738 d.saveError(fmt.Errorf("json: unknown field %q", key))
739 }
740 }
741
742
743 if d.opcode == scanSkipSpace {
744 d.scanWhile(scanSkipSpace)
745 }
746 if d.opcode != scanObjectKey {
747 panic(phasePanicMsg)
748 }
749 d.scanWhile(scanSkipSpace)
750
751 if destring {
752 switch qv := d.valueQuoted().(type) {
753 case nil:
754 if err := d.literalStore(nullLiteral, subv, false); err != nil {
755 return err
756 }
757 case string:
758 if err := d.literalStore([]byte(qv), subv, true); err != nil {
759 return err
760 }
761 default:
762 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
763 }
764 } else {
765 if err := d.value(subv); err != nil {
766 return err
767 }
768 }
769
770
771
772 if v.Kind() == reflect.Map {
773 kt := t.Key()
774 var kv reflect.Value
775 if reflect.PointerTo(kt).Implements(textUnmarshalerType) {
776 kv = reflect.New(kt)
777 if err := d.literalStore(item, kv, true); err != nil {
778 return err
779 }
780 kv = kv.Elem()
781 } else {
782 switch kt.Kind() {
783 case reflect.String:
784 kv = reflect.New(kt).Elem()
785 kv.SetString(string(key))
786 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
787 s := string(key)
788 n, err := strconv.ParseInt(s, 10, 64)
789 if err != nil || kt.OverflowInt(n) {
790 d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
791 break
792 }
793 kv = reflect.New(kt).Elem()
794 kv.SetInt(n)
795 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
796 s := string(key)
797 n, err := strconv.ParseUint(s, 10, 64)
798 if err != nil || kt.OverflowUint(n) {
799 d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
800 break
801 }
802 kv = reflect.New(kt).Elem()
803 kv.SetUint(n)
804 default:
805 panic("json: Unexpected key type")
806 }
807 }
808 if kv.IsValid() {
809 v.SetMapIndex(kv, subv)
810 }
811 }
812
813
814 if d.opcode == scanSkipSpace {
815 d.scanWhile(scanSkipSpace)
816 }
817 if d.errorContext != nil {
818
819
820
821 d.errorContext.FieldStack = d.errorContext.FieldStack[:len(origErrorContext.FieldStack)]
822 d.errorContext.Struct = origErrorContext.Struct
823 }
824 if d.opcode == scanEndObject {
825 break
826 }
827 if d.opcode != scanObjectValue {
828 panic(phasePanicMsg)
829 }
830 }
831 return nil
832 }
833
834
835
836 func (d *decodeState) convertNumber(s string) (any, error) {
837 if d.useNumber {
838 return Number(s), nil
839 }
840 f, err := strconv.ParseFloat(s, 64)
841 if err != nil {
842 return nil, &UnmarshalTypeError{Value: "number " + s, Type: reflect.TypeFor[float64](), Offset: int64(d.off)}
843 }
844 return f, nil
845 }
846
847 var numberType = reflect.TypeFor[Number]()
848
849
850
851
852
853
854 func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error {
855
856 if len(item) == 0 {
857
858 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
859 return nil
860 }
861 isNull := item[0] == 'n'
862 u, ut, pv := indirect(v, isNull)
863 if u != nil {
864 return u.UnmarshalJSON(item)
865 }
866 if ut != nil {
867 if item[0] != '"' {
868 if fromQuoted {
869 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
870 return nil
871 }
872 val := "number"
873 switch item[0] {
874 case 'n':
875 val = "null"
876 case 't', 'f':
877 val = "bool"
878 }
879 d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())})
880 return nil
881 }
882 s, ok := unquoteBytes(item)
883 if !ok {
884 if fromQuoted {
885 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
886 }
887 panic(phasePanicMsg)
888 }
889 return ut.UnmarshalText(s)
890 }
891
892 v = pv
893
894 switch c := item[0]; c {
895 case 'n':
896
897
898 if fromQuoted && string(item) != "null" {
899 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
900 break
901 }
902 switch v.Kind() {
903 case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
904 v.SetZero()
905
906 }
907 case 't', 'f':
908 value := item[0] == 't'
909
910
911 if fromQuoted && string(item) != "true" && string(item) != "false" {
912 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
913 break
914 }
915 switch v.Kind() {
916 default:
917 if fromQuoted {
918 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
919 } else {
920 d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
921 }
922 case reflect.Bool:
923 v.SetBool(value)
924 case reflect.Interface:
925 if v.NumMethod() == 0 {
926 v.Set(reflect.ValueOf(value))
927 } else {
928 d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
929 }
930 }
931
932 case '"':
933 s, ok := unquoteBytes(item)
934 if !ok {
935 if fromQuoted {
936 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
937 }
938 panic(phasePanicMsg)
939 }
940 switch v.Kind() {
941 default:
942 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
943 case reflect.Slice:
944 if v.Type().Elem().Kind() != reflect.Uint8 {
945 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
946 break
947 }
948 b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
949 n, err := base64.StdEncoding.Decode(b, s)
950 if err != nil {
951 d.saveError(err)
952 break
953 }
954 v.SetBytes(b[:n])
955 case reflect.String:
956 t := string(s)
957 if v.Type() == numberType && !isValidNumber(t) {
958 return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)
959 }
960 v.SetString(t)
961 case reflect.Interface:
962 if v.NumMethod() == 0 {
963 v.Set(reflect.ValueOf(string(s)))
964 } else {
965 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
966 }
967 }
968
969 default:
970 if c != '-' && (c < '0' || c > '9') {
971 if fromQuoted {
972 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
973 }
974 panic(phasePanicMsg)
975 }
976 switch v.Kind() {
977 default:
978 if v.Kind() == reflect.String && v.Type() == numberType {
979
980
981 v.SetString(string(item))
982 break
983 }
984 if fromQuoted {
985 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
986 }
987 d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
988 case reflect.Interface:
989 n, err := d.convertNumber(string(item))
990 if err != nil {
991 d.saveError(err)
992 break
993 }
994 if v.NumMethod() != 0 {
995 d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
996 break
997 }
998 v.Set(reflect.ValueOf(n))
999
1000 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1001 n, err := strconv.ParseInt(string(item), 10, 64)
1002 if err != nil || v.OverflowInt(n) {
1003 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1004 break
1005 }
1006 v.SetInt(n)
1007
1008 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1009 n, err := strconv.ParseUint(string(item), 10, 64)
1010 if err != nil || v.OverflowUint(n) {
1011 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1012 break
1013 }
1014 v.SetUint(n)
1015
1016 case reflect.Float32, reflect.Float64:
1017 n, err := strconv.ParseFloat(string(item), v.Type().Bits())
1018 if err != nil || v.OverflowFloat(n) {
1019 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1020 break
1021 }
1022 v.SetFloat(n)
1023 }
1024 }
1025 return nil
1026 }
1027
1028
1029
1030
1031
1032
1033 func (d *decodeState) valueInterface() (val any) {
1034 switch d.opcode {
1035 default:
1036 panic(phasePanicMsg)
1037 case scanBeginArray:
1038 val = d.arrayInterface()
1039 d.scanNext()
1040 case scanBeginObject:
1041 val = d.objectInterface()
1042 d.scanNext()
1043 case scanBeginLiteral:
1044 val = d.literalInterface()
1045 }
1046 return
1047 }
1048
1049
1050 func (d *decodeState) arrayInterface() []any {
1051 var v = make([]any, 0)
1052 for {
1053
1054 d.scanWhile(scanSkipSpace)
1055 if d.opcode == scanEndArray {
1056 break
1057 }
1058
1059 v = append(v, d.valueInterface())
1060
1061
1062 if d.opcode == scanSkipSpace {
1063 d.scanWhile(scanSkipSpace)
1064 }
1065 if d.opcode == scanEndArray {
1066 break
1067 }
1068 if d.opcode != scanArrayValue {
1069 panic(phasePanicMsg)
1070 }
1071 }
1072 return v
1073 }
1074
1075
1076 func (d *decodeState) objectInterface() map[string]any {
1077 m := make(map[string]any)
1078 for {
1079
1080 d.scanWhile(scanSkipSpace)
1081 if d.opcode == scanEndObject {
1082
1083 break
1084 }
1085 if d.opcode != scanBeginLiteral {
1086 panic(phasePanicMsg)
1087 }
1088
1089
1090 start := d.readIndex()
1091 d.rescanLiteral()
1092 item := d.data[start:d.readIndex()]
1093 key, ok := unquote(item)
1094 if !ok {
1095 panic(phasePanicMsg)
1096 }
1097
1098
1099 if d.opcode == scanSkipSpace {
1100 d.scanWhile(scanSkipSpace)
1101 }
1102 if d.opcode != scanObjectKey {
1103 panic(phasePanicMsg)
1104 }
1105 d.scanWhile(scanSkipSpace)
1106
1107
1108 m[key] = d.valueInterface()
1109
1110
1111 if d.opcode == scanSkipSpace {
1112 d.scanWhile(scanSkipSpace)
1113 }
1114 if d.opcode == scanEndObject {
1115 break
1116 }
1117 if d.opcode != scanObjectValue {
1118 panic(phasePanicMsg)
1119 }
1120 }
1121 return m
1122 }
1123
1124
1125
1126
1127 func (d *decodeState) literalInterface() any {
1128
1129 start := d.readIndex()
1130 d.rescanLiteral()
1131
1132 item := d.data[start:d.readIndex()]
1133
1134 switch c := item[0]; c {
1135 case 'n':
1136 return nil
1137
1138 case 't', 'f':
1139 return c == 't'
1140
1141 case '"':
1142 s, ok := unquote(item)
1143 if !ok {
1144 panic(phasePanicMsg)
1145 }
1146 return s
1147
1148 default:
1149 if c != '-' && (c < '0' || c > '9') {
1150 panic(phasePanicMsg)
1151 }
1152 n, err := d.convertNumber(string(item))
1153 if err != nil {
1154 d.saveError(err)
1155 }
1156 return n
1157 }
1158 }
1159
1160
1161
1162 func getu4(s []byte) rune {
1163 if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
1164 return -1
1165 }
1166 var r rune
1167 for _, c := range s[2:6] {
1168 switch {
1169 case '0' <= c && c <= '9':
1170 c = c - '0'
1171 case 'a' <= c && c <= 'f':
1172 c = c - 'a' + 10
1173 case 'A' <= c && c <= 'F':
1174 c = c - 'A' + 10
1175 default:
1176 return -1
1177 }
1178 r = r*16 + rune(c)
1179 }
1180 return r
1181 }
1182
1183
1184
1185 func unquote(s []byte) (t string, ok bool) {
1186 s, ok = unquoteBytes(s)
1187 t = string(s)
1188 return
1189 }
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200 func unquoteBytes(s []byte) (t []byte, ok bool) {
1201 if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
1202 return
1203 }
1204 s = s[1 : len(s)-1]
1205
1206
1207
1208
1209 r := 0
1210 for r < len(s) {
1211 c := s[r]
1212 if c == '\\' || c == '"' || c < ' ' {
1213 break
1214 }
1215 if c < utf8.RuneSelf {
1216 r++
1217 continue
1218 }
1219 rr, size := utf8.DecodeRune(s[r:])
1220 if rr == utf8.RuneError && size == 1 {
1221 break
1222 }
1223 r += size
1224 }
1225 if r == len(s) {
1226 return s, true
1227 }
1228
1229 b := make([]byte, len(s)+2*utf8.UTFMax)
1230 w := copy(b, s[0:r])
1231 for r < len(s) {
1232
1233
1234
1235 if w >= len(b)-2*utf8.UTFMax {
1236 nb := make([]byte, (len(b)+utf8.UTFMax)*2)
1237 copy(nb, b[0:w])
1238 b = nb
1239 }
1240 switch c := s[r]; {
1241 case c == '\\':
1242 r++
1243 if r >= len(s) {
1244 return
1245 }
1246 switch s[r] {
1247 default:
1248 return
1249 case '"', '\\', '/', '\'':
1250 b[w] = s[r]
1251 r++
1252 w++
1253 case 'b':
1254 b[w] = '\b'
1255 r++
1256 w++
1257 case 'f':
1258 b[w] = '\f'
1259 r++
1260 w++
1261 case 'n':
1262 b[w] = '\n'
1263 r++
1264 w++
1265 case 'r':
1266 b[w] = '\r'
1267 r++
1268 w++
1269 case 't':
1270 b[w] = '\t'
1271 r++
1272 w++
1273 case 'u':
1274 r--
1275 rr := getu4(s[r:])
1276 if rr < 0 {
1277 return
1278 }
1279 r += 6
1280 if utf16.IsSurrogate(rr) {
1281 rr1 := getu4(s[r:])
1282 if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
1283
1284 r += 6
1285 w += utf8.EncodeRune(b[w:], dec)
1286 break
1287 }
1288
1289 rr = unicode.ReplacementChar
1290 }
1291 w += utf8.EncodeRune(b[w:], rr)
1292 }
1293
1294
1295 case c == '"', c < ' ':
1296 return
1297
1298
1299 case c < utf8.RuneSelf:
1300 b[w] = c
1301 r++
1302 w++
1303
1304
1305 default:
1306 rr, size := utf8.DecodeRune(s[r:])
1307 r += size
1308 w += utf8.EncodeRune(b[w:], rr)
1309 }
1310 }
1311 return b[0:w], true
1312 }
1313
View as plain text