Debian Codegraph @

encode_field_run_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "testing"
6
7 "github.com/goccy/go-json"
8 )
9
10 // Fields of the same kind in a row are encoded by the opcode of the run, which falls through the opcodes of
11 // the fields after the first: runs of every length, of every kind which has them, broken by a field of
12 // another kind or by omitempty, in embedded structs and at the end of a struct, must encode as encoding/json.
13
14 type fieldRunEmbedded struct {
15 E1 int
16 E2 int
17 E3 int
18 E4 int
19 }
20
21 type fieldRunPtrEmbedded struct {
22 P1 string
23 P2 string
24 }
25
26 type fieldRuns struct {
27 I1 int
28 I2 int
29 I3 int
30 I4 int
31 I5 int
32 S1 string
33 S2 string
34 S3 string
35 B1 bool
36 B2 bool
37 B3 bool
38 B4 bool
39 F1 float64
40 F2 float64
41 F3 float64
42 U1 uint
43 U2 uint
44 U3 uint16
45 U4 uint8
46 fieldRunEmbedded
47 I6 int
48 *fieldRunPtrEmbedded
49 S4 string
50 O1 int `json:",omitempty"`
51 O2 int `json:",omitempty"`
52 I7 int
53 I8 int
54 X1 int8
55 X2 int64
56 X3 int32
57 M1 float32
58 M2 float32
59 N1 int `json:"n1,string"`
60 N2 int `json:"n2,string"`
61 N3 int
62 N4 int
63 N5 int
64 N6 int
65 N7 int
66 }
67
68 func TestEncodeFieldRuns(t *testing.T) {
69 values := []any{
70 fieldRuns{},
71 &fieldRuns{},
72 fieldRuns{
73 I1: 1, I2: -2, I3: 3, I4: -4, I5: 5, S1: "a", S2: "b\"c", S3: "日本", B1: true, B3: true,
74 F1: 1.5, F2: -2.5, F3: 1e21, U1: 1, U2: 2, U3: 3, U4: 4, fieldRunEmbedded: fieldRunEmbedded{1, 2, 3, 4},
75 I6: 6, fieldRunPtrEmbedded: &fieldRunPtrEmbedded{"p1", "p2"}, S4: "s4", O1: 1, I7: 7, I8: 8,
76 X1: -1, X2: 2, X3: -3, M1: 1.25, M2: -1.25, N1: 1, N2: 2, N3: 3, N4: 4, N5: 5, N6: 6, N7: 7,
77 },
78 []fieldRuns{{I1: 1}, {S1: "x"}},
79 struct {
80 A int
81 B int
82 }{1, 2},
83 struct {
84 A string
85 B string
86 C string
87 D string
88 E string
89 F string
90 G string
91 }{"a", "b", "c", "d", "e", "f", "g"},
92 struct {
93 A bool
94 B bool
95 C float64
96 D float64
97 E float64
98 F float64
99 }{true, false, 1, 2, 3, 4},
100 }
101 for _, v := range values {
102 expected, err := stdjson.Marshal(v)
103 if err != nil {
104 t.Fatal(err)
105 }
106 got, err := json.Marshal(v)
107 if err != nil {
108 t.Fatalf("%T: %v", v, err)
109 }
110 if string(got) != string(expected) {
111 t.Errorf("%T:\n got %s\nwant %s", v, got, expected)
112 }
113 expected, _ = stdjson.MarshalIndent(v, "", " ")
114 got, err = json.MarshalIndent(v, "", " ")
115 if err != nil {
116 t.Fatalf("%T: %v", v, err)
117 }
118 if string(got) != string(expected) {
119 t.Errorf("%T with indent:\n got %s\nwant %s", v, got, expected)
120 }
121 }
122 }