forked from go-json-experiment/json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arshal_test.go
8604 lines (8528 loc) · 299 KB
/
arshal_test.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"
"encoding/base32"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"net"
"net/netip"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/go-json-experiment/json/internal/jsonflags"
"github.com/go-json-experiment/json/internal/jsonopts"
"github.com/go-json-experiment/json/internal/jsontest"
"github.com/go-json-experiment/json/jsontext"
)
type (
jsonObject = map[string]any
jsonArray = []any
namedAny any
namedBool bool
namedString string
namedBytes []byte
namedInt64 int64
namedUint64 uint64
namedFloat64 float64
namedByte byte
recursiveMap map[string]recursiveMap
recursiveSlice []recursiveSlice
recursivePointer struct{ P *recursivePointer }
structEmpty struct{}
structConflicting struct {
A string `json:"conflict"`
B string `json:"conflict"`
}
structNoneExported struct {
unexported string
}
structUnexportedIgnored struct {
ignored string `json:"-"`
}
structMalformedTag struct {
Malformed string `json:"\""`
}
structUnexportedTag struct {
unexported string `json:"name"`
}
structUnexportedEmbedded struct {
namedString
}
structIgnoredUnexportedEmbedded struct {
namedString `json:"-"`
}
structWeirdNames struct {
Empty string `json:"''"`
Comma string `json:"','"`
Quote string `json:"'\"'"`
}
structNoCase struct {
Aaa string `json:",strictcase"`
AA_A string
AaA string `json:",nocase"`
AAa string `json:",nocase"`
AAA string
}
structScalars struct {
unexported bool
Ignored bool `json:"-"`
Bool bool
String string
Bytes []byte
Int int64
Uint uint64
Float float64
}
structSlices struct {
unexported bool
Ignored bool `json:"-"`
SliceBool []bool
SliceString []string
SliceBytes [][]byte
SliceInt []int64
SliceUint []uint64
SliceFloat []float64
}
structMaps struct {
unexported bool
Ignored bool `json:"-"`
MapBool map[string]bool
MapString map[string]string
MapBytes map[string][]byte
MapInt map[string]int64
MapUint map[string]uint64
MapFloat map[string]float64
}
structAll struct {
Bool bool
String string
Bytes []byte
Int int64
Uint uint64
Float float64
Map map[string]string
StructScalars structScalars
StructMaps structMaps
StructSlices structSlices
Slice []string
Array [1]string
Pointer *structAll
Interface any
}
structStringifiedAll struct {
Bool bool `json:",string"`
String string `json:",string"`
Bytes []byte `json:",string"`
Int int64 `json:",string"`
Uint uint64 `json:",string"`
Float float64 `json:",string"`
Map map[string]string `json:",string"`
StructScalars structScalars `json:",string"`
StructMaps structMaps `json:",string"`
StructSlices structSlices `json:",string"`
Slice []string `json:",string"`
Array [1]string `json:",string"`
Pointer *structStringifiedAll `json:",string"`
Interface any `json:",string"`
}
structOmitZeroAll struct {
Bool bool `json:",omitzero"`
String string `json:",omitzero"`
Bytes []byte `json:",omitzero"`
Int int64 `json:",omitzero"`
Uint uint64 `json:",omitzero"`
Float float64 `json:",omitzero"`
Map map[string]string `json:",omitzero"`
StructScalars structScalars `json:",omitzero"`
StructMaps structMaps `json:",omitzero"`
StructSlices structSlices `json:",omitzero"`
Slice []string `json:",omitzero"`
Array [1]string `json:",omitzero"`
Pointer *structOmitZeroAll `json:",omitzero"`
Interface any `json:",omitzero"`
}
structOmitZeroMethodAll struct {
ValueAlwaysZero valueAlwaysZero `json:",omitzero"`
ValueNeverZero valueNeverZero `json:",omitzero"`
PointerAlwaysZero pointerAlwaysZero `json:",omitzero"`
PointerNeverZero pointerNeverZero `json:",omitzero"`
PointerValueAlwaysZero *valueAlwaysZero `json:",omitzero"`
PointerValueNeverZero *valueNeverZero `json:",omitzero"`
PointerPointerAlwaysZero *pointerAlwaysZero `json:",omitzero"`
PointerPointerNeverZero *pointerNeverZero `json:",omitzero"`
PointerPointerValueAlwaysZero **valueAlwaysZero `json:",omitzero"`
PointerPointerValueNeverZero **valueNeverZero `json:",omitzero"`
PointerPointerPointerAlwaysZero **pointerAlwaysZero `json:",omitzero"`
PointerPointerPointerNeverZero **pointerNeverZero `json:",omitzero"`
}
structOmitZeroMethodInterfaceAll struct {
ValueAlwaysZero isZeroer `json:",omitzero"`
ValueNeverZero isZeroer `json:",omitzero"`
PointerValueAlwaysZero isZeroer `json:",omitzero"`
PointerValueNeverZero isZeroer `json:",omitzero"`
PointerPointerAlwaysZero isZeroer `json:",omitzero"`
PointerPointerNeverZero isZeroer `json:",omitzero"`
}
structOmitEmptyAll struct {
Bool bool `json:",omitempty"`
PointerBool *bool `json:",omitempty"`
String string `json:",omitempty"`
StringEmpty stringMarshalEmpty `json:",omitempty"`
StringNonEmpty stringMarshalNonEmpty `json:",omitempty"`
PointerString *string `json:",omitempty"`
PointerStringEmpty *stringMarshalEmpty `json:",omitempty"`
PointerStringNonEmpty *stringMarshalNonEmpty `json:",omitempty"`
Bytes []byte `json:",omitempty"`
BytesEmpty bytesMarshalEmpty `json:",omitempty"`
BytesNonEmpty bytesMarshalNonEmpty `json:",omitempty"`
PointerBytes *[]byte `json:",omitempty"`
PointerBytesEmpty *bytesMarshalEmpty `json:",omitempty"`
PointerBytesNonEmpty *bytesMarshalNonEmpty `json:",omitempty"`
Float float64 `json:",omitempty"`
PointerFloat *float64 `json:",omitempty"`
Map map[string]string `json:",omitempty"`
MapEmpty mapMarshalEmpty `json:",omitempty"`
MapNonEmpty mapMarshalNonEmpty `json:",omitempty"`
PointerMap *map[string]string `json:",omitempty"`
PointerMapEmpty *mapMarshalEmpty `json:",omitempty"`
PointerMapNonEmpty *mapMarshalNonEmpty `json:",omitempty"`
Slice []string `json:",omitempty"`
SliceEmpty sliceMarshalEmpty `json:",omitempty"`
SliceNonEmpty sliceMarshalNonEmpty `json:",omitempty"`
PointerSlice *[]string `json:",omitempty"`
PointerSliceEmpty *sliceMarshalEmpty `json:",omitempty"`
PointerSliceNonEmpty *sliceMarshalNonEmpty `json:",omitempty"`
Pointer *structOmitZeroEmptyAll `json:",omitempty"`
Interface any `json:",omitempty"`
}
structOmitZeroEmptyAll struct {
Bool bool `json:",omitzero,omitempty"`
String string `json:",omitzero,omitempty"`
Bytes []byte `json:",omitzero,omitempty"`
Int int64 `json:",omitzero,omitempty"`
Uint uint64 `json:",omitzero,omitempty"`
Float float64 `json:",omitzero,omitempty"`
Map map[string]string `json:",omitzero,omitempty"`
Slice []string `json:",omitzero,omitempty"`
Array [1]string `json:",omitzero,omitempty"`
Pointer *structOmitZeroEmptyAll `json:",omitzero,omitempty"`
Interface any `json:",omitzero,omitempty"`
}
structFormatBytes struct {
Base16 []byte `json:",format:base16"`
Base32 []byte `json:",format:base32"`
Base32Hex []byte `json:",format:base32hex"`
Base64 []byte `json:",format:base64"`
Base64URL []byte `json:",format:base64url"`
Array []byte `json:",format:array"`
}
structFormatArrayBytes struct {
Base16 [4]byte `json:",format:base16"`
Base32 [4]byte `json:",format:base32"`
Base32Hex [4]byte `json:",format:base32hex"`
Base64 [4]byte `json:",format:base64"`
Base64URL [4]byte `json:",format:base64url"`
Array [4]byte `json:",format:array"`
Default [4]byte
}
structFormatFloats struct {
NonFinite float64 `json:",format:nonfinite"`
PointerNonFinite *float64 `json:",format:nonfinite"`
}
structFormatMaps struct {
EmitNull map[string]string `json:",format:emitnull"`
PointerEmitNull *map[string]string `json:",format:emitnull"`
EmitEmpty map[string]string `json:",format:emitempty"`
PointerEmitEmpty *map[string]string `json:",format:emitempty"`
EmitDefault map[string]string
PointerEmitDefault *map[string]string
}
structFormatSlices struct {
EmitNull []string `json:",format:emitnull"`
PointerEmitNull *[]string `json:",format:emitnull"`
EmitEmpty []string `json:",format:emitempty"`
PointerEmitEmpty *[]string `json:",format:emitempty"`
EmitDefault []string
PointerEmitDefault *[]string
}
structFormatInvalid struct {
Bool bool `json:",omitzero,format:invalid"`
String string `json:",omitzero,format:invalid"`
Bytes []byte `json:",omitzero,format:invalid"`
Int int64 `json:",omitzero,format:invalid"`
Uint uint64 `json:",omitzero,format:invalid"`
Float float64 `json:",omitzero,format:invalid"`
Map map[string]string `json:",omitzero,format:invalid"`
Struct structAll `json:",omitzero,format:invalid"`
Slice []string `json:",omitzero,format:invalid"`
Array [1]string `json:",omitzero,format:invalid"`
Interface any `json:",omitzero,format:invalid"`
}
structDurationFormat struct {
D1 time.Duration
D2 time.Duration `json:",format:units"`
D3 time.Duration `json:",format:sec"`
D4 time.Duration `json:",string,format:sec"`
D5 time.Duration `json:",format:milli"`
D6 time.Duration `json:",string,format:milli"`
D7 time.Duration `json:",format:micro"`
D8 time.Duration `json:",string,format:micro"`
D9 time.Duration `json:",format:nano"`
D10 time.Duration `json:",string,format:nano"`
D11 time.Duration `json:",format:base60"`
}
structTimeFormat struct {
T1 time.Time
T2 time.Time `json:",format:ANSIC"`
T3 time.Time `json:",format:UnixDate"`
T4 time.Time `json:",format:RubyDate"`
T5 time.Time `json:",format:RFC822"`
T6 time.Time `json:",format:RFC822Z"`
T7 time.Time `json:",format:RFC850"`
T8 time.Time `json:",format:RFC1123"`
T9 time.Time `json:",format:RFC1123Z"`
T10 time.Time `json:",format:RFC3339"`
T11 time.Time `json:",format:RFC3339Nano"`
T12 time.Time `json:",format:Kitchen"`
T13 time.Time `json:",format:Stamp"`
T14 time.Time `json:",format:StampMilli"`
T15 time.Time `json:",format:StampMicro"`
T16 time.Time `json:",format:StampNano"`
T17 time.Time `json:",format:DateTime"`
T18 time.Time `json:",format:DateOnly"`
T19 time.Time `json:",format:TimeOnly"`
T20 time.Time `json:",format:'2006-01-02'"`
T21 time.Time `json:",format:'\"weird\"2006'"`
T22 time.Time `json:",format:unix"`
T23 time.Time `json:",string,format:unix"`
T24 time.Time `json:",format:unixmilli"`
T25 time.Time `json:",string,format:unixmilli"`
T26 time.Time `json:",format:unixmicro"`
T27 time.Time `json:",string,format:unixmicro"`
T28 time.Time `json:",format:unixnano"`
T29 time.Time `json:",string,format:unixnano"`
}
structInlined struct {
X structInlinedL1 `json:",inline"`
*StructEmbed2 // implicit inline
}
structInlinedL1 struct {
X *structInlinedL2 `json:",inline"`
StructEmbed1 `json:",inline"`
}
structInlinedL2 struct{ A, B, C string }
StructEmbed1 struct{ C, D, E string }
StructEmbed2 struct{ E, F, G string }
structUnknownTextValue struct {
A int `json:",omitzero"`
X jsontext.Value `json:",unknown"`
B int `json:",omitzero"`
}
structInlineTextValue struct {
A int `json:",omitzero"`
X jsontext.Value `json:",inline"`
B int `json:",omitzero"`
}
structInlinePointerTextValue struct {
A int `json:",omitzero"`
X *jsontext.Value `json:",inline"`
B int `json:",omitzero"`
}
structInlinePointerInlineTextValue struct {
X *struct {
A int
X jsontext.Value `json:",inline"`
} `json:",inline"`
}
structInlineInlinePointerTextValue struct {
X struct {
X *jsontext.Value `json:",inline"`
} `json:",inline"`
}
structInlineMapStringAny struct {
A int `json:",omitzero"`
X jsonObject `json:",inline"`
B int `json:",omitzero"`
}
structInlinePointerMapStringAny struct {
A int `json:",omitzero"`
X *jsonObject `json:",inline"`
B int `json:",omitzero"`
}
structInlinePointerInlineMapStringAny struct {
X *struct {
A int
X jsonObject `json:",inline"`
} `json:",inline"`
}
structInlineInlinePointerMapStringAny struct {
X struct {
X *jsonObject `json:",inline"`
} `json:",inline"`
}
structInlineMapStringInt struct {
X map[string]int `json:",inline"`
}
structNoCaseInlineTextValue struct {
AAA string `json:",omitempty,strictcase"`
AA_b string `json:",omitempty"`
AaA string `json:",omitempty,nocase"`
AAa string `json:",omitempty,nocase"`
Aaa string `json:",omitempty"`
X jsontext.Value `json:",inline"`
}
structNoCaseInlineMapStringAny struct {
AAA string `json:",omitempty"`
AaA string `json:",omitempty,nocase"`
AAa string `json:",omitempty,nocase"`
Aaa string `json:",omitempty"`
X jsonObject `json:",inline"`
}
allMethods struct {
method string // the method that was called
value []byte // the raw value to provide or store
}
allMethodsExceptJSONv2 struct {
allMethods
MarshalJSONV2 struct{} // cancel out MarshalJSONV2 method with collision
UnmarshalJSONV2 struct{} // cancel out UnmarshalJSONV2 method with collision
}
allMethodsExceptJSONv1 struct {
allMethods
MarshalJSON struct{} // cancel out MarshalJSON method with collision
UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
}
allMethodsExceptText struct {
allMethods
MarshalText struct{} // cancel out MarshalText method with collision
UnmarshalText struct{} // cancel out UnmarshalText method with collision
}
onlyMethodJSONv2 struct {
allMethods
MarshalJSON struct{} // cancel out MarshalJSON method with collision
UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
MarshalText struct{} // cancel out MarshalText method with collision
UnmarshalText struct{} // cancel out UnmarshalText method with collision
}
onlyMethodJSONv1 struct {
allMethods
MarshalJSONV2 struct{} // cancel out MarshalJSONV2 method with collision
UnmarshalJSONV2 struct{} // cancel out UnmarshalJSONV2 method with collision
MarshalText struct{} // cancel out MarshalText method with collision
UnmarshalText struct{} // cancel out UnmarshalText method with collision
}
onlyMethodText struct {
allMethods
MarshalJSONV2 struct{} // cancel out MarshalJSONV2 method with collision
UnmarshalJSONV2 struct{} // cancel out UnmarshalJSONV2 method with collision
MarshalJSON struct{} // cancel out MarshalJSON method with collision
UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
}
structMethodJSONv2 struct{ value string }
structMethodJSONv1 struct{ value string }
structMethodText struct{ value string }
marshalJSONv2Func func(*jsontext.Encoder, Options) error
marshalJSONv1Func func() ([]byte, error)
appendTextFunc func([]byte) ([]byte, error)
marshalTextFunc func() ([]byte, error)
unmarshalJSONv2Func func(*jsontext.Decoder, Options) error
unmarshalJSONv1Func func([]byte) error
unmarshalTextFunc func([]byte) error
nocaseString string
stringMarshalEmpty string
stringMarshalNonEmpty string
bytesMarshalEmpty []byte
bytesMarshalNonEmpty []byte
mapMarshalEmpty map[string]string
mapMarshalNonEmpty map[string]string
sliceMarshalEmpty []string
sliceMarshalNonEmpty []string
valueAlwaysZero string
valueNeverZero string
pointerAlwaysZero string
pointerNeverZero string
valueStringer struct{}
pointerStringer struct{}
cyclicA struct {
B1 cyclicB `json:",inline"`
B2 cyclicB `json:",inline"`
}
cyclicB struct {
F int
A *cyclicA `json:",inline"`
}
)
func (p *allMethods) MarshalJSONV2(enc *jsontext.Encoder, opts Options) error {
if got, want := "MarshalJSONV2", p.method; got != want {
return fmt.Errorf("called wrong method: got %v, want %v", got, want)
}
return enc.WriteValue(p.value)
}
func (p *allMethods) MarshalJSON() ([]byte, error) {
if got, want := "MarshalJSON", p.method; got != want {
return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
}
return p.value, nil
}
func (p *allMethods) MarshalText() ([]byte, error) {
if got, want := "MarshalText", p.method; got != want {
return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
}
return p.value, nil
}
func (p *allMethods) UnmarshalJSONV2(dec *jsontext.Decoder, opts Options) error {
p.method = "UnmarshalJSONV2"
val, err := dec.ReadValue()
p.value = val
return err
}
func (p *allMethods) UnmarshalJSON(val []byte) error {
p.method = "UnmarshalJSON"
p.value = val
return nil
}
func (p *allMethods) UnmarshalText(val []byte) error {
p.method = "UnmarshalText"
p.value = val
return nil
}
func (s structMethodJSONv2) MarshalJSONV2(enc *jsontext.Encoder, opts Options) error {
return enc.WriteToken(jsontext.String(s.value))
}
func (s *structMethodJSONv2) UnmarshalJSONV2(dec *jsontext.Decoder, opts Options) error {
tok, err := dec.ReadToken()
if err != nil {
return err
}
if k := tok.Kind(); k != '"' {
return &SemanticError{action: "unmarshal", JSONKind: k, GoType: structMethodJSONv2Type}
}
s.value = tok.String()
return nil
}
func (s structMethodJSONv1) MarshalJSON() ([]byte, error) {
return jsontext.AppendQuote(nil, s.value)
}
func (s *structMethodJSONv1) UnmarshalJSON(b []byte) error {
if k := jsontext.Value(b).Kind(); k != '"' {
return &SemanticError{action: "unmarshal", JSONKind: k, GoType: structMethodJSONv1Type}
}
b, _ = jsontext.AppendUnquote(nil, b)
s.value = string(b)
return nil
}
func (s structMethodText) MarshalText() ([]byte, error) {
return []byte(s.value), nil
}
func (s *structMethodText) UnmarshalText(b []byte) error {
s.value = string(b)
return nil
}
func (f marshalJSONv2Func) MarshalJSONV2(enc *jsontext.Encoder, opts Options) error {
return f(enc, opts)
}
func (f marshalJSONv1Func) MarshalJSON() ([]byte, error) {
return f()
}
func (f appendTextFunc) AppendText(b []byte) ([]byte, error) {
return f(b)
}
func (f marshalTextFunc) MarshalText() ([]byte, error) {
return f()
}
func (f unmarshalJSONv2Func) UnmarshalJSONV2(dec *jsontext.Decoder, opts Options) error {
return f(dec, opts)
}
func (f unmarshalJSONv1Func) UnmarshalJSON(b []byte) error {
return f(b)
}
func (f unmarshalTextFunc) UnmarshalText(b []byte) error {
return f(b)
}
func (k nocaseString) MarshalText() ([]byte, error) {
return []byte(strings.ToLower(string(k))), nil
}
func (k *nocaseString) UnmarshalText(b []byte) error {
*k = nocaseString(strings.ToLower(string(b)))
return nil
}
func (stringMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`""`), nil }
func (stringMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`"value"`), nil }
func (bytesMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
func (bytesMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
func (mapMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`{}`), nil }
func (mapMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`{"key":"value"}`), nil }
func (sliceMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
func (sliceMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
func (valueAlwaysZero) IsZero() bool { return true }
func (valueNeverZero) IsZero() bool { return false }
func (*pointerAlwaysZero) IsZero() bool { return true }
func (*pointerNeverZero) IsZero() bool { return false }
func (valueStringer) String() string { return "" }
func (*pointerStringer) String() string { return "" }
var (
namedBoolType = reflect.TypeFor[namedBool]()
intType = reflect.TypeFor[int]()
int8Type = reflect.TypeFor[int8]()
int16Type = reflect.TypeFor[int16]()
int32Type = reflect.TypeFor[int32]()
int64Type = reflect.TypeFor[int64]()
uintType = reflect.TypeFor[uint]()
uint8Type = reflect.TypeFor[uint8]()
uint16Type = reflect.TypeFor[uint16]()
uint32Type = reflect.TypeFor[uint32]()
uint64Type = reflect.TypeFor[uint64]()
float32Type = reflect.TypeFor[float32]()
sliceStringType = reflect.TypeFor[[]string]()
array1StringType = reflect.TypeFor[[1]string]()
array0ByteType = reflect.TypeFor[[0]byte]()
array1ByteType = reflect.TypeFor[[1]byte]()
array2ByteType = reflect.TypeFor[[2]byte]()
array3ByteType = reflect.TypeFor[[3]byte]()
array4ByteType = reflect.TypeFor[[4]byte]()
mapStringStringType = reflect.TypeFor[map[string]string]()
structAllType = reflect.TypeFor[structAll]()
structConflictingType = reflect.TypeFor[structConflicting]()
structNoneExportedType = reflect.TypeFor[structNoneExported]()
structMalformedTagType = reflect.TypeFor[structMalformedTag]()
structUnexportedTagType = reflect.TypeFor[structUnexportedTag]()
structUnexportedEmbeddedType = reflect.TypeFor[structUnexportedEmbedded]()
structUnknownTextValueType = reflect.TypeFor[structUnknownTextValue]()
allMethodsType = reflect.TypeFor[allMethods]()
allMethodsExceptJSONv2Type = reflect.TypeFor[allMethodsExceptJSONv2]()
allMethodsExceptJSONv1Type = reflect.TypeFor[allMethodsExceptJSONv1]()
allMethodsExceptTextType = reflect.TypeFor[allMethodsExceptText]()
onlyMethodJSONv2Type = reflect.TypeFor[onlyMethodJSONv2]()
onlyMethodJSONv1Type = reflect.TypeFor[onlyMethodJSONv1]()
onlyMethodTextType = reflect.TypeFor[onlyMethodText]()
structMethodJSONv2Type = reflect.TypeFor[structMethodJSONv2]()
structMethodJSONv1Type = reflect.TypeFor[structMethodJSONv1]()
structMethodTextType = reflect.TypeFor[structMethodText]()
marshalJSONv2FuncType = reflect.TypeFor[marshalJSONv2Func]()
marshalJSONv1FuncType = reflect.TypeFor[marshalJSONv1Func]()
appendTextFuncType = reflect.TypeFor[appendTextFunc]()
marshalTextFuncType = reflect.TypeFor[marshalTextFunc]()
unmarshalJSONv2FuncType = reflect.TypeFor[unmarshalJSONv2Func]()
unmarshalJSONv1FuncType = reflect.TypeFor[unmarshalJSONv1Func]()
unmarshalTextFuncType = reflect.TypeFor[unmarshalTextFunc]()
nocaseStringType = reflect.TypeFor[nocaseString]()
ioReaderType = reflect.TypeFor[io.Reader]()
fmtStringerType = reflect.TypeFor[fmt.Stringer]()
chanStringType = reflect.TypeFor[chan string]()
)
func addr[T any](v T) *T {
return &v
}
func mustParseTime(layout, value string) time.Time {
t, err := time.Parse(layout, value)
if err != nil {
panic(err)
}
return t
}
var invalidFormatOption = &jsonopts.Struct{
ArshalValues: jsonopts.ArshalValues{FormatDepth: 1000, Format: "invalid"},
}
func TestMarshal(t *testing.T) {
tests := []struct {
name jsontest.CaseName
opts []Options
in any
want string
wantErr error
canonicalize bool // canonicalize the output before comparing?
useWriter bool // call MarshalWrite instead of Marshal
}{{
name: jsontest.Name("Nil"),
in: nil,
want: `null`,
}, {
name: jsontest.Name("Bools"),
in: []bool{false, true},
want: `[false,true]`,
}, {
name: jsontest.Name("Bools/Named"),
in: []namedBool{false, true},
want: `[false,true]`,
}, {
name: jsontest.Name("Bools/NotStringified"),
opts: []Options{StringifyNumbers(true)},
in: []bool{false, true},
want: `[false,true]`,
}, {
name: jsontest.Name("Bools/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: true,
want: `true`,
}, {
name: jsontest.Name("Strings"),
in: []string{"", "hello", "世界"},
want: `["","hello","世界"]`,
}, {
name: jsontest.Name("Strings/Named"),
in: []namedString{"", "hello", "世界"},
want: `["","hello","世界"]`,
}, {
name: jsontest.Name("Strings/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: "string",
want: `"string"`,
}, {
name: jsontest.Name("Bytes"),
in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
want: `["","","AQ==","AQI=","AQID"]`,
}, {
name: jsontest.Name("Bytes/FormatNilSliceAsNull"),
opts: []Options{FormatNilSliceAsNull(true)},
in: [][]byte{nil, {}},
want: `[null,""]`,
}, {
name: jsontest.Name("Bytes/Large"),
in: []byte("the quick brown fox jumped over the lazy dog and ate the homework that I spent so much time on."),
want: `"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgYW5kIGF0ZSB0aGUgaG9tZXdvcmsgdGhhdCBJIHNwZW50IHNvIG11Y2ggdGltZSBvbi4="`,
}, {
name: jsontest.Name("Bytes/Named"),
in: []namedBytes{nil, {}, {1}, {1, 2}, {1, 2, 3}},
want: `["","","AQ==","AQI=","AQID"]`,
}, {
name: jsontest.Name("Bytes/NotStringified"),
opts: []Options{StringifyNumbers(true)},
in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
want: `["","","AQ==","AQI=","AQID"]`,
}, {
// NOTE: []namedByte is not assignable to []byte,
// so the following should be treated as a slice of uints.
name: jsontest.Name("Bytes/Invariant"),
in: [][]namedByte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
want: `[[],[],[1],[1,2],[1,2,3]]`,
}, {
// NOTE: This differs in behavior from v1,
// but keeps the representation of slices and arrays more consistent.
name: jsontest.Name("Bytes/ByteArray"),
in: [5]byte{'h', 'e', 'l', 'l', 'o'},
want: `"aGVsbG8="`,
}, {
// NOTE: []namedByte is not assignable to []byte,
// so the following should be treated as an array of uints.
name: jsontest.Name("Bytes/NamedByteArray"),
in: [5]namedByte{'h', 'e', 'l', 'l', 'o'},
want: `[104,101,108,108,111]`,
}, {
name: jsontest.Name("Bytes/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: []byte("hello"),
want: `"aGVsbG8="`,
}, {
name: jsontest.Name("Ints"),
in: []any{
int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
},
want: `[0,-128,-32768,-2147483648,-9223372036854775808,-6464]`,
}, {
name: jsontest.Name("Ints/Stringified"),
opts: []Options{StringifyNumbers(true)},
in: []any{
int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
},
want: `["0","-128","-32768","-2147483648","-9223372036854775808","-6464"]`,
}, {
name: jsontest.Name("Ints/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: int(0),
want: `0`,
}, {
name: jsontest.Name("Uints"),
in: []any{
uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464), uintptr(1234),
},
want: `[0,255,65535,4294967295,18446744073709551615,6464,1234]`,
}, {
name: jsontest.Name("Uints/Stringified"),
opts: []Options{StringifyNumbers(true)},
in: []any{
uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464),
},
want: `["0","255","65535","4294967295","18446744073709551615","6464"]`,
}, {
name: jsontest.Name("Uints/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: uint(0),
want: `0`,
}, {
name: jsontest.Name("Floats"),
in: []any{
float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
},
want: `[3.4028235e+38,1.7976931348623157e+308,64.64]`,
}, {
name: jsontest.Name("Floats/Stringified"),
opts: []Options{StringifyNumbers(true)},
in: []any{
float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
},
want: `["3.4028235e+38","1.7976931348623157e+308","64.64"]`,
}, {
name: jsontest.Name("Floats/Invalid/NaN"),
opts: []Options{StringifyNumbers(true)},
in: math.NaN(),
wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.NaN())},
}, {
name: jsontest.Name("Floats/Invalid/PositiveInfinity"),
in: math.Inf(+1),
wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.Inf(+1))},
}, {
name: jsontest.Name("Floats/Invalid/NegativeInfinity"),
in: math.Inf(-1),
wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.Inf(-1))},
}, {
name: jsontest.Name("Floats/IgnoreInvalidFormat"),
opts: []Options{invalidFormatOption},
in: float64(0),
want: `0`,
}, {
name: jsontest.Name("Maps/InvalidKey/Bool"),
in: map[bool]string{false: "value"},
want: `{`,
wantErr: export.NewMissingNameError(len64(`{`)),
}, {
name: jsontest.Name("Maps/InvalidKey/NamedBool"),
in: map[namedBool]string{false: "value"},
want: `{`,
wantErr: export.NewMissingNameError(len64(`{`)),
}, {
name: jsontest.Name("Maps/InvalidKey/Array"),
in: map[[1]string]string{{"key"}: "value"},
want: `{`,
wantErr: export.NewMissingNameError(len64(`{`)),
}, {
name: jsontest.Name("Maps/InvalidKey/Channel"),
in: map[chan string]string{make(chan string): "value"},
want: `{`,
wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
}, {
name: jsontest.Name("Maps/ValidKey/Int"),
in: map[int64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
canonicalize: true,
want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
}, {
name: jsontest.Name("Maps/ValidKey/PointerInt"),
in: map[*int64]string{addr(int64(math.MinInt64)): "MinInt64", addr(int64(0)): "Zero", addr(int64(math.MaxInt64)): "MaxInt64"},
canonicalize: true,
want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
}, {
name: jsontest.Name("Maps/DuplicateName/PointerInt"),
in: map[*int64]string{addr(int64(0)): "0", addr(int64(0)): "0"},
canonicalize: true,
want: `{"0":"0"`,
wantErr: export.NewDuplicateNameError([]byte(`"0"`), len64(`{"0":"0",`)),
}, {
name: jsontest.Name("Maps/ValidKey/NamedInt"),
in: map[namedInt64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
canonicalize: true,
want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
}, {
name: jsontest.Name("Maps/ValidKey/Uint"),
in: map[uint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
canonicalize: true,
want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
}, {
name: jsontest.Name("Maps/ValidKey/NamedUint"),
in: map[namedUint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
canonicalize: true,
want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
}, {
name: jsontest.Name("Maps/ValidKey/Float"),
in: map[float64]string{3.14159: "value"},
want: `{"3.14159":"value"}`,
}, {
name: jsontest.Name("Maps/InvalidKey/Float/NaN"),
in: map[float64]string{math.NaN(): "NaN", math.NaN(): "NaN"},
want: `{`,
wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: errors.New("invalid value: NaN")},
}, {
name: jsontest.Name("Maps/ValidKey/Interface"),
in: map[any]any{
"key": "key",
namedInt64(-64): int32(-32),
namedUint64(+64): uint32(+32),
namedFloat64(64.64): float32(32.32),
},
canonicalize: true,
want: `{"-64":-32,"64":32,"64.64":32.32,"key":"key"}`,
}, {
name: jsontest.Name("Maps/DuplicateName/String/AllowInvalidUTF8+AllowDuplicateNames"),
opts: []Options{jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(true)},
in: map[string]string{"\x80": "", "\x81": ""},
want: `{"�":"","�":""}`,
}, {
name: jsontest.Name("Maps/DuplicateName/String/AllowInvalidUTF8"),
opts: []Options{jsontext.AllowInvalidUTF8(true)},
in: map[string]string{"\x80": "", "\x81": ""},
want: `{"�":""`,
wantErr: export.NewDuplicateNameError([]byte(`"�"`), len64(`{"�":"",`)),
}, {
name: jsontest.Name("Maps/DuplicateName/NoCaseString/AllowDuplicateNames"),
opts: []Options{jsontext.AllowDuplicateNames(true)},
in: map[nocaseString]string{"hello": "", "HELLO": ""},
want: `{"hello":"","hello":""}`,
}, {
name: jsontest.Name("Maps/DuplicateName/NoCaseString"),
in: map[nocaseString]string{"hello": "", "HELLO": ""},
want: `{"hello":""`,
wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: reflect.TypeFor[nocaseString](), Err: export.NewDuplicateNameError([]byte(`"hello"`), len64(`{"hello":"",`))},
}, {
name: jsontest.Name("Maps/DuplicateName/NaNs/Deterministic+AllowDuplicateNames"),
opts: []Options{
WithMarshalers(
MarshalFuncV1(func(v float64) ([]byte, error) { return []byte(`"NaN"`), nil }),
),
Deterministic(true),
jsontext.AllowDuplicateNames(true),
},
in: map[float64]string{math.NaN(): "NaN", math.NaN(): "NaN"},
want: `{"NaN":"NaN","NaN":"NaN"}`,
}, {
name: jsontest.Name("Maps/InvalidValue/Channel"),
in: map[string]chan string{
"key": nil,
},
want: `{"key"`,
wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
}, {
name: jsontest.Name("Maps/String/Deterministic"),
opts: []Options{Deterministic(true)},
in: map[string]int{"a": 0, "b": 1, "c": 2},
want: `{"a":0,"b":1,"c":2}`,
}, {
name: jsontest.Name("Maps/String/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
opts: []Options{
Deterministic(true),
jsontext.AllowInvalidUTF8(true),
jsontext.AllowDuplicateNames(false),
},
in: map[string]int{"\xff": 0, "\xfe": 1},
want: `{"�":1`,
wantErr: export.NewDuplicateNameError([]byte(`"�"`), len64(`{"�":1,`)),
}, {
name: jsontest.Name("Maps/String/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
opts: []Options{
Deterministic(true),
jsontext.AllowInvalidUTF8(true),
jsontext.AllowDuplicateNames(true),
},
in: map[string]int{"\xff": 0, "\xfe": 1},
want: `{"�":1,"�":0}`,
}, {
name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs"),
opts: []Options{
Deterministic(true),
WithMarshalers(MarshalFuncV2(func(enc *jsontext.Encoder, v string, opts Options) error {
if p := enc.StackPointer(); p != "/X" {
return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
}
switch v {
case "a":
return enc.WriteToken(jsontext.String("b"))
case "b":
return enc.WriteToken(jsontext.String("a"))
default:
return fmt.Errorf("invalid value: %q", v)
}
})),
},
in: map[namedString]map[string]int{"X": {"a": -1, "b": 1}},
want: `{"X":{"a":1,"b":-1}}`,
}, {
name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs+RejectDuplicateNames"),
opts: []Options{
Deterministic(true),
WithMarshalers(MarshalFuncV2(func(enc *jsontext.Encoder, v string, opts Options) error {
if p := enc.StackPointer(); p != "/X" {
return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
}
switch v {
case "a", "b":
return enc.WriteToken(jsontext.String("x"))
default:
return fmt.Errorf("invalid value: %q", v)
}
})),
jsontext.AllowDuplicateNames(false),
},
in: map[namedString]map[string]int{"X": {"a": 1, "b": 1}},
want: `{"X":{"x":1`,
wantErr: export.NewDuplicateNameError([]byte(`"x"`), len64(`{"X":{"x":1,`)),
}, {
name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs+AllowDuplicateNames"),