Debian Codegraph @

decode_std_unmarshaler_test.go

raw
1 package json_test
2
3 import (
4 "bytes"
5 stdjson "encoding/json"
6 "log/slog"
7 "math/big"
8 "net"
9 "net/netip"
10 "reflect"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
15
16 "github.com/goccy/go-json"
17 )
18
19 // json.RawMessage is given the bytes of the buffer of the decoder without a copy, since its UnmarshalJSON copies
20 // them: what it holds must not change when the buffer is written again by the next calls and the next values of
21 // a stream.
22 func TestDecodeRawMessageKeepsItsBytes(t *testing.T) {
23 type message struct {
24 ID int
25 Input stdjson.RawMessage
26 Ptr *stdjson.RawMessage
27 List []stdjson.RawMessage
28 Map map[string]stdjson.RawMessage
29 }
30 input := func(i int) string {
31 v := `{"k":"` + strings.Repeat(strconv.Itoa(i), 40) + `","n":[` + strconv.Itoa(i) + `,null]}`
32 return `{"ID":` + strconv.Itoa(i) + `,"Input":` + v + `,"Ptr":` + v + `,"List":[` + v + `,"s",null],"Map":{"a":` + v + `}}`
33 }
34 var stream strings.Builder
35 var fromCalls, wants []message
36 for i := 0; i < 200; i++ {
37 var want, got message
38 if err := stdjson.Unmarshal([]byte(input(i)), &want); err != nil {
39 t.Fatal(err)
40 }
41 if err := json.Unmarshal([]byte(input(i)), &got); err != nil {
42 t.Fatal(err)
43 }
44 wants = append(wants, want)
45 fromCalls = append(fromCalls, got)
46 stream.WriteString(input(i) + "\n")
47 }
48 dec := json.NewDecoder(strings.NewReader(stream.String()))
49 var fromStream []message
50 for {
51 var got message
52 if err := dec.Decode(&got); err != nil {
53 break
54 }
55 fromStream = append(fromStream, got)
56 }
57 if len(fromStream) != len(wants) {
58 t.Fatalf("expected %d values from the stream but got %d", len(wants), len(fromStream))
59 }
60 for i, want := range wants {
61 for _, got := range []message{fromCalls[i], fromStream[i]} {
62 w, _ := stdjson.Marshal(want)
63 g, _ := stdjson.Marshal(got)
64 if !bytes.Equal(w, g) {
65 t.Fatalf("value %d:\n got %s\nwant %s", i, g, w)
66 }
67 }
68 }
69 // a RawMessage decoded into keeps using its own array, as UnmarshalJSON does.
70 m := make(stdjson.RawMessage, 0, 64)
71 before := &m[:1][0]
72 if err := json.Unmarshal([]byte(`{"a":1}`), &m); err != nil || string(m) != `{"a":1}` || &m[0] != before {
73 t.Fatalf("got %s %v, reused: %v", m, err, &m[0] == before)
74 }
75 }
76
77 // The unmarshalers of the types of the standard library are given the bytes of the buffer without a copy: they
78 // keep nothing of them. The values must be the ones encoding/json decodes, and must not change when the buffer is
79 // written again by the next values of a stream.
80 func TestDecodeStdUnmarshalers(t *testing.T) {
81 type record struct {
82 Int *big.Int
83 Value big.Int
84 Float *big.Float
85 Rat *big.Rat
86 Level slog.Level
87 Time time.Time
88 Addr netip.Addr
89 Prefix netip.Prefix
90 IP net.IP
91 Levels map[slog.Level]int
92 }
93 input := func(i int) string {
94 n := strconv.Itoa(i)
95 return `{"Int":1` + strings.Repeat(n, 30) + `,"Value":-` + n + `,"Float":"1.5e` + n + `","Rat":"` + n + `/7",` +
96 `"Level":"WARN+` + n + `","Time":"2026-09-28T01:02:03.` + strings.Repeat("1", 1+i%9) + `+09:00",` +
97 `"Addr":"2001:db8::` + strconv.FormatInt(int64(i), 16) + `","Prefix":"10.0.0.0/8","IP":"192.0.2.` + strconv.Itoa(i%255) + `",` +
98 `"Levels":{"INFO":` + n + `,"DEBUG-2":1}}`
99 }
100 var stream strings.Builder
101 var wants []record
102 for i := 0; i < 100; i++ {
103 var want, got record
104 if err := stdjson.Unmarshal([]byte(input(i)), &want); err != nil {
105 t.Fatal(err)
106 }
107 if err := json.Unmarshal([]byte(input(i)), &got); err != nil {
108 t.Fatal(err)
109 }
110 if !reflect.DeepEqual(got, want) {
111 t.Fatalf("value %d:\n got %+v\nwant %+v", i, got, want)
112 }
113 wants = append(wants, want)
114 stream.WriteString(input(i) + "\n")
115 }
116 dec := json.NewDecoder(strings.NewReader(stream.String()))
117 var fromStream []record
118 for {
119 var got record
120 if err := dec.Decode(&got); err != nil {
121 break
122 }
123 fromStream = append(fromStream, got)
124 }
125 if !reflect.DeepEqual(fromStream, wants) {
126 t.Fatal("the values decoded from the stream differ from the ones of encoding/json")
127 }
128 // null, and the errors of the unmarshalers, as encoding/json has them.
129 for _, in := range []string{`{"Int":null,"Time":null,"Addr":null}`, `{"Level":null}`, `{"Int":"x"}`, `{"Level":"LOUD"}`,
130 `{"Addr":"1.2.3"}`, `{"Time":"2026-13-01T00:00:00Z"}`, `{"Value":1e3}`} {
131 var want, got record
132 wantErr := stdjson.Unmarshal([]byte(in), &want)
133 gotErr := json.Unmarshal([]byte(in), &got)
134 // the value left by an error is not compared: go-json leaves a pointer nil which encoding/json of Go 1.26
135 // and earlier allocates before the unmarshaler fails.
136 if (wantErr == nil) != (gotErr == nil) || (wantErr == nil && !reflect.DeepEqual(got, want)) {
137 t.Fatalf("%s:\n got %+v %v\nwant %+v %v", in, got, gotErr, want, wantErr)
138 }
139 }
140 }
141
142 func BenchmarkDecodeRawMessage(b *testing.B) {
143 type message struct {
144 Type string
145 Input stdjson.RawMessage
146 }
147 data := []byte(`{"Type":"tool_use","Input":{"path":"internal/decoder/decode.go","old_string":"` + strings.Repeat("x", 200) + `","new_string":"y"}}`)
148 b.ReportAllocs()
149 for i := 0; i < b.N; i++ {
150 var v message
151 if err := json.Unmarshal(data, &v); err != nil {
152 b.Fatal(err)
153 }
154 }
155 }
156
157 // A type which has the UnmarshalJSON of time.Time only by embedding it is given the bytes of the buffer, which the
158 // method keeps nothing of: the values decoded from a stream, whose buffer is written again, are the ones of
159 // encoding/json.
160 func TestDecodeEmbeddedStdUnmarshalers(t *testing.T) {
161 type record struct {
162 T embeddedTime
163 TP *embeddedTime
164 A embeddedTimeAfter
165 Nst embeddedTimeNested
166 Ad embeddedAddr
167 }
168 input := func(i int) string {
169 ts := `"2026-09-28T01:02:03.` + strings.Repeat("1", 1+i%9) + `+09:00"`
170 return `{"T":` + ts + `,"TP":` + ts + `,"A":` + ts + `,"Nst":` + ts + `,"Ad":"2001:db8::` + strconv.Itoa(i) + `"}`
171 }
172 var stream strings.Builder
173 var wants []record
174 for i := 0; i < 50; i++ {
175 var want, got record
176 if err := stdjson.Unmarshal([]byte(input(i)), &want); err != nil {
177 t.Fatal(err)
178 }
179 if err := json.Unmarshal([]byte(input(i)), &got); err != nil {
180 t.Fatal(err)
181 }
182 if !reflect.DeepEqual(got, want) {
183 t.Fatalf("value %d:\n got %+v\nwant %+v", i, got, want)
184 }
185 wants = append(wants, want)
186 stream.WriteString(input(i) + "\n")
187 }
188 dec := json.NewDecoder(strings.NewReader(stream.String()))
189 var fromStream []record
190 for {
191 var got record
192 if err := dec.Decode(&got); err != nil {
193 break
194 }
195 fromStream = append(fromStream, got)
196 }
197 if !reflect.DeepEqual(fromStream, wants) {
198 t.Fatal("the values decoded from the stream differ from the ones of encoding/json")
199 }
200 }