forked from go-json-experiment/json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arshal_default.go
1736 lines (1650 loc) · 52.6 KB
/
arshal_default.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
// Copyright 2020 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.
package json
import (
"bytes"
"encoding/base32"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math"
"reflect"
"slices"
"strconv"
"sync"
"github.com/go-json-experiment/json/internal"
"github.com/go-json-experiment/json/internal/jsonflags"
"github.com/go-json-experiment/json/internal/jsonopts"
"github.com/go-json-experiment/json/internal/jsonwire"
"github.com/go-json-experiment/json/jsontext"
)
// optimizeCommon specifies whether to use optimizations targeted for certain
// common patterns, rather than using the slower, but more general logic.
// All tests should pass regardless of whether this is true or not.
const optimizeCommon = true
var (
// Most natural Go type that correspond with each JSON type.
anyType = reflect.TypeFor[any]() // JSON value
boolType = reflect.TypeFor[bool]() // JSON bool
stringType = reflect.TypeFor[string]() // JSON string
float64Type = reflect.TypeFor[float64]() // JSON number
mapStringAnyType = reflect.TypeFor[map[string]any]() // JSON object
sliceAnyType = reflect.TypeFor[[]any]() // JSON array
bytesType = reflect.TypeFor[[]byte]()
emptyStructType = reflect.TypeFor[struct{}]()
)
const startDetectingCyclesAfter = 1000
type seenPointers = map[any]struct{}
type typedPointer struct {
typ reflect.Type
ptr any // always stores unsafe.Pointer, but avoids depending on unsafe
len int // remember slice length to avoid false positives
}
// visitPointer visits pointer p of type t, reporting an error if seen before.
// If successfully visited, then the caller must eventually call leave.
func visitPointer(m *seenPointers, v reflect.Value) error {
p := typedPointer{v.Type(), v.UnsafePointer(), sliceLen(v)}
if _, ok := (*m)[p]; ok {
return internal.ErrCycle
}
if *m == nil {
*m = make(seenPointers)
}
(*m)[p] = struct{}{}
return nil
}
func leavePointer(m *seenPointers, v reflect.Value) {
p := typedPointer{v.Type(), v.UnsafePointer(), sliceLen(v)}
delete(*m, p)
}
func sliceLen(v reflect.Value) int {
if v.Kind() == reflect.Slice {
return v.Len()
}
return 0
}
func len64[Bytes ~[]byte | ~string](in Bytes) int64 {
return int64(len(in))
}
func makeDefaultArshaler(t reflect.Type) *arshaler {
switch t.Kind() {
case reflect.Bool:
return makeBoolArshaler(t)
case reflect.String:
return makeStringArshaler(t)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return makeIntArshaler(t)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return makeUintArshaler(t)
case reflect.Float32, reflect.Float64:
return makeFloatArshaler(t)
case reflect.Map:
return makeMapArshaler(t)
case reflect.Struct:
return makeStructArshaler(t)
case reflect.Slice:
fncs := makeSliceArshaler(t)
if t.AssignableTo(bytesType) {
return makeBytesArshaler(t, fncs)
}
return fncs
case reflect.Array:
fncs := makeArrayArshaler(t)
if reflect.SliceOf(t.Elem()).AssignableTo(bytesType) {
return makeBytesArshaler(t, fncs)
}
return fncs
case reflect.Pointer:
return makePointerArshaler(t)
case reflect.Interface:
return makeInterfaceArshaler(t)
default:
return makeInvalidArshaler(t)
}
}
func makeBoolArshaler(t reflect.Type) *arshaler {
var fncs arshaler
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
return newInvalidFormatError(enc, t, mo.Format)
}
// Optimize for marshaling without preceding whitespace.
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) && !xe.Tokens.Last.NeedObjectName() {
xe.Buf = strconv.AppendBool(xe.Tokens.MayAppendDelim(xe.Buf, 't'), va.Bool())
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
if mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) {
if va.Bool() {
return enc.WriteToken(jsontext.String("true"))
} else {
return enc.WriteToken(jsontext.String("false"))
}
}
return enc.WriteToken(jsontext.Bool(va.Bool()))
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
return newInvalidFormatError(dec, t, uo.Format)
}
tok, err := dec.ReadToken()
if err != nil {
return err
}
k := tok.Kind()
switch k {
case 'n':
va.SetBool(false)
return nil
case 't', 'f':
if !uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) {
va.SetBool(tok.Bool())
return nil
}
case '"':
if uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) {
switch tok.String() {
case "true":
va.SetBool(true)
case "false":
va.SetBool(false)
default:
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax)
}
return nil
}
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
func makeStringArshaler(t reflect.Type) *arshaler {
var fncs arshaler
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
return newInvalidFormatError(enc, t, mo.Format)
}
// Optimize for marshaling without preceding whitespace or string escaping.
s := va.String()
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) && !xe.Tokens.Last.NeedObjectName() && !jsonwire.NeedEscape(s) {
b := xe.Buf
b = xe.Tokens.MayAppendDelim(b, '"')
b = append(b, '"')
b = append(b, s...)
b = append(b, '"')
xe.Buf = b
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
if mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) {
b, err := jsontext.AppendQuote(nil, s) // only fails for invalid UTF-8
q, _ := jsontext.AppendQuote(nil, b) // cannot fail since b is valid UTF-8
if err != nil && !xe.Flags.Get(jsonflags.AllowInvalidUTF8) {
return newMarshalErrorBefore(enc, t, err)
}
return enc.WriteValue(q)
}
return enc.WriteToken(jsontext.String(s))
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
return newInvalidFormatError(dec, t, uo.Format)
}
var flags jsonwire.ValueFlags
val, err := xd.ReadValue(&flags)
if err != nil {
return err
}
k := val.Kind()
switch k {
case 'n':
va.SetString("")
return nil
case '"':
val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
if uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) {
val, err = jsontext.AppendUnquote(nil, val)
if err != nil {
return newUnmarshalErrorAfter(dec, t, err)
}
}
if xd.StringCache == nil {
xd.StringCache = new(stringCache)
}
str := makeString(xd.StringCache, val)
va.SetString(str)
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
var (
encodeBase16 = func(dst, src []byte) { hex.Encode(dst, src) }
encodeBase32 = base32.StdEncoding.Encode
encodeBase32Hex = base32.HexEncoding.Encode
encodeBase64 = base64.StdEncoding.Encode
encodeBase64URL = base64.URLEncoding.Encode
encodedLenBase16 = hex.EncodedLen
encodedLenBase32 = base32.StdEncoding.EncodedLen
encodedLenBase32Hex = base32.HexEncoding.EncodedLen
encodedLenBase64 = base64.StdEncoding.EncodedLen
encodedLenBase64URL = base64.URLEncoding.EncodedLen
decodeBase16 = hex.Decode
decodeBase32 = base32.StdEncoding.Decode
decodeBase32Hex = base32.HexEncoding.Decode
decodeBase64 = base64.StdEncoding.Decode
decodeBase64URL = base64.URLEncoding.Decode
decodedLenBase16 = hex.DecodedLen
decodedLenBase32 = base32.StdEncoding.WithPadding(base32.NoPadding).DecodedLen
decodedLenBase32Hex = base32.HexEncoding.WithPadding(base32.NoPadding).DecodedLen
decodedLenBase64 = base64.StdEncoding.WithPadding(base64.NoPadding).DecodedLen
decodedLenBase64URL = base64.URLEncoding.WithPadding(base64.NoPadding).DecodedLen
)
func makeBytesArshaler(t reflect.Type, fncs *arshaler) *arshaler {
// NOTE: This handles both []byte and [N]byte.
marshalArray := fncs.marshal
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
encode, encodedLen := encodeBase64, encodedLenBase64
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
switch mo.Format {
case "base64":
encode, encodedLen = encodeBase64, encodedLenBase64
case "base64url":
encode, encodedLen = encodeBase64URL, encodedLenBase64URL
case "base32":
encode, encodedLen = encodeBase32, encodedLenBase32
case "base32hex":
encode, encodedLen = encodeBase32Hex, encodedLenBase32Hex
case "base16", "hex":
encode, encodedLen = encodeBase16, encodedLenBase16
case "array":
mo.Format = ""
return marshalArray(enc, va, mo)
default:
return newInvalidFormatError(enc, t, mo.Format)
}
} else if mo.Flags.Get(jsonflags.FormatByteArrayAsArray) && va.Kind() == reflect.Array {
return marshalArray(enc, va, mo)
}
if mo.Flags.Get(jsonflags.FormatNilSliceAsNull) && va.Kind() == reflect.Slice && va.IsNil() {
// TODO: Provide a "emitempty" format override?
return enc.WriteToken(jsontext.Null)
}
val := enc.UnusedBuffer()
b := va.Bytes()
n := len(`"`) + encodedLen(len(b)) + len(`"`)
if cap(val) < n {
val = make([]byte, n)
} else {
val = val[:n]
}
val[0] = '"'
encode(val[len(`"`):len(val)-len(`"`)], b)
val[len(val)-1] = '"'
return enc.WriteValue(val)
}
unmarshalArray := fncs.unmarshal
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
decode, decodedLen, encodedLen := decodeBase64, decodedLenBase64, encodedLenBase64
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
switch uo.Format {
case "base64":
decode, decodedLen, encodedLen = decodeBase64, decodedLenBase64, encodedLenBase64
case "base64url":
decode, decodedLen, encodedLen = decodeBase64URL, decodedLenBase64URL, encodedLenBase64URL
case "base32":
decode, decodedLen, encodedLen = decodeBase32, decodedLenBase32, encodedLenBase32
case "base32hex":
decode, decodedLen, encodedLen = decodeBase32Hex, decodedLenBase32Hex, encodedLenBase32Hex
case "base16", "hex":
decode, decodedLen, encodedLen = decodeBase16, decodedLenBase16, encodedLenBase16
case "array":
uo.Format = ""
return unmarshalArray(dec, va, uo)
default:
return newInvalidFormatError(dec, t, uo.Format)
}
} else if uo.Flags.Get(jsonflags.FormatByteArrayAsArray) && va.Kind() == reflect.Array {
return unmarshalArray(dec, va, uo)
}
var flags jsonwire.ValueFlags
val, err := xd.ReadValue(&flags)
if err != nil {
return err
}
k := val.Kind()
switch k {
case 'n':
va.SetZero()
return nil
case '"':
val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
// For base64 and base32, decodedLen computes the maximum output size
// when given the original input size. To compute the exact size,
// adjust the input size by excluding trailing padding characters.
// This is unnecessary for base16, but also harmless.
n := len(val)
for n > 0 && val[n-1] == '=' {
n--
}
n = decodedLen(n)
b := va.Bytes()
if va.Kind() == reflect.Array {
if n != len(b) {
err := fmt.Errorf("decoded length of %d mismatches array length of %d", n, len(b))
return newUnmarshalErrorAfter(dec, t, err)
}
} else {
if b == nil || cap(b) < n {
b = make([]byte, n)
} else {
b = b[:n]
}
}
n2, err := decode(b, val)
if err == nil && len(val) != encodedLen(n2) {
// TODO(https://go.dev/issue/53845): RFC 4648, section 3.3,
// specifies that non-alphabet characters must be rejected.
// Unfortunately, the "base32" and "base64" packages allow
// '\r' and '\n' characters by default.
i := bytes.IndexAny(val, "\r\n")
err = fmt.Errorf("illegal character %s at offset %d", jsonwire.QuoteRune(val[i:]), i)
}
if err != nil {
return newUnmarshalErrorAfter(dec, t, err)
}
if va.Kind() == reflect.Slice {
va.SetBytes(b)
}
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return fncs
}
func makeIntArshaler(t reflect.Type) *arshaler {
var fncs arshaler
bits := t.Bits()
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
return newInvalidFormatError(enc, t, mo.Format)
}
// Optimize for marshaling without preceding whitespace or string escaping.
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !mo.Flags.Get(jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() {
xe.Buf = strconv.AppendInt(xe.Tokens.MayAppendDelim(xe.Buf, '0'), va.Int(), 10)
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
k := stringOrNumberKind(mo.Flags.Get(jsonflags.StringifyNumbers))
return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) {
return strconv.AppendInt(b, va.Int(), 10), nil
})
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
return newInvalidFormatError(dec, t, uo.Format)
}
var flags jsonwire.ValueFlags
val, err := xd.ReadValue(&flags)
if err != nil {
return err
}
k := val.Kind()
switch k {
case 'n':
va.SetInt(0)
return nil
case '"':
if !uo.Flags.Get(jsonflags.StringifyNumbers) {
break
}
val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
fallthrough
case '0':
if uo.Flags.Get(jsonflags.StringifyNumbers) && k == '0' {
break
}
var negOffset int
neg := len(val) > 0 && val[0] == '-'
if neg {
negOffset = 1
}
n, ok := jsonwire.ParseUint(val[negOffset:])
maxInt := uint64(1) << (bits - 1)
overflow := (neg && n > maxInt) || (!neg && n > maxInt-1)
if !ok {
if n != math.MaxUint64 {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax)
}
overflow = true
}
if overflow {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange)
}
if neg {
va.SetInt(int64(-n))
} else {
va.SetInt(int64(+n))
}
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
func makeUintArshaler(t reflect.Type) *arshaler {
var fncs arshaler
bits := t.Bits()
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
return newInvalidFormatError(enc, t, mo.Format)
}
// Optimize for marshaling without preceding whitespace or string escaping.
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !mo.Flags.Get(jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() {
xe.Buf = strconv.AppendUint(xe.Tokens.MayAppendDelim(xe.Buf, '0'), va.Uint(), 10)
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
k := stringOrNumberKind(mo.Flags.Get(jsonflags.StringifyNumbers))
return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) {
return strconv.AppendUint(b, va.Uint(), 10), nil
})
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
return newInvalidFormatError(dec, t, uo.Format)
}
var flags jsonwire.ValueFlags
val, err := xd.ReadValue(&flags)
if err != nil {
return err
}
k := val.Kind()
switch k {
case 'n':
va.SetUint(0)
return nil
case '"':
if !uo.Flags.Get(jsonflags.StringifyNumbers) {
break
}
val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
fallthrough
case '0':
if uo.Flags.Get(jsonflags.StringifyNumbers) && k == '0' {
break
}
n, ok := jsonwire.ParseUint(val)
maxUint := uint64(1) << bits
overflow := n > maxUint-1
if !ok {
if n != math.MaxUint64 {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax)
}
overflow = true
}
if overflow {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange)
}
va.SetUint(n)
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
func makeFloatArshaler(t reflect.Type) *arshaler {
var fncs arshaler
bits := t.Bits()
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
var allowNonFinite bool
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
if mo.Format == "nonfinite" {
allowNonFinite = true
} else {
return newInvalidFormatError(enc, t, mo.Format)
}
}
fv := va.Float()
if math.IsNaN(fv) || math.IsInf(fv, 0) {
if !allowNonFinite {
err := fmt.Errorf("unsupported value: %v", fv)
return newMarshalErrorBefore(enc, t, err)
}
return enc.WriteToken(jsontext.Float(fv))
}
// Optimize for marshaling without preceding whitespace or string escaping.
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !mo.Flags.Get(jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() {
xe.Buf = jsonwire.AppendFloat(xe.Tokens.MayAppendDelim(xe.Buf, '0'), fv, bits)
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
k := stringOrNumberKind(mo.Flags.Get(jsonflags.StringifyNumbers))
return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) {
return jsonwire.AppendFloat(b, va.Float(), bits), nil
})
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
var allowNonFinite bool
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
if uo.Format == "nonfinite" {
allowNonFinite = true
} else {
return newInvalidFormatError(dec, t, uo.Format)
}
}
var flags jsonwire.ValueFlags
val, err := xd.ReadValue(&flags)
if err != nil {
return err
}
k := val.Kind()
switch k {
case 'n':
va.SetFloat(0)
return nil
case '"':
val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
if allowNonFinite {
switch string(val) {
case "NaN":
va.SetFloat(math.NaN())
return nil
case "Infinity":
va.SetFloat(math.Inf(+1))
return nil
case "-Infinity":
va.SetFloat(math.Inf(-1))
return nil
}
}
if !uo.Flags.Get(jsonflags.StringifyNumbers) {
break
}
if n, err := jsonwire.ConsumeNumber(val); n != len(val) || err != nil {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax)
}
fallthrough
case '0':
if uo.Flags.Get(jsonflags.StringifyNumbers) && k == '0' {
break
}
fv, ok := jsonwire.ParseFloat(val, bits)
if !ok && uo.Flags.Get(jsonflags.RejectFloatOverflow) {
return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange)
}
va.SetFloat(fv)
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
func makeMapArshaler(t reflect.Type) *arshaler {
// NOTE: The logic below disables namespaces for tracking duplicate names
// when handling map keys with a unique representation.
// NOTE: Values retrieved from a map are not addressable,
// so we shallow copy the values to make them addressable and
// store them back into the map afterwards.
var fncs arshaler
var (
once sync.Once
keyFncs *arshaler
valFncs *arshaler
)
init := func() {
keyFncs = lookupArshaler(t.Key())
valFncs = lookupArshaler(t.Elem())
}
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
// Check for cycles.
xe := export.Encoder(enc)
if xe.Tokens.Depth() > startDetectingCyclesAfter {
if err := visitPointer(&xe.SeenPointers, va.Value); err != nil {
return newMarshalErrorBefore(enc, t, err)
}
defer leavePointer(&xe.SeenPointers, va.Value)
}
emitNull := mo.Flags.Get(jsonflags.FormatNilMapAsNull)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
switch mo.Format {
case "emitnull":
emitNull = true
mo.Format = ""
case "emitempty":
emitNull = false
mo.Format = ""
default:
return newInvalidFormatError(enc, t, mo.Format)
}
}
// Handle empty maps.
n := va.Len()
if n == 0 {
if emitNull && va.IsNil() {
return enc.WriteToken(jsontext.Null)
}
// Optimize for marshaling an empty map without any preceding whitespace.
if optimizeCommon && !xe.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() {
xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '{'), "{}"...)
xe.Tokens.Last.Increment()
if xe.NeedFlush() {
return xe.Flush()
}
return nil
}
}
once.Do(init)
if err := enc.WriteToken(jsontext.ObjectStart); err != nil {
return err
}
if n > 0 {
nonDefaultKey := keyFncs.nonDefault
marshalKey := keyFncs.marshal
marshalVal := valFncs.marshal
if mo.Marshalers != nil {
var ok bool
marshalKey, ok = mo.Marshalers.(*Marshalers).lookup(marshalKey, t.Key())
marshalVal, _ = mo.Marshalers.(*Marshalers).lookup(marshalVal, t.Elem())
nonDefaultKey = nonDefaultKey || ok
}
k := newAddressableValue(t.Key())
v := newAddressableValue(t.Elem())
// A Go map guarantees that each entry has a unique key.
// As such, disable the expensive duplicate name check if we know
// that every Go key will serialize as a unique JSON string.
if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), xe.Flags.Get(jsonflags.AllowInvalidUTF8)) {
xe.Tokens.Last.DisableNamespace()
}
switch {
case !mo.Flags.Get(jsonflags.Deterministic) || n <= 1:
for iter := va.Value.MapRange(); iter.Next(); {
k.SetIterKey(iter)
flagsOriginal := mo.Flags
mo.Flags.Set(jsonflags.StringifyNumbers | 1) // stringify for numeric keys
err := marshalKey(enc, k, mo)
mo.Flags = flagsOriginal
if err != nil {
if serr, ok := err.(*jsontext.SyntacticError); ok && serr.Err == jsontext.ErrNonStringName {
err = newMarshalErrorBefore(enc, k.Type(), err)
}
return err
}
v.SetIterValue(iter)
if err := marshalVal(enc, v, mo); err != nil {
return err
}
}
case !nonDefaultKey && t.Key().Kind() == reflect.String:
names := getStrings(n)
for i, iter := 0, va.Value.MapRange(); i < n && iter.Next(); i++ {
k.SetIterKey(iter)
(*names)[i] = k.String()
}
names.Sort()
for _, name := range *names {
if err := enc.WriteToken(jsontext.String(name)); err != nil {
return err
}
// TODO(https://go.dev/issue/57061): Use v.SetMapIndexOf.
k.SetString(name)
v.Set(va.MapIndex(k.Value))
if err := marshalVal(enc, v, mo); err != nil {
return err
}
}
putStrings(names)
default:
type member struct {
name string // unquoted name
key addressableValue
val addressableValue
}
members := make([]member, n)
keys := reflect.MakeSlice(reflect.SliceOf(t.Key()), n, n)
vals := reflect.MakeSlice(reflect.SliceOf(t.Elem()), n, n)
for i, iter := 0, va.Value.MapRange(); i < n && iter.Next(); i++ {
// Marshal the member name.
k := addressableValue{keys.Index(i)} // indexed slice element is always addressable
k.SetIterKey(iter)
v := addressableValue{vals.Index(i)} // indexed slice element is always addressable
v.SetIterValue(iter)
flagsOriginal := mo.Flags
mo.Flags.Set(jsonflags.StringifyNumbers | 1) // stringify for numeric keys
err := marshalKey(enc, k, mo)
mo.Flags = flagsOriginal
if err != nil {
if serr, ok := err.(*jsontext.SyntacticError); ok && serr.Err == jsontext.ErrNonStringName {
err = newMarshalErrorBefore(enc, k.Type(), err)
}
return err
}
name := xe.UnwriteOnlyObjectMemberName()
members[i] = member{name, k, v}
}
// TODO: If AllowDuplicateNames is enabled, then sort according
// to reflect.Value as well if the names are equal.
// See internal/fmtsort.
slices.SortFunc(members, func(x, y member) int {
return jsonwire.CompareUTF16(x.name, y.name)
})
for _, member := range members {
if err := enc.WriteToken(jsontext.String(member.name)); err != nil {
return err
}
if err := marshalVal(enc, member.val, mo); err != nil {
return err
}
}
}
}
if err := enc.WriteToken(jsontext.ObjectEnd); err != nil {
return err
}
return nil
}
fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error {
xd := export.Decoder(dec)
if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() {
switch uo.Format {
case "emitnull", "emitempty":
uo.Format = "" // only relevant for marshaling
default:
return newInvalidFormatError(dec, t, uo.Format)
}
}
tok, err := dec.ReadToken()
if err != nil {
return err
}
k := tok.Kind()
switch k {
case 'n':
va.SetZero()
return nil
case '{':
once.Do(init)
if va.IsNil() {
va.Set(reflect.MakeMap(t))
}
nonDefaultKey := keyFncs.nonDefault
unmarshalKey := keyFncs.unmarshal
unmarshalVal := valFncs.unmarshal
if uo.Unmarshalers != nil {
var ok bool
unmarshalKey, ok = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshalKey, t.Key())
unmarshalVal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshalVal, t.Elem())
nonDefaultKey = nonDefaultKey || ok
}
k := newAddressableValue(t.Key())
v := newAddressableValue(t.Elem())
// Manually check for duplicate entries by virtue of whether the
// unmarshaled key already exists in the destination Go map.
// Consequently, syntactically different names (e.g., "0" and "-0")
// will be rejected as duplicates since they semantically refer
// to the same Go value. This is an unusual interaction
// between syntax and semantics, but is more correct.
if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), xd.Flags.Get(jsonflags.AllowInvalidUTF8)) {
xd.Tokens.Last.DisableNamespace()
}
// In the rare case where the map is not already empty,
// then we need to manually track which keys we already saw
// since existing presence alone is insufficient to indicate
// whether the input had a duplicate name.
var seen reflect.Value
if !xd.Flags.Get(jsonflags.AllowDuplicateNames) && va.Len() > 0 {
seen = reflect.MakeMap(reflect.MapOf(k.Type(), emptyStructType))
}
for dec.PeekKind() != '}' {
k.SetZero()
flagsOriginal := uo.Flags
uo.Flags.Set(jsonflags.StringifyNumbers | 1) // stringify for numeric keys
err := unmarshalKey(dec, k, uo)
uo.Flags = flagsOriginal
if err != nil {
return err
}
if k.Kind() == reflect.Interface && !k.IsNil() && !k.Elem().Type().Comparable() {
err := fmt.Errorf("invalid incomparable key type %v", k.Elem().Type())
return newUnmarshalErrorAfter(dec, t, err)
}
if v2 := va.MapIndex(k.Value); v2.IsValid() {
if !xd.Flags.Get(jsonflags.AllowDuplicateNames) && (!seen.IsValid() || seen.MapIndex(k.Value).IsValid()) {
// TODO: Unread the object name.
name := xd.PreviousTokenOrValue()
return newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(name))
}
v.Set(v2)
} else {
v.SetZero()
}
err = unmarshalVal(dec, v, uo)
va.SetMapIndex(k.Value, v.Value)
if seen.IsValid() {
seen.SetMapIndex(k.Value, reflect.Zero(emptyStructType))
}
if err != nil {
return err
}
}
if _, err := dec.ReadToken(); err != nil {
return err
}
return nil
}
return newUnmarshalErrorAfter(dec, t, nil)
}
return &fncs
}
// mapKeyWithUniqueRepresentation reports whether all possible values of k
// marshal to a different JSON value, and whether all possible JSON values
// that can unmarshal into k unmarshal to different Go values.
// In other words, the representation must be a bijective.
func mapKeyWithUniqueRepresentation(k reflect.Kind, allowInvalidUTF8 bool) bool {
switch k {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return true
case reflect.String:
// For strings, we have to be careful since names with invalid UTF-8
// maybe unescape to the same Go string value.
return !allowInvalidUTF8
default:
// Floating-point kinds are not listed above since NaNs
// can appear multiple times and all serialize as "NaN".
return false
}
}
var errNilField = errors.New("cannot set embedded pointer to unexported struct type")
func makeStructArshaler(t reflect.Type) *arshaler {
// NOTE: The logic below disables namespaces for tracking duplicate names
// and does the tracking locally with an efficient bit-set based on which
// Go struct fields were seen.
var fncs arshaler
var (
once sync.Once
fields structFields
errInit *SemanticError
)
init := func() {
fields, errInit = makeStructFields(t)
}
fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error {
xe := export.Encoder(enc)
if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() {
return newInvalidFormatError(enc, t, mo.Format)
}
once.Do(init)
if errInit != nil && !mo.Flags.Get(jsonflags.IgnoreStructErrors) {
return newMarshalErrorBefore(enc, errInit.GoType, errInit.Err)
}
if err := enc.WriteToken(jsontext.ObjectStart); err != nil {
return err
}
var seenIdxs uintSet
prevIdx := -1
xe.Tokens.Last.DisableNamespace() // we manually ensure unique names below
for i := range fields.flattened {
f := &fields.flattened[i]
v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable
if len(f.index) > 1 {
v = v.fieldByIndex(f.index[1:], false)
if !v.IsValid() {
continue // implies a nil inlined field
}
}
// OmitZero skips the field if the Go value is zero,
// which we can determine up front without calling the marshaler.
if (f.omitzero || mo.Flags.Get(jsonflags.OmitZeroStructFields)) &&
((f.isZero == nil && v.IsZero()) || (f.isZero != nil && f.isZero(v))) {
continue
}
// Check for the legacy definition of omitempty.
if f.omitempty && mo.Flags.Get(jsonflags.OmitEmptyWithLegacyDefinition) && isLegacyEmpty(v) {
continue
}
marshal := f.fncs.marshal
nonDefault := f.fncs.nonDefault
if mo.Marshalers != nil {
var ok bool
marshal, ok = mo.Marshalers.(*Marshalers).lookup(marshal, f.typ)
nonDefault = nonDefault || ok
}
// OmitEmpty skips the field if the marshaled JSON value is empty,
// which we can know up front if there are no custom marshalers,
// otherwise we must marshal the value and unwrite it if empty.
if f.omitempty && !mo.Flags.Get(jsonflags.OmitEmptyWithLegacyDefinition) &&