1
2
3
4
5
6
7 package json
8
9 import (
10 "bytes"
11 "encoding"
12 "errors"
13 "fmt"
14 "image"
15 "io"
16 "maps"
17 "math"
18 "math/big"
19 "net"
20 "reflect"
21 "slices"
22 "strconv"
23 "strings"
24 "testing"
25 "time"
26 )
27
28 func len64(s string) int64 {
29 return int64(len(s))
30 }
31
32 type T struct {
33 X string
34 Y int
35 Z int `json:"-"`
36 }
37
38 type U struct {
39 Alphabet string `json:"alpha"`
40 }
41
42 type V struct {
43 F1 any
44 F2 int32
45 F3 Number
46 F4 *VOuter
47 }
48
49 type VOuter struct {
50 V V
51 }
52
53 type W struct {
54 S SS
55 }
56
57 type P struct {
58 PP PP
59 }
60
61 type PP struct {
62 T T
63 Ts []T
64 }
65
66 type SS string
67
68 func (*SS) UnmarshalJSON(data []byte) error {
69 return &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[SS]()}
70 }
71
72 type TAlias T
73
74 func (tt *TAlias) UnmarshalJSON(data []byte) error {
75 t := T{}
76 if err := Unmarshal(data, &t); err != nil {
77 return err
78 }
79 *tt = TAlias(t)
80 return nil
81 }
82
83 type TOuter struct {
84 T TAlias
85 }
86
87
88
89 var ifaceNumAsFloat64 = map[string]any{
90 "k1": float64(1),
91 "k2": "s",
92 "k3": []any{float64(1), float64(2.0), float64(3e-3)},
93 "k4": map[string]any{"kk1": "s", "kk2": float64(2)},
94 }
95
96 var ifaceNumAsNumber = map[string]any{
97 "k1": Number("1"),
98 "k2": "s",
99 "k3": []any{Number("1"), Number("2.0"), Number("3e-3")},
100 "k4": map[string]any{"kk1": "s", "kk2": Number("2")},
101 }
102
103 type tx struct {
104 x int
105 }
106
107 type u8 uint8
108
109
110
111 type unmarshaler struct {
112 T bool
113 }
114
115 func (u *unmarshaler) UnmarshalJSON(b []byte) error {
116 *u = unmarshaler{true}
117 return nil
118 }
119
120 type ustruct struct {
121 M unmarshaler
122 }
123
124 type unmarshalerText struct {
125 A, B string
126 }
127
128
129 func (u unmarshalerText) MarshalText() ([]byte, error) {
130 return []byte(u.A + ":" + u.B), nil
131 }
132
133 func (u *unmarshalerText) UnmarshalText(b []byte) error {
134 pos := bytes.IndexByte(b, ':')
135 if pos == -1 {
136 return errors.New("missing separator")
137 }
138 u.A, u.B = string(b[:pos]), string(b[pos+1:])
139 return nil
140 }
141
142 var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil)
143
144 type ustructText struct {
145 M unmarshalerText
146 }
147
148
149 type u8marshal uint8
150
151 func (u8 u8marshal) MarshalText() ([]byte, error) {
152 return []byte(fmt.Sprintf("u%d", u8)), nil
153 }
154
155 var errMissingU8Prefix = errors.New("missing 'u' prefix")
156
157 func (u8 *u8marshal) UnmarshalText(b []byte) error {
158 if !bytes.HasPrefix(b, []byte{'u'}) {
159 return errMissingU8Prefix
160 }
161 n, err := strconv.Atoi(string(b[1:]))
162 if err != nil {
163 return err
164 }
165 *u8 = u8marshal(n)
166 return nil
167 }
168
169 var _ encoding.TextUnmarshaler = (*u8marshal)(nil)
170
171 var (
172 umtrue = unmarshaler{true}
173 umslice = []unmarshaler{{true}}
174 umstruct = ustruct{unmarshaler{true}}
175
176 umtrueXY = unmarshalerText{"x", "y"}
177 umsliceXY = []unmarshalerText{{"x", "y"}}
178 umstructXY = ustructText{unmarshalerText{"x", "y"}}
179
180 ummapXY = map[unmarshalerText]bool{{"x", "y"}: true}
181 )
182
183
184
185 type Point struct {
186 Z int
187 }
188
189 type Top struct {
190 Level0 int
191 Embed0
192 *Embed0a
193 *Embed0b `json:"e,omitempty"`
194 Embed0c `json:"-"`
195 Loop
196 Embed0p
197 Embed0q
198 embed
199 }
200
201 type Embed0 struct {
202 Level1a int
203 Level1b int
204 Level1c int
205 Level1d int
206 Level1e int `json:"x"`
207 }
208
209 type Embed0a struct {
210 Level1a int `json:"Level1a,omitempty"`
211 Level1b int `json:"LEVEL1B,omitempty"`
212 Level1c int `json:"-"`
213 Level1d int
214 Level1f int `json:"x"`
215 }
216
217 type Embed0b Embed0
218
219 type Embed0c Embed0
220
221 type Embed0p struct {
222 image.Point
223 }
224
225 type Embed0q struct {
226 Point
227 }
228
229 type embed struct {
230 Q int
231 }
232
233 type Loop struct {
234 Loop1 int `json:",omitempty"`
235 Loop2 int `json:",omitempty"`
236 *Loop
237 }
238
239
240
241 type S5 struct {
242 S6
243 S7
244 S8
245 }
246
247 type S6 struct {
248 X int
249 }
250
251 type S7 S6
252
253 type S8 struct {
254 S9
255 }
256
257 type S9 struct {
258 X int
259 Y int
260 }
261
262
263
264 type S10 struct {
265 S11
266 S12
267 S13
268 }
269
270 type S11 struct {
271 S6
272 }
273
274 type S12 struct {
275 S6
276 }
277
278 type S13 struct {
279 S8
280 }
281
282 type Ambig struct {
283
284 First int `json:"HELLO"`
285 Second int `json:"Hello"`
286 }
287
288 type XYZ struct {
289 X any
290 Y any
291 Z any
292 }
293
294 type unexportedWithMethods struct{}
295
296 func (unexportedWithMethods) F() {}
297
298 type byteWithMarshalJSON byte
299
300 func (b byteWithMarshalJSON) MarshalJSON() ([]byte, error) {
301 return []byte(fmt.Sprintf(`"Z%.2x"`, byte(b))), nil
302 }
303
304 func (b *byteWithMarshalJSON) UnmarshalJSON(data []byte) error {
305 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
306 return fmt.Errorf("bad quoted string")
307 }
308 i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
309 if err != nil {
310 return fmt.Errorf("bad hex")
311 }
312 *b = byteWithMarshalJSON(i)
313 return nil
314 }
315
316 type byteWithPtrMarshalJSON byte
317
318 func (b *byteWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
319 return byteWithMarshalJSON(*b).MarshalJSON()
320 }
321
322 func (b *byteWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
323 return (*byteWithMarshalJSON)(b).UnmarshalJSON(data)
324 }
325
326 type byteWithMarshalText byte
327
328 func (b byteWithMarshalText) MarshalText() ([]byte, error) {
329 return []byte(fmt.Sprintf(`Z%.2x`, byte(b))), nil
330 }
331
332 func (b *byteWithMarshalText) UnmarshalText(data []byte) error {
333 if len(data) != 3 || data[0] != 'Z' {
334 return fmt.Errorf("bad quoted string")
335 }
336 i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
337 if err != nil {
338 return fmt.Errorf("bad hex")
339 }
340 *b = byteWithMarshalText(i)
341 return nil
342 }
343
344 type byteWithPtrMarshalText byte
345
346 func (b *byteWithPtrMarshalText) MarshalText() ([]byte, error) {
347 return byteWithMarshalText(*b).MarshalText()
348 }
349
350 func (b *byteWithPtrMarshalText) UnmarshalText(data []byte) error {
351 return (*byteWithMarshalText)(b).UnmarshalText(data)
352 }
353
354 type intWithMarshalJSON int
355
356 func (b intWithMarshalJSON) MarshalJSON() ([]byte, error) {
357 return []byte(fmt.Sprintf(`"Z%.2x"`, int(b))), nil
358 }
359
360 func (b *intWithMarshalJSON) UnmarshalJSON(data []byte) error {
361 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
362 return fmt.Errorf("bad quoted string")
363 }
364 i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
365 if err != nil {
366 return fmt.Errorf("bad hex")
367 }
368 *b = intWithMarshalJSON(i)
369 return nil
370 }
371
372 type intWithPtrMarshalJSON int
373
374 func (b *intWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
375 return intWithMarshalJSON(*b).MarshalJSON()
376 }
377
378 func (b *intWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
379 return (*intWithMarshalJSON)(b).UnmarshalJSON(data)
380 }
381
382 type intWithMarshalText int
383
384 func (b intWithMarshalText) MarshalText() ([]byte, error) {
385 return []byte(fmt.Sprintf(`Z%.2x`, int(b))), nil
386 }
387
388 func (b *intWithMarshalText) UnmarshalText(data []byte) error {
389 if len(data) != 3 || data[0] != 'Z' {
390 return fmt.Errorf("bad quoted string")
391 }
392 i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
393 if err != nil {
394 return fmt.Errorf("bad hex")
395 }
396 *b = intWithMarshalText(i)
397 return nil
398 }
399
400 type intWithPtrMarshalText int
401
402 func (b *intWithPtrMarshalText) MarshalText() ([]byte, error) {
403 return intWithMarshalText(*b).MarshalText()
404 }
405
406 func (b *intWithPtrMarshalText) UnmarshalText(data []byte) error {
407 return (*intWithMarshalText)(b).UnmarshalText(data)
408 }
409
410 type mapStringToStringData struct {
411 Data map[string]string `json:"data"`
412 }
413
414 type B struct {
415 B bool `json:",string"`
416 }
417
418 type DoublePtr struct {
419 I **int
420 J **int
421 }
422
423 type NestedUnamed struct{ F struct{ V int } }
424
425 var unmarshalTests = []struct {
426 CaseName
427 in string
428 ptr any
429 out any
430 err error
431 useNumber bool
432 golden bool
433 disallowUnknownFields bool
434 }{
435
436 {CaseName: Name(""), in: `true`, ptr: new(bool), out: true},
437 {CaseName: Name(""), in: `1`, ptr: new(int), out: 1},
438 {CaseName: Name(""), in: `1.2`, ptr: new(float64), out: 1.2},
439 {CaseName: Name(""), in: `1e1000`, ptr: new(float64), out: float64(0), err: &UnmarshalTypeError{Value: "number 1e1000", Type: reflect.TypeFor[float64](), Offset: len64("1e1000")}},
440 {CaseName: Name(""), in: `-5`, ptr: new(int16), out: int16(-5)},
441 {CaseName: Name(""), in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
442 {CaseName: Name(""), in: `2`, ptr: new(Number), out: Number("2")},
443 {CaseName: Name(""), in: `2`, ptr: new(any), out: float64(2.0)},
444 {CaseName: Name(""), in: `2`, ptr: new(any), out: Number("2"), useNumber: true},
445 {CaseName: Name(""), in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
446 {CaseName: Name(""), in: `"http:\/\/"`, ptr: new(string), out: "http://"},
447 {CaseName: Name(""), in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
448 {CaseName: Name(""), in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
449 {CaseName: Name(""), in: "null", ptr: new(any), out: nil},
450 {CaseName: Name(""), in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeFor[string](), len64(`{"X": [`), "T", "X"}},
451 {CaseName: Name(""), in: `{"X": 23}`, ptr: new(T), out: T{}, err: &UnmarshalTypeError{"number", reflect.TypeFor[string](), len64(`{"X": 23`), "T", "X"}},
452 {CaseName: Name(""), in: `{"x": 1}`, ptr: new(tx), out: tx{}},
453 {CaseName: Name(""), in: `{"x": 1}`, ptr: new(tx), out: tx{}},
454 {CaseName: Name(""), in: `{"x": 1}`, ptr: new(tx), err: fmt.Errorf("json: unknown field \"x\""), disallowUnknownFields: true},
455 {CaseName: Name(""), in: `{"S": 23}`, ptr: new(W), out: W{}, err: &UnmarshalTypeError{"number", reflect.TypeFor[SS](), 0, "W", "S"}},
456 {CaseName: Name(""), in: `{"T": {"X": 23}}`, ptr: new(TOuter), out: TOuter{}, err: &UnmarshalTypeError{"number", reflect.TypeFor[string](), len64(`{"T": {"`), "TOuter", "T.X"}},
457 {CaseName: Name(""), in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
458 {CaseName: Name(""), in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
459 {CaseName: Name(""), in: `{"F1":"1","F2":2,"F3":"3"}`, ptr: new(V), out: V{F1: "1", F2: int32(2), F3: Number("3")}, useNumber: true},
460 {CaseName: Name(""), in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsFloat64},
461 {CaseName: Name(""), in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsNumber, useNumber: true},
462
463
464 {CaseName: Name(""), in: "\n true ", ptr: new(bool), out: true},
465 {CaseName: Name(""), in: "\t 1 ", ptr: new(int), out: 1},
466 {CaseName: Name(""), in: "\r 1.2 ", ptr: new(float64), out: 1.2},
467 {CaseName: Name(""), in: "\t -5 \n", ptr: new(int16), out: int16(-5)},
468 {CaseName: Name(""), in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"},
469
470
471 {CaseName: Name(""), in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},
472 {CaseName: Name(""), in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}, err: fmt.Errorf("json: unknown field \"Z\""), disallowUnknownFields: true},
473
474 {CaseName: Name(""), in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},
475 {CaseName: Name(""), in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}, err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true},
476 {CaseName: Name(""), in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},
477 {CaseName: Name(""), in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},
478 {CaseName: Name(""), in: `{"alphabet": "xyz"}`, ptr: new(U), err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true},
479
480
481 {CaseName: Name(""), in: ``, ptr: new(any), err: &SyntaxError{"unexpected end of JSON input", 0}},
482 {CaseName: Name(""), in: " \n\r\t", ptr: new(any), err: &SyntaxError{"unexpected end of JSON input", len64(" \n\r\t")}},
483 {CaseName: Name(""), in: `[2, 3`, ptr: new(any), err: &SyntaxError{"unexpected end of JSON input", len64(`[2, 3`)}},
484 {CaseName: Name(""), in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", len64(`{"X": "foo", "Y"}`)}},
485 {CaseName: Name(""), in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", len64(`[1, 2, 3+`)}},
486 {CaseName: Name(""), in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", len64(`{"X":12x`)}, useNumber: true},
487 {CaseName: Name(""), in: `{"F3": -}`, ptr: new(V), err: &SyntaxError{"invalid character '}' in numeric literal", len64(`{"F3": -}`)}},
488
489
490 {CaseName: Name(""), in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", len64("\x01")}},
491 {CaseName: Name(""), in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", len64(" 42 \x01")}},
492 {CaseName: Name(""), in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", len64("\x01")}},
493 {CaseName: Name(""), in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", len64(" false \x01")}},
494 {CaseName: Name(""), in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", len64("\x01")}},
495 {CaseName: Name(""), in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", len64(" 3.4 \x01")}},
496 {CaseName: Name(""), in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", len64("\x01")}},
497 {CaseName: Name(""), in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", len64(" \"string\" \x01")}},
498
499
500 {CaseName: Name(""), in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},
501 {CaseName: Name(""), in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},
502 {CaseName: Name(""), in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},
503 {CaseName: Name(""), in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")},
504
505
506 {CaseName: Name(""), in: `[]`, ptr: new([]any), out: []any{}},
507 {CaseName: Name(""), in: `null`, ptr: new([]any), out: []any(nil)},
508 {CaseName: Name(""), in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}},
509 {CaseName: Name(""), in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}},
510
511
512 {CaseName: Name(""), in: allValueIndent, ptr: new(All), out: allValue},
513 {CaseName: Name(""), in: allValueCompact, ptr: new(All), out: allValue},
514 {CaseName: Name(""), in: allValueIndent, ptr: new(*All), out: &allValue},
515 {CaseName: Name(""), in: allValueCompact, ptr: new(*All), out: &allValue},
516 {CaseName: Name(""), in: pallValueIndent, ptr: new(All), out: pallValue},
517 {CaseName: Name(""), in: pallValueCompact, ptr: new(All), out: pallValue},
518 {CaseName: Name(""), in: pallValueIndent, ptr: new(*All), out: &pallValue},
519 {CaseName: Name(""), in: pallValueCompact, ptr: new(*All), out: &pallValue},
520
521
522 {CaseName: Name(""), in: `{"T":false}`, ptr: new(unmarshaler), out: umtrue},
523 {CaseName: Name(""), in: `{"T":false}`, ptr: new(*unmarshaler), out: &umtrue},
524 {CaseName: Name(""), in: `[{"T":false}]`, ptr: new([]unmarshaler), out: umslice},
525 {CaseName: Name(""), in: `[{"T":false}]`, ptr: new(*[]unmarshaler), out: &umslice},
526 {CaseName: Name(""), in: `{"M":{"T":"x:y"}}`, ptr: new(ustruct), out: umstruct},
527
528
529 {CaseName: Name(""), in: `"x:y"`, ptr: new(unmarshalerText), out: umtrueXY},
530 {CaseName: Name(""), in: `"x:y"`, ptr: new(*unmarshalerText), out: &umtrueXY},
531 {CaseName: Name(""), in: `["x:y"]`, ptr: new([]unmarshalerText), out: umsliceXY},
532 {CaseName: Name(""), in: `["x:y"]`, ptr: new(*[]unmarshalerText), out: &umsliceXY},
533 {CaseName: Name(""), in: `{"M":"x:y"}`, ptr: new(ustructText), out: umstructXY},
534
535
536 {
537 CaseName: Name(""),
538 in: `{"-1":"a","0":"b","1":"c"}`,
539 ptr: new(map[int]string),
540 out: map[int]string{-1: "a", 0: "b", 1: "c"},
541 },
542 {
543 CaseName: Name(""),
544 in: `{"0":"a","10":"c","9":"b"}`,
545 ptr: new(map[u8]string),
546 out: map[u8]string{0: "a", 9: "b", 10: "c"},
547 },
548 {
549 CaseName: Name(""),
550 in: `{"-9223372036854775808":"min","9223372036854775807":"max"}`,
551 ptr: new(map[int64]string),
552 out: map[int64]string{math.MinInt64: "min", math.MaxInt64: "max"},
553 },
554 {
555 CaseName: Name(""),
556 in: `{"18446744073709551615":"max"}`,
557 ptr: new(map[uint64]string),
558 out: map[uint64]string{math.MaxUint64: "max"},
559 },
560 {
561 CaseName: Name(""),
562 in: `{"0":false,"10":true}`,
563 ptr: new(map[uintptr]bool),
564 out: map[uintptr]bool{0: false, 10: true},
565 },
566
567
568
569 {
570 CaseName: Name(""),
571 in: `{"u2":4}`,
572 ptr: new(map[u8marshal]int),
573 out: map[u8marshal]int{2: 4},
574 },
575 {
576 CaseName: Name(""),
577 in: `{"2":4}`,
578 ptr: new(map[u8marshal]int),
579 out: map[u8marshal]int{},
580 err: errMissingU8Prefix,
581 },
582
583
584 {
585 CaseName: Name(""),
586 in: `{"abc":"abc"}`,
587 ptr: new(map[int]string),
588 out: map[int]string{},
589 err: &UnmarshalTypeError{Value: "number abc", Type: reflect.TypeFor[int](), Offset: len64(`{"`)},
590 },
591 {
592 CaseName: Name(""),
593 in: `{"256":"abc"}`,
594 ptr: new(map[uint8]string),
595 out: map[uint8]string{},
596 err: &UnmarshalTypeError{Value: "number 256", Type: reflect.TypeFor[uint8](), Offset: len64(`{"`)},
597 },
598 {
599 CaseName: Name(""),
600 in: `{"128":"abc"}`,
601 ptr: new(map[int8]string),
602 out: map[int8]string{},
603 err: &UnmarshalTypeError{Value: "number 128", Type: reflect.TypeFor[int8](), Offset: len64(`{"`)},
604 },
605 {
606 CaseName: Name(""),
607 in: `{"-1":"abc"}`,
608 ptr: new(map[uint8]string),
609 out: map[uint8]string{},
610 err: &UnmarshalTypeError{Value: "number -1", Type: reflect.TypeFor[uint8](), Offset: len64(`{"`)},
611 },
612 {
613 CaseName: Name(""),
614 in: `{"F":{"a":2,"3":4}}`,
615 ptr: new(map[string]map[int]int),
616 out: map[string]map[int]int{"F": {3: 4}},
617 err: &UnmarshalTypeError{Value: "number a", Type: reflect.TypeFor[int](), Offset: len64(`{"F":{"`)},
618 },
619 {
620 CaseName: Name(""),
621 in: `{"F":{"a":2,"3":4}}`,
622 ptr: new(map[string]map[uint]int),
623 out: map[string]map[uint]int{"F": {3: 4}},
624 err: &UnmarshalTypeError{Value: "number a", Type: reflect.TypeFor[uint](), Offset: len64(`{"F":{"`)},
625 },
626
627
628 {CaseName: Name(""), in: `{"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY},
629
630 {CaseName: Name(""), in: `{"x:y":false,"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY},
631
632 {
633 CaseName: Name(""),
634 in: `{
635 "Level0": 1,
636 "Level1b": 2,
637 "Level1c": 3,
638 "x": 4,
639 "Level1a": 5,
640 "LEVEL1B": 6,
641 "e": {
642 "Level1a": 8,
643 "Level1b": 9,
644 "Level1c": 10,
645 "Level1d": 11,
646 "x": 12
647 },
648 "Loop1": 13,
649 "Loop2": 14,
650 "X": 15,
651 "Y": 16,
652 "Z": 17,
653 "Q": 18
654 }`,
655 ptr: new(Top),
656 out: Top{
657 Level0: 1,
658 Embed0: Embed0{
659 Level1b: 2,
660 Level1c: 3,
661 },
662 Embed0a: &Embed0a{
663 Level1a: 5,
664 Level1b: 6,
665 },
666 Embed0b: &Embed0b{
667 Level1a: 8,
668 Level1b: 9,
669 Level1c: 10,
670 Level1d: 11,
671 Level1e: 12,
672 },
673 Loop: Loop{
674 Loop1: 13,
675 Loop2: 14,
676 },
677 Embed0p: Embed0p{
678 Point: image.Point{X: 15, Y: 16},
679 },
680 Embed0q: Embed0q{
681 Point: Point{Z: 17},
682 },
683 embed: embed{
684 Q: 18,
685 },
686 },
687 },
688 {
689 CaseName: Name(""),
690 in: `{"hello": 1}`,
691 ptr: new(Ambig),
692 out: Ambig{First: 1},
693 },
694
695 {
696 CaseName: Name(""),
697 in: `{"X": 1,"Y":2}`,
698 ptr: new(S5),
699 out: S5{S8: S8{S9: S9{Y: 2}}},
700 },
701 {
702 CaseName: Name(""),
703 in: `{"X": 1,"Y":2}`,
704 ptr: new(S5),
705 out: S5{S8: S8{S9{Y: 2}}},
706 err: fmt.Errorf("json: unknown field \"X\""),
707 disallowUnknownFields: true,
708 },
709 {
710 CaseName: Name(""),
711 in: `{"X": 1,"Y":2}`,
712 ptr: new(S10),
713 out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
714 },
715 {
716 CaseName: Name(""),
717 in: `{"X": 1,"Y":2}`,
718 ptr: new(S10),
719 out: S10{S13: S13{S8{S9{Y: 2}}}},
720 err: fmt.Errorf("json: unknown field \"X\""),
721 disallowUnknownFields: true,
722 },
723 {
724 CaseName: Name(""),
725 in: `{"I": 0, "I": null, "J": null}`,
726 ptr: new(DoublePtr),
727 out: DoublePtr{I: nil, J: nil},
728 },
729
730
731 {
732 CaseName: Name(""),
733 in: "\"hello\xffworld\"",
734 ptr: new(string),
735 out: "hello\ufffdworld",
736 },
737 {
738 CaseName: Name(""),
739 in: "\"hello\xc2\xc2world\"",
740 ptr: new(string),
741 out: "hello\ufffd\ufffdworld",
742 },
743 {
744 CaseName: Name(""),
745 in: "\"hello\xc2\xffworld\"",
746 ptr: new(string),
747 out: "hello\ufffd\ufffdworld",
748 },
749 {
750 CaseName: Name(""),
751 in: "\"hello\\ud800world\"",
752 ptr: new(string),
753 out: "hello\ufffdworld",
754 },
755 {
756 CaseName: Name(""),
757 in: "\"hello\\ud800\\ud800world\"",
758 ptr: new(string),
759 out: "hello\ufffd\ufffdworld",
760 },
761 {
762 CaseName: Name(""),
763 in: "\"hello\\ud800\\ud800world\"",
764 ptr: new(string),
765 out: "hello\ufffd\ufffdworld",
766 },
767 {
768 CaseName: Name(""),
769 in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"",
770 ptr: new(string),
771 out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
772 },
773
774
775 {
776 CaseName: Name(""),
777 in: `{"2009-11-10T23:00:00Z": "hello world"}`,
778 ptr: new(map[time.Time]string),
779 out: map[time.Time]string{time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC): "hello world"},
780 },
781
782
783 {
784 CaseName: Name(""),
785 in: `{"2009-11-10T23:00:00Z": "hello world"}`,
786 ptr: new(map[Point]string),
787 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeFor[map[Point]string](), Offset: len64(`{`)},
788 },
789 {
790 CaseName: Name(""),
791 in: `{"asdf": "hello world"}`,
792 ptr: new(map[unmarshaler]string),
793 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeFor[map[unmarshaler]string](), Offset: len64(`{`)},
794 },
795
796
797
798
799
800
801
802
803 {
804 CaseName: Name(""),
805 in: `"AQID"`,
806 ptr: new([]byteWithMarshalJSON),
807 out: []byteWithMarshalJSON{1, 2, 3},
808 },
809 {
810 CaseName: Name(""),
811 in: `["Z01","Z02","Z03"]`,
812 ptr: new([]byteWithMarshalJSON),
813 out: []byteWithMarshalJSON{1, 2, 3},
814 golden: true,
815 },
816 {
817 CaseName: Name(""),
818 in: `"AQID"`,
819 ptr: new([]byteWithMarshalText),
820 out: []byteWithMarshalText{1, 2, 3},
821 },
822 {
823 CaseName: Name(""),
824 in: `["Z01","Z02","Z03"]`,
825 ptr: new([]byteWithMarshalText),
826 out: []byteWithMarshalText{1, 2, 3},
827 golden: true,
828 },
829 {
830 CaseName: Name(""),
831 in: `"AQID"`,
832 ptr: new([]byteWithPtrMarshalJSON),
833 out: []byteWithPtrMarshalJSON{1, 2, 3},
834 },
835 {
836 CaseName: Name(""),
837 in: `["Z01","Z02","Z03"]`,
838 ptr: new([]byteWithPtrMarshalJSON),
839 out: []byteWithPtrMarshalJSON{1, 2, 3},
840 golden: true,
841 },
842 {
843 CaseName: Name(""),
844 in: `"AQID"`,
845 ptr: new([]byteWithPtrMarshalText),
846 out: []byteWithPtrMarshalText{1, 2, 3},
847 },
848 {
849 CaseName: Name(""),
850 in: `["Z01","Z02","Z03"]`,
851 ptr: new([]byteWithPtrMarshalText),
852 out: []byteWithPtrMarshalText{1, 2, 3},
853 golden: true,
854 },
855
856
857 {
858 CaseName: Name(""),
859 in: `["Z01","Z02","Z03"]`,
860 ptr: new([]intWithMarshalJSON),
861 out: []intWithMarshalJSON{1, 2, 3},
862 golden: true,
863 },
864 {
865 CaseName: Name(""),
866 in: `["Z01","Z02","Z03"]`,
867 ptr: new([]intWithMarshalText),
868 out: []intWithMarshalText{1, 2, 3},
869 golden: true,
870 },
871 {
872 CaseName: Name(""),
873 in: `["Z01","Z02","Z03"]`,
874 ptr: new([]intWithPtrMarshalJSON),
875 out: []intWithPtrMarshalJSON{1, 2, 3},
876 golden: true,
877 },
878 {
879 CaseName: Name(""),
880 in: `["Z01","Z02","Z03"]`,
881 ptr: new([]intWithPtrMarshalText),
882 out: []intWithPtrMarshalText{1, 2, 3},
883 golden: true,
884 },
885
886 {CaseName: Name(""), in: `0.000001`, ptr: new(float64), out: 0.000001, golden: true},
887 {CaseName: Name(""), in: `1e-7`, ptr: new(float64), out: 1e-7, golden: true},
888 {CaseName: Name(""), in: `100000000000000000000`, ptr: new(float64), out: 100000000000000000000.0, golden: true},
889 {CaseName: Name(""), in: `1e+21`, ptr: new(float64), out: 1e21, golden: true},
890 {CaseName: Name(""), in: `-0.000001`, ptr: new(float64), out: -0.000001, golden: true},
891 {CaseName: Name(""), in: `-1e-7`, ptr: new(float64), out: -1e-7, golden: true},
892 {CaseName: Name(""), in: `-100000000000000000000`, ptr: new(float64), out: -100000000000000000000.0, golden: true},
893 {CaseName: Name(""), in: `-1e+21`, ptr: new(float64), out: -1e21, golden: true},
894 {CaseName: Name(""), in: `999999999999999900000`, ptr: new(float64), out: 999999999999999900000.0, golden: true},
895 {CaseName: Name(""), in: `9007199254740992`, ptr: new(float64), out: 9007199254740992.0, golden: true},
896 {CaseName: Name(""), in: `9007199254740993`, ptr: new(float64), out: 9007199254740992.0, golden: false},
897
898 {
899 CaseName: Name(""),
900 in: `{"V": {"F2": "hello"}}`,
901 ptr: new(VOuter),
902 err: &UnmarshalTypeError{
903 Value: "string",
904 Struct: "V",
905 Field: "V.F2",
906 Type: reflect.TypeFor[int32](),
907 Offset: len64(`{"V": {"F2": "hello"`),
908 },
909 },
910 {
911 CaseName: Name(""),
912 in: `{"V": {"F4": {}, "F2": "hello"}}`,
913 ptr: new(VOuter),
914 out: VOuter{V: V{F4: &VOuter{}}},
915 err: &UnmarshalTypeError{
916 Value: "string",
917 Struct: "V",
918 Field: "V.F2",
919 Type: reflect.TypeFor[int32](),
920 Offset: len64(`{"V": {"F4": {}, "F2": "hello"`),
921 },
922 },
923
924 {
925 CaseName: Name(""),
926 in: `{"Level1a": "hello"}`,
927 ptr: new(Top),
928 out: Top{Embed0a: &Embed0a{}},
929 err: &UnmarshalTypeError{
930 Value: "string",
931 Struct: "Top",
932 Field: "Embed0a.Level1a",
933 Type: reflect.TypeFor[int](),
934 Offset: len64(`{"Level1a": "hello"`),
935 },
936 },
937
938
939
940 {CaseName: Name(""), in: `{"B":"true"}`, ptr: new(B), out: B{true}, golden: true},
941 {CaseName: Name(""), in: `{"B":"false"}`, ptr: new(B), out: B{false}, golden: true},
942 {CaseName: Name(""), in: `{"B": "maybe"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "maybe" into bool`)},
943 {CaseName: Name(""), in: `{"B": "tru"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "tru" into bool`)},
944 {CaseName: Name(""), in: `{"B": "False"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "False" into bool`)},
945 {CaseName: Name(""), in: `{"B": "null"}`, ptr: new(B), out: B{false}},
946 {CaseName: Name(""), in: `{"B": "nul"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "nul" into bool`)},
947 {CaseName: Name(""), in: `{"B": [2, 3]}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal unquoted value into bool`)},
948
949
950 {
951 CaseName: Name(""),
952 in: `{
953 "Level0": 1,
954 "Level1b": 2,
955 "Level1c": 3,
956 "x": 4,
957 "Level1a": 5,
958 "LEVEL1B": 6,
959 "e": {
960 "Level1a": 8,
961 "Level1b": 9,
962 "Level1c": 10,
963 "Level1d": 11,
964 "x": 12
965 },
966 "Loop1": 13,
967 "Loop2": 14,
968 "X": 15,
969 "Y": 16,
970 "Z": 17,
971 "Q": 18,
972 "extra": true
973 }`,
974 ptr: new(Top),
975 out: Top{
976 Level0: 1,
977 Embed0: Embed0{
978 Level1b: 2,
979 Level1c: 3,
980 },
981 Embed0a: &Embed0a{Level1a: 5, Level1b: 6},
982 Embed0b: &Embed0b{Level1a: 8, Level1b: 9, Level1c: 10, Level1d: 11, Level1e: 12},
983 Loop: Loop{
984 Loop1: 13,
985 Loop2: 14,
986 Loop: nil,
987 },
988 Embed0p: Embed0p{
989 Point: image.Point{
990 X: 15,
991 Y: 16,
992 },
993 },
994 Embed0q: Embed0q{Point: Point{Z: 17}},
995 embed: embed{Q: 18},
996 },
997 err: fmt.Errorf("json: unknown field \"extra\""),
998 disallowUnknownFields: true,
999 },
1000 {
1001 CaseName: Name(""),
1002 in: `{
1003 "Level0": 1,
1004 "Level1b": 2,
1005 "Level1c": 3,
1006 "x": 4,
1007 "Level1a": 5,
1008 "LEVEL1B": 6,
1009 "e": {
1010 "Level1a": 8,
1011 "Level1b": 9,
1012 "Level1c": 10,
1013 "Level1d": 11,
1014 "x": 12,
1015 "extra": null
1016 },
1017 "Loop1": 13,
1018 "Loop2": 14,
1019 "X": 15,
1020 "Y": 16,
1021 "Z": 17,
1022 "Q": 18
1023 }`,
1024 ptr: new(Top),
1025 out: Top{
1026 Level0: 1,
1027 Embed0: Embed0{
1028 Level1b: 2,
1029 Level1c: 3,
1030 },
1031 Embed0a: &Embed0a{Level1a: 5, Level1b: 6},
1032 Embed0b: &Embed0b{Level1a: 8, Level1b: 9, Level1c: 10, Level1d: 11, Level1e: 12},
1033 Loop: Loop{
1034 Loop1: 13,
1035 Loop2: 14,
1036 Loop: nil,
1037 },
1038 Embed0p: Embed0p{
1039 Point: image.Point{
1040 X: 15,
1041 Y: 16,
1042 },
1043 },
1044 Embed0q: Embed0q{Point: Point{Z: 17}},
1045 embed: embed{Q: 18},
1046 },
1047 err: fmt.Errorf("json: unknown field \"extra\""),
1048 disallowUnknownFields: true,
1049 },
1050
1051
1052 {
1053 CaseName: Name(""),
1054 in: `{"data":{"test1": "bob", "test2": 123}}`,
1055 ptr: new(mapStringToStringData),
1056 out: mapStringToStringData{map[string]string{"test1": "bob", "test2": ""}},
1057 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[string](), Offset: len64(`{"data":{"test1": "bob", "test2": 123`), Struct: "mapStringToStringData", Field: "data"},
1058 },
1059 {
1060 CaseName: Name(""),
1061 in: `{"data":{"test1": 123, "test2": "bob"}}`,
1062 ptr: new(mapStringToStringData),
1063 out: mapStringToStringData{Data: map[string]string{"test1": "", "test2": "bob"}},
1064 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[string](), Offset: len64(`{"data":{"test1": 123`), Struct: "mapStringToStringData", Field: "data"},
1065 },
1066
1067
1068 {
1069 CaseName: Name(""),
1070 in: `[1, 2, 3]`,
1071 ptr: new(MustNotUnmarshalText),
1072 err: &UnmarshalTypeError{Value: "array", Type: reflect.TypeFor[*MustNotUnmarshalText](), Offset: len64(`[`)},
1073 },
1074 {
1075 CaseName: Name(""),
1076 in: `{"foo": "bar"}`,
1077 ptr: new(MustNotUnmarshalText),
1078 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeFor[*MustNotUnmarshalText](), Offset: len64(`{`)},
1079 },
1080
1081 {
1082 CaseName: Name(""),
1083 in: `{"PP": {"T": {"Y": "bad-type"}}}`,
1084 ptr: new(P),
1085 err: &UnmarshalTypeError{
1086 Value: "string",
1087 Struct: "T",
1088 Field: "PP.T.Y",
1089 Type: reflect.TypeFor[int](),
1090 Offset: len64(`{"PP": {"T": {"Y": "bad-type"`),
1091 },
1092 },
1093 {
1094 CaseName: Name(""),
1095 in: `{"Ts": [{"Y": 1}, {"Y": 2}, {"Y": "bad-type"}]}`,
1096 ptr: new(PP),
1097 out: PP{Ts: []T{{Y: 1}, {Y: 2}, {Y: 0}}},
1098 err: &UnmarshalTypeError{
1099 Value: "string",
1100 Struct: "T",
1101 Field: "Ts.Y",
1102 Type: reflect.TypeFor[int](),
1103 Offset: len64(`{"Ts": [{"Y": 1}, {"Y": 2}, {"Y": "bad-type"`),
1104 },
1105 },
1106
1107 {
1108 CaseName: Name(""),
1109 in: `invalid`,
1110 ptr: new(Number),
1111 err: &SyntaxError{
1112 msg: "invalid character 'i' looking for beginning of value",
1113 Offset: len64(`i`),
1114 },
1115 },
1116 {
1117 CaseName: Name(""),
1118 in: `"invalid"`,
1119 ptr: new(Number),
1120 err: fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", `"invalid"`),
1121 },
1122 {
1123 CaseName: Name(""),
1124 in: `{"A":"invalid"}`,
1125 ptr: new(struct{ A Number }),
1126 err: fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", `"invalid"`),
1127 },
1128 {
1129 CaseName: Name(""),
1130 in: `{"A":"invalid"}`,
1131 ptr: new(struct {
1132 A Number `json:",string"`
1133 }),
1134 err: fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into json.Number", `invalid`),
1135 },
1136 {
1137 CaseName: Name(""),
1138 in: `{"A":"invalid"}`,
1139 ptr: new(map[string]Number),
1140 out: map[string]Number{},
1141 err: fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", `"invalid"`),
1142 },
1143
1144 {
1145 CaseName: Name(""),
1146 in: `5`,
1147 ptr: new(Number),
1148 out: Number("5"),
1149 },
1150 {
1151 CaseName: Name(""),
1152 in: `"5"`,
1153 ptr: new(Number),
1154 out: Number("5"),
1155 },
1156 {
1157 CaseName: Name(""),
1158 in: `{"N":5}`,
1159 ptr: new(struct{ N Number }),
1160 out: struct{ N Number }{"5"},
1161 },
1162 {
1163 CaseName: Name(""),
1164 in: `{"N":"5"}`,
1165 ptr: new(struct{ N Number }),
1166 out: struct{ N Number }{"5"},
1167 },
1168 {
1169 CaseName: Name(""),
1170 in: `{"N":5}`,
1171 ptr: new(struct {
1172 N Number `json:",string"`
1173 }),
1174 err: fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into json.Number"),
1175 },
1176 {
1177 CaseName: Name(""),
1178 in: `{"N":"5"}`,
1179 ptr: new(struct {
1180 N Number `json:",string"`
1181 }),
1182 out: struct {
1183 N Number `json:",string"`
1184 }{"5"},
1185 },
1186
1187
1188
1189
1190 {
1191 CaseName: Name(""),
1192 in: `[1,2,true,4,5}`,
1193 ptr: new([]int),
1194 err: &SyntaxError{msg: "invalid character '}' after array element", Offset: len64(`[1,2,true,4,5}`)},
1195 },
1196 {
1197 CaseName: Name(""),
1198 in: `[1,2,true,4,5]`,
1199 ptr: new([]int),
1200 out: []int{1, 2, 0, 4, 5},
1201 err: &UnmarshalTypeError{Value: "bool", Type: reflect.TypeFor[int](), Offset: len64(`[1,2,true`)},
1202 },
1203
1204 {
1205 CaseName: Name("DashComma"),
1206 in: `{"-":"hello"}`,
1207 ptr: new(struct {
1208 F string `json:"-,"`
1209 }),
1210 out: struct {
1211 F string `json:"-,"`
1212 }{"hello"},
1213 },
1214 {
1215 CaseName: Name("DashCommaOmitEmpty"),
1216 in: `{"-":"hello"}`,
1217 ptr: new(struct {
1218 F string `json:"-,omitempty"`
1219 }),
1220 out: struct {
1221 F string `json:"-,omitempty"`
1222 }{"hello"},
1223 },
1224
1225 {
1226 CaseName: Name("ErrorForNestedUnamed"),
1227 in: `{"F":{"V":"s"}}`,
1228 ptr: new(NestedUnamed),
1229 out: NestedUnamed{},
1230 err: &UnmarshalTypeError{Value: "string", Type: reflect.TypeFor[int](), Offset: len64(`{"F":{"V":"s"`), Field: "F.V"},
1231 },
1232 {
1233 CaseName: Name("ErrorInterface"),
1234 in: `1`,
1235 ptr: new(error),
1236 out: error(nil),
1237 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[error](), Offset: len64(`1`)},
1238 },
1239 {
1240 CaseName: Name("ErrorChan"),
1241 in: `1`,
1242 ptr: new(chan int),
1243 out: (chan int)(nil),
1244 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[chan int](), Offset: len64(`1`)},
1245 },
1246
1247
1248 {
1249 CaseName: Name("QuotedInt/GoSyntax"),
1250 in: `{"X": "-0000123"}`,
1251 ptr: new(struct {
1252 X int64 `json:",string"`
1253 }),
1254 out: struct {
1255 X int64 `json:",string"`
1256 }{-123},
1257 },
1258 {
1259 CaseName: Name("QuotedInt/Invalid"),
1260 in: `{"X": "123 "}`,
1261 ptr: new(struct {
1262 X int64 `json:",string"`
1263 }),
1264 err: &UnmarshalTypeError{Value: "number 123 ", Type: reflect.TypeFor[int64](), Field: "X", Offset: len64(`{"X": "123 "`)},
1265 },
1266 {
1267 CaseName: Name("QuotedUint/GoSyntax"),
1268 in: `{"X": "0000123"}`,
1269 ptr: new(struct {
1270 X uint64 `json:",string"`
1271 }),
1272 out: struct {
1273 X uint64 `json:",string"`
1274 }{123},
1275 },
1276 {
1277 CaseName: Name("QuotedUint/Invalid"),
1278 in: `{"X": "0x123"}`,
1279 ptr: new(struct {
1280 X uint64 `json:",string"`
1281 }),
1282 err: &UnmarshalTypeError{Value: "number 0x123", Type: reflect.TypeFor[uint64](), Field: "X", Offset: len64(`{"X": "0x123"`)},
1283 },
1284 {
1285 CaseName: Name("QuotedFloat/GoSyntax"),
1286 in: `{"X": "0x1_4p-2"}`,
1287 ptr: new(struct {
1288 X float64 `json:",string"`
1289 }),
1290 out: struct {
1291 X float64 `json:",string"`
1292 }{0x1_4p-2},
1293 },
1294 {
1295 CaseName: Name("QuotedFloat/Invalid"),
1296 in: `{"X": "1.5e1_"}`,
1297 ptr: new(struct {
1298 X float64 `json:",string"`
1299 }),
1300 err: &UnmarshalTypeError{Value: "number 1.5e1_", Type: reflect.TypeFor[float64](), Field: "X", Offset: len64(`{"X": "1.5e1_"`)},
1301 },
1302
1303
1304 {
1305 CaseName: Name("MapInt/NullKey"),
1306 in: `{"null":"abc"}`,
1307 ptr: new(map[int]string),
1308 out: map[int]string{},
1309 err: &UnmarshalTypeError{Value: "number null", Type: reflect.TypeFor[int](), Offset: len64(`{"`)},
1310 },
1311 {
1312 CaseName: Name("MapUint/NullKey"),
1313 in: `{"null":"abc"}`,
1314 ptr: new(map[uint]string),
1315 out: map[uint]string{},
1316 err: &UnmarshalTypeError{Value: "number null", Type: reflect.TypeFor[uint](), Offset: len64(`{"`)},
1317 },
1318 {
1319 CaseName: Name("UnsupportedTypes"),
1320 in: `{"A":null,"B":[1,2,3],"C":321,"D":"X"}`,
1321 ptr: &struct {
1322 A chan int
1323 B complex128
1324 C int
1325 D func()
1326 }{},
1327 out: struct {
1328 A chan int
1329 B complex128
1330 C int
1331 D func()
1332 }{C: 321},
1333 err: &UnmarshalTypeError{Value: "array", Type: reflect.TypeFor[complex128](), Field: "B", Offset: len64(`{"A":null,"B":[`)},
1334 },
1335 {
1336 CaseName: Name("QuotedNull"),
1337 in: `{"A":"null", "B":"null", "C":"null", "D":"null"}`,
1338 ptr: new(struct {
1339 A string `json:"A,string"`
1340 B int `json:"B,string"`
1341 C float64 `json:"C,string"`
1342 D bool `json:"D,string"`
1343 }),
1344 out: struct {
1345 A string `json:"A,string"`
1346 B int `json:"B,string"`
1347 C float64 `json:"C,string"`
1348 D bool `json:"D,string"`
1349 }{},
1350 },
1351 }
1352
1353 func TestMarshal(t *testing.T) {
1354 b, err := Marshal(allValue)
1355 if err != nil {
1356 t.Fatalf("Marshal error: %v", err)
1357 }
1358 if string(b) != allValueCompact {
1359 t.Errorf("Marshal:")
1360 diff(t, b, []byte(allValueCompact))
1361 return
1362 }
1363
1364 b, err = Marshal(pallValue)
1365 if err != nil {
1366 t.Fatalf("Marshal error: %v", err)
1367 }
1368 if string(b) != pallValueCompact {
1369 t.Errorf("Marshal:")
1370 diff(t, b, []byte(pallValueCompact))
1371 return
1372 }
1373 }
1374
1375 func TestMarshalInvalidUTF8(t *testing.T) {
1376 tests := []struct {
1377 CaseName
1378 in string
1379 want string
1380 }{
1381 {Name(""), "hello\xffworld", `"hello\ufffdworld"`},
1382 {Name(""), "", `""`},
1383 {Name(""), "\xff", `"\ufffd"`},
1384 {Name(""), "\xff\xff", `"\ufffd\ufffd"`},
1385 {Name(""), "a\xffb", `"a\ufffdb"`},
1386 {Name(""), "\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`},
1387 }
1388 for _, tt := range tests {
1389 t.Run(tt.Name, func(t *testing.T) {
1390 got, err := Marshal(tt.in)
1391 if string(got) != tt.want || err != nil {
1392 t.Errorf("%s: Marshal(%q):\n\tgot: (%q, %v)\n\twant: (%q, nil)", tt.Where, tt.in, got, err, tt.want)
1393 }
1394 })
1395 }
1396 }
1397
1398 func TestMarshalNumberZeroVal(t *testing.T) {
1399 var n Number
1400 out, err := Marshal(n)
1401 if err != nil {
1402 t.Fatalf("Marshal error: %v", err)
1403 }
1404 got := string(out)
1405 if got != "0" {
1406 t.Fatalf("Marshal: got %s, want 0", got)
1407 }
1408 }
1409
1410 func TestMarshalEmbeds(t *testing.T) {
1411 top := &Top{
1412 Level0: 1,
1413 Embed0: Embed0{
1414 Level1b: 2,
1415 Level1c: 3,
1416 },
1417 Embed0a: &Embed0a{
1418 Level1a: 5,
1419 Level1b: 6,
1420 },
1421 Embed0b: &Embed0b{
1422 Level1a: 8,
1423 Level1b: 9,
1424 Level1c: 10,
1425 Level1d: 11,
1426 Level1e: 12,
1427 },
1428 Loop: Loop{
1429 Loop1: 13,
1430 Loop2: 14,
1431 },
1432 Embed0p: Embed0p{
1433 Point: image.Point{X: 15, Y: 16},
1434 },
1435 Embed0q: Embed0q{
1436 Point: Point{Z: 17},
1437 },
1438 embed: embed{
1439 Q: 18,
1440 },
1441 }
1442 got, err := Marshal(top)
1443 if err != nil {
1444 t.Fatalf("Marshal error: %v", err)
1445 }
1446 want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}"
1447 if string(got) != want {
1448 t.Errorf("Marshal:\n\tgot: %s\n\twant: %s", got, want)
1449 }
1450 }
1451
1452 func equalError(a, b error) bool {
1453 isJSONError := func(err error) bool {
1454 switch err.(type) {
1455 case
1456 *InvalidUTF8Error,
1457 *InvalidUnmarshalError,
1458 *MarshalerError,
1459 *SyntaxError,
1460 *UnmarshalFieldError,
1461 *UnmarshalTypeError,
1462 *UnsupportedTypeError,
1463 *UnsupportedValueError:
1464 return true
1465 }
1466 return false
1467 }
1468
1469 if a == nil || b == nil {
1470 return a == nil && b == nil
1471 }
1472 if isJSONError(a) || isJSONError(b) {
1473 return reflect.DeepEqual(a, b)
1474 }
1475 return a.Error() == b.Error()
1476 }
1477
1478 func TestUnmarshal(t *testing.T) {
1479 for _, tt := range unmarshalTests {
1480 t.Run(tt.Name, func(t *testing.T) {
1481 in := []byte(tt.in)
1482 var scan scanner
1483 if err := checkValid(in, &scan); err != nil {
1484 if !equalError(err, tt.err) {
1485 t.Fatalf("%s: checkValid error:\n\tgot %#v\n\twant %#v", tt.Where, err, tt.err)
1486 }
1487 }
1488 if tt.ptr == nil {
1489 return
1490 }
1491
1492 typ := reflect.TypeOf(tt.ptr)
1493 if typ.Kind() != reflect.Pointer {
1494 t.Fatalf("%s: unmarshalTest.ptr %T is not a pointer type", tt.Where, tt.ptr)
1495 }
1496 typ = typ.Elem()
1497
1498
1499 v := reflect.New(typ)
1500
1501 if !reflect.DeepEqual(tt.ptr, v.Interface()) {
1502
1503
1504
1505
1506
1507
1508 t.Fatalf("%s: unmarshalTest.ptr %#v is not a pointer to a zero value", tt.Where, tt.ptr)
1509 }
1510
1511 dec := NewDecoder(bytes.NewReader(in))
1512 if tt.useNumber {
1513 dec.UseNumber()
1514 }
1515 if tt.disallowUnknownFields {
1516 dec.DisallowUnknownFields()
1517 }
1518 if tt.err != nil && strings.Contains(tt.err.Error(), "unexpected end of JSON input") {
1519
1520 if strings.TrimSpace(tt.in) == "" {
1521 tt.err = io.EOF
1522 } else {
1523 tt.err = io.ErrUnexpectedEOF
1524 }
1525 }
1526 if err := dec.Decode(v.Interface()); !equalError(err, tt.err) {
1527 t.Fatalf("%s: Decode error:\n\tgot: %v\n\twant: %v\n\n\tgot: %#v\n\twant: %#v", tt.Where, err, tt.err, err, tt.err)
1528 } else if err != nil && tt.out == nil {
1529
1530
1531 tt.out = reflect.Zero(v.Elem().Type()).Interface()
1532 }
1533 if got := v.Elem().Interface(); !reflect.DeepEqual(got, tt.out) {
1534 gotJSON, _ := Marshal(got)
1535 wantJSON, _ := Marshal(tt.out)
1536 t.Fatalf("%s: Decode:\n\tgot: %#+v\n\twant: %#+v\n\n\tgotJSON: %s\n\twantJSON: %s", tt.Where, got, tt.out, gotJSON, wantJSON)
1537 }
1538
1539
1540 if tt.err == nil {
1541 enc, err := Marshal(v.Interface())
1542 if err != nil {
1543 t.Fatalf("%s: Marshal error after roundtrip: %v", tt.Where, err)
1544 }
1545 if tt.golden && !bytes.Equal(enc, in) {
1546 t.Errorf("%s: Marshal:\n\tgot: %s\n\twant: %s", tt.Where, enc, in)
1547 }
1548 vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
1549 dec = NewDecoder(bytes.NewReader(enc))
1550 if tt.useNumber {
1551 dec.UseNumber()
1552 }
1553 if err := dec.Decode(vv.Interface()); err != nil {
1554 t.Fatalf("%s: Decode(%#q) error after roundtrip: %v", tt.Where, enc, err)
1555 }
1556 if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
1557 t.Fatalf("%s: Decode:\n\tgot: %#+v\n\twant: %#+v\n\n\tgotJSON: %s\n\twantJSON: %s",
1558 tt.Where, v.Elem().Interface(), vv.Elem().Interface(),
1559 stripWhitespace(string(enc)), stripWhitespace(string(in)))
1560 }
1561 }
1562 })
1563 }
1564 }
1565
1566 func TestUnmarshalMarshal(t *testing.T) {
1567 initBig()
1568 var v any
1569 if err := Unmarshal(jsonBig, &v); err != nil {
1570 t.Fatalf("Unmarshal error: %v", err)
1571 }
1572 b, err := Marshal(v)
1573 if err != nil {
1574 t.Fatalf("Marshal error: %v", err)
1575 }
1576 if !bytes.Equal(jsonBig, b) {
1577 t.Errorf("Marshal:")
1578 diff(t, b, jsonBig)
1579 return
1580 }
1581 }
1582
1583
1584 func TestNumberAccessors(t *testing.T) {
1585 tests := []struct {
1586 CaseName
1587 in string
1588 i int64
1589 intErr string
1590 f float64
1591 floatErr string
1592 }{
1593 {CaseName: Name(""), in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
1594 {CaseName: Name(""), in: "-12", i: -12, f: -12.0},
1595 {CaseName: Name(""), in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
1596 }
1597 for _, tt := range tests {
1598 t.Run(tt.Name, func(t *testing.T) {
1599 n := Number(tt.in)
1600 if got := n.String(); got != tt.in {
1601 t.Errorf("%s: Number(%q).String() = %s, want %s", tt.Where, tt.in, got, tt.in)
1602 }
1603 if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
1604 t.Errorf("%s: Number(%q).Int64() = %d, want %d", tt.Where, tt.in, i, tt.i)
1605 } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
1606 t.Errorf("%s: Number(%q).Int64() error:\n\tgot: %v\n\twant: %v", tt.Where, tt.in, err, tt.intErr)
1607 }
1608 if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
1609 t.Errorf("%s: Number(%q).Float64() = %g, want %g", tt.Where, tt.in, f, tt.f)
1610 } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
1611 t.Errorf("%s: Number(%q).Float64() error:\n\tgot %v\n\twant: %v", tt.Where, tt.in, err, tt.floatErr)
1612 }
1613 })
1614 }
1615 }
1616
1617 func TestLargeByteSlice(t *testing.T) {
1618 s0 := make([]byte, 2000)
1619 for i := range s0 {
1620 s0[i] = byte(i)
1621 }
1622 b, err := Marshal(s0)
1623 if err != nil {
1624 t.Fatalf("Marshal error: %v", err)
1625 }
1626 var s1 []byte
1627 if err := Unmarshal(b, &s1); err != nil {
1628 t.Fatalf("Unmarshal error: %v", err)
1629 }
1630 if !bytes.Equal(s0, s1) {
1631 t.Errorf("Marshal:")
1632 diff(t, s0, s1)
1633 }
1634 }
1635
1636 type Xint struct {
1637 X int
1638 }
1639
1640 func TestUnmarshalInterface(t *testing.T) {
1641 var xint Xint
1642 var i any = &xint
1643 if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
1644 t.Fatalf("Unmarshal error: %v", err)
1645 }
1646 if xint.X != 1 {
1647 t.Fatalf("xint.X = %d, want 1", xint.X)
1648 }
1649 }
1650
1651 func TestUnmarshalPtrPtr(t *testing.T) {
1652 var xint Xint
1653 pxint := &xint
1654 if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
1655 t.Fatalf("Unmarshal: %v", err)
1656 }
1657 if xint.X != 1 {
1658 t.Fatalf("xint.X = %d, want 1", xint.X)
1659 }
1660 }
1661
1662 func TestEscape(t *testing.T) {
1663 const input = `"foobar"<html>` + " [\u2028 \u2029]"
1664 const want = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"`
1665 got, err := Marshal(input)
1666 if err != nil {
1667 t.Fatalf("Marshal error: %v", err)
1668 }
1669 if string(got) != want {
1670 t.Errorf("Marshal(%#q):\n\tgot: %s\n\twant: %s", input, got, want)
1671 }
1672 }
1673
1674
1675
1676 func TestErrorMessageFromMisusedString(t *testing.T) {
1677
1678 type WrongString struct {
1679 Message string `json:"result,string"`
1680 }
1681 tests := []struct {
1682 CaseName
1683 in, err string
1684 }{
1685 {Name(""), `{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
1686 {Name(""), `{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
1687 {Name(""), `{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
1688 {Name(""), `{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`},
1689 {Name(""), `{"result":"\""}`, `json: invalid use of ,string struct tag, trying to unmarshal "\"" into string`},
1690 {Name(""), `{"result":"\"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "\"foo" into string`},
1691 }
1692 for _, tt := range tests {
1693 t.Run(tt.Name, func(t *testing.T) {
1694 r := strings.NewReader(tt.in)
1695 var s WrongString
1696 err := NewDecoder(r).Decode(&s)
1697 got := fmt.Sprintf("%v", err)
1698 if got != tt.err {
1699 t.Errorf("%s: Decode error:\n\tgot: %s\n\twant: %s", tt.Where, got, tt.err)
1700 }
1701 })
1702 }
1703 }
1704
1705 type All struct {
1706 Bool bool
1707 Int int
1708 Int8 int8
1709 Int16 int16
1710 Int32 int32
1711 Int64 int64
1712 Uint uint
1713 Uint8 uint8
1714 Uint16 uint16
1715 Uint32 uint32
1716 Uint64 uint64
1717 Uintptr uintptr
1718 Float32 float32
1719 Float64 float64
1720
1721 Foo string `json:"bar"`
1722 Foo2 string `json:"bar2,dummyopt"`
1723
1724 IntStr int64 `json:",string"`
1725 UintptrStr uintptr `json:",string"`
1726
1727 PBool *bool
1728 PInt *int
1729 PInt8 *int8
1730 PInt16 *int16
1731 PInt32 *int32
1732 PInt64 *int64
1733 PUint *uint
1734 PUint8 *uint8
1735 PUint16 *uint16
1736 PUint32 *uint32
1737 PUint64 *uint64
1738 PUintptr *uintptr
1739 PFloat32 *float32
1740 PFloat64 *float64
1741
1742 String string
1743 PString *string
1744
1745 Map map[string]Small
1746 MapP map[string]*Small
1747 PMap *map[string]Small
1748 PMapP *map[string]*Small
1749
1750 EmptyMap map[string]Small
1751 NilMap map[string]Small
1752
1753 Slice []Small
1754 SliceP []*Small
1755 PSlice *[]Small
1756 PSliceP *[]*Small
1757
1758 EmptySlice []Small
1759 NilSlice []Small
1760
1761 StringSlice []string
1762 ByteSlice []byte
1763
1764 Small Small
1765 PSmall *Small
1766 PPSmall **Small
1767
1768 Interface any
1769 PInterface *any
1770
1771 InvalidEmbed int `json:",embed"`
1772
1773 unexported int
1774 }
1775
1776 type Small struct {
1777 Tag string
1778 }
1779
1780 var allValue = All{
1781 Bool: true,
1782 Int: 2,
1783 Int8: 3,
1784 Int16: 4,
1785 Int32: 5,
1786 Int64: 6,
1787 Uint: 7,
1788 Uint8: 8,
1789 Uint16: 9,
1790 Uint32: 10,
1791 Uint64: 11,
1792 Uintptr: 12,
1793 Float32: 14.1,
1794 Float64: 15.1,
1795 Foo: "foo",
1796 Foo2: "foo2",
1797 IntStr: 42,
1798 UintptrStr: 44,
1799 String: "16",
1800 Map: map[string]Small{
1801 "17": {Tag: "tag17"},
1802 "18": {Tag: "tag18"},
1803 },
1804 MapP: map[string]*Small{
1805 "19": {Tag: "tag19"},
1806 "20": nil,
1807 },
1808 EmptyMap: map[string]Small{},
1809 Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}},
1810 SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
1811 EmptySlice: []Small{},
1812 StringSlice: []string{"str24", "str25", "str26"},
1813 ByteSlice: []byte{27, 28, 29},
1814 Small: Small{Tag: "tag30"},
1815 PSmall: &Small{Tag: "tag31"},
1816 Interface: 5.2,
1817 InvalidEmbed: 123,
1818 }
1819
1820 var pallValue = All{
1821 PBool: &allValue.Bool,
1822 PInt: &allValue.Int,
1823 PInt8: &allValue.Int8,
1824 PInt16: &allValue.Int16,
1825 PInt32: &allValue.Int32,
1826 PInt64: &allValue.Int64,
1827 PUint: &allValue.Uint,
1828 PUint8: &allValue.Uint8,
1829 PUint16: &allValue.Uint16,
1830 PUint32: &allValue.Uint32,
1831 PUint64: &allValue.Uint64,
1832 PUintptr: &allValue.Uintptr,
1833 PFloat32: &allValue.Float32,
1834 PFloat64: &allValue.Float64,
1835 PString: &allValue.String,
1836 PMap: &allValue.Map,
1837 PMapP: &allValue.MapP,
1838 PSlice: &allValue.Slice,
1839 PSliceP: &allValue.SliceP,
1840 PPSmall: &allValue.PSmall,
1841 PInterface: &allValue.Interface,
1842 }
1843
1844 var allValueIndent = `{
1845 "Bool": true,
1846 "Int": 2,
1847 "Int8": 3,
1848 "Int16": 4,
1849 "Int32": 5,
1850 "Int64": 6,
1851 "Uint": 7,
1852 "Uint8": 8,
1853 "Uint16": 9,
1854 "Uint32": 10,
1855 "Uint64": 11,
1856 "Uintptr": 12,
1857 "Float32": 14.1,
1858 "Float64": 15.1,
1859 "bar": "foo",
1860 "bar2": "foo2",
1861 "IntStr": "42",
1862 "UintptrStr": "44",
1863 "PBool": null,
1864 "PInt": null,
1865 "PInt8": null,
1866 "PInt16": null,
1867 "PInt32": null,
1868 "PInt64": null,
1869 "PUint": null,
1870 "PUint8": null,
1871 "PUint16": null,
1872 "PUint32": null,
1873 "PUint64": null,
1874 "PUintptr": null,
1875 "PFloat32": null,
1876 "PFloat64": null,
1877 "String": "16",
1878 "PString": null,
1879 "Map": {
1880 "17": {
1881 "Tag": "tag17"
1882 },
1883 "18": {
1884 "Tag": "tag18"
1885 }
1886 },
1887 "MapP": {
1888 "19": {
1889 "Tag": "tag19"
1890 },
1891 "20": null
1892 },
1893 "PMap": null,
1894 "PMapP": null,
1895 "EmptyMap": {},
1896 "NilMap": null,
1897 "Slice": [
1898 {
1899 "Tag": "tag20"
1900 },
1901 {
1902 "Tag": "tag21"
1903 }
1904 ],
1905 "SliceP": [
1906 {
1907 "Tag": "tag22"
1908 },
1909 null,
1910 {
1911 "Tag": "tag23"
1912 }
1913 ],
1914 "PSlice": null,
1915 "PSliceP": null,
1916 "EmptySlice": [],
1917 "NilSlice": null,
1918 "StringSlice": [
1919 "str24",
1920 "str25",
1921 "str26"
1922 ],
1923 "ByteSlice": "Gxwd",
1924 "Small": {
1925 "Tag": "tag30"
1926 },
1927 "PSmall": {
1928 "Tag": "tag31"
1929 },
1930 "PPSmall": null,
1931 "Interface": 5.2,
1932 "PInterface": null,
1933 "InvalidEmbed": 123
1934 }`
1935
1936 var allValueCompact = stripWhitespace(allValueIndent)
1937
1938 var pallValueIndent = `{
1939 "Bool": false,
1940 "Int": 0,
1941 "Int8": 0,
1942 "Int16": 0,
1943 "Int32": 0,
1944 "Int64": 0,
1945 "Uint": 0,
1946 "Uint8": 0,
1947 "Uint16": 0,
1948 "Uint32": 0,
1949 "Uint64": 0,
1950 "Uintptr": 0,
1951 "Float32": 0,
1952 "Float64": 0,
1953 "bar": "",
1954 "bar2": "",
1955 "IntStr": "0",
1956 "UintptrStr": "0",
1957 "PBool": true,
1958 "PInt": 2,
1959 "PInt8": 3,
1960 "PInt16": 4,
1961 "PInt32": 5,
1962 "PInt64": 6,
1963 "PUint": 7,
1964 "PUint8": 8,
1965 "PUint16": 9,
1966 "PUint32": 10,
1967 "PUint64": 11,
1968 "PUintptr": 12,
1969 "PFloat32": 14.1,
1970 "PFloat64": 15.1,
1971 "String": "",
1972 "PString": "16",
1973 "Map": null,
1974 "MapP": null,
1975 "PMap": {
1976 "17": {
1977 "Tag": "tag17"
1978 },
1979 "18": {
1980 "Tag": "tag18"
1981 }
1982 },
1983 "PMapP": {
1984 "19": {
1985 "Tag": "tag19"
1986 },
1987 "20": null
1988 },
1989 "EmptyMap": null,
1990 "NilMap": null,
1991 "Slice": null,
1992 "SliceP": null,
1993 "PSlice": [
1994 {
1995 "Tag": "tag20"
1996 },
1997 {
1998 "Tag": "tag21"
1999 }
2000 ],
2001 "PSliceP": [
2002 {
2003 "Tag": "tag22"
2004 },
2005 null,
2006 {
2007 "Tag": "tag23"
2008 }
2009 ],
2010 "EmptySlice": null,
2011 "NilSlice": null,
2012 "StringSlice": null,
2013 "ByteSlice": null,
2014 "Small": {
2015 "Tag": ""
2016 },
2017 "PSmall": null,
2018 "PPSmall": {
2019 "Tag": "tag31"
2020 },
2021 "Interface": null,
2022 "PInterface": 5.2,
2023 "InvalidEmbed": 0
2024 }`
2025
2026 var pallValueCompact = stripWhitespace(pallValueIndent)
2027
2028 func TestRefUnmarshal(t *testing.T) {
2029 type S struct {
2030
2031 R0 Ref
2032 R1 *Ref
2033 R2 RefText
2034 R3 *RefText
2035 }
2036 want := S{
2037 R0: 12,
2038 R1: new(Ref),
2039 R2: 13,
2040 R3: new(RefText),
2041 }
2042 *want.R1 = 12
2043 *want.R3 = 13
2044
2045 var got S
2046 if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil {
2047 t.Fatalf("Unmarshal error: %v", err)
2048 }
2049 if !reflect.DeepEqual(got, want) {
2050 t.Errorf("Unmarsha:\n\tgot: %+v\n\twant: %+v", got, want)
2051 }
2052 }
2053
2054
2055
2056 func TestEmptyString(t *testing.T) {
2057 type T2 struct {
2058 Number1 int `json:",string"`
2059 Number2 int `json:",string"`
2060 }
2061 data := `{"Number1":"1", "Number2":""}`
2062 dec := NewDecoder(strings.NewReader(data))
2063 var got T2
2064 switch err := dec.Decode(&got); {
2065 case err == nil:
2066 t.Fatalf("Decode error: got nil, want non-nil")
2067 case got.Number1 != 1:
2068 t.Fatalf("Decode: got.Number1 = %d, want 1", got.Number1)
2069 }
2070 }
2071
2072
2073
2074 func TestNullString(t *testing.T) {
2075 type T struct {
2076 A int `json:",string"`
2077 B int `json:",string"`
2078 C *int `json:",string"`
2079 }
2080 data := []byte(`{"A": "1", "B": null, "C": null}`)
2081 var s T
2082 s.B = 1
2083 s.C = new(int)
2084 *s.C = 2
2085 switch err := Unmarshal(data, &s); {
2086 case err != nil:
2087 t.Fatalf("Unmarshal error: %v", err)
2088 case s.B != 1:
2089 t.Fatalf("Unmarshal: s.B = %d, want 1", s.B)
2090 case s.C != nil:
2091 t.Fatalf("Unmarshal: s.C = new(%d), want nil", *s.C)
2092 }
2093 }
2094
2095 func TestInterfaceSet(t *testing.T) {
2096 errUnmarshal := &UnmarshalTypeError{Value: "object", Offset: len64(`{"X":{`), Type: reflect.TypeFor[int](), Field: "X"}
2097 tests := []struct {
2098 CaseName
2099 pre any
2100 json string
2101 post any
2102 }{
2103 {Name(""), "foo", `"bar"`, "bar"},
2104 {Name(""), "foo", `2`, 2.0},
2105 {Name(""), "foo", `true`, true},
2106 {Name(""), "foo", `null`, nil},
2107 {Name(""), map[string]any{}, `true`, true},
2108 {Name(""), []string{}, `true`, true},
2109
2110 {Name(""), any(nil), `null`, any(nil)},
2111 {Name(""), (*int)(nil), `null`, any(nil)},
2112 {Name(""), (*int)(new(0)), `null`, any(nil)},
2113 {Name(""), (*int)(new(1)), `null`, any(nil)},
2114 {Name(""), (**int)(nil), `null`, any(nil)},
2115 {Name(""), (**int)(new((*int)(nil))), `null`, (**int)(new((*int)(nil)))},
2116 {Name(""), (**int)(new(new(1))), `null`, (**int)(new((*int)(nil)))},
2117 {Name(""), (***int)(nil), `null`, any(nil)},
2118 {Name(""), (***int)(new((**int)(nil))), `null`, (***int)(new((**int)(nil)))},
2119 {Name(""), (***int)(new(new((*int)(nil)))), `null`, (***int)(new((**int)(nil)))},
2120 {Name(""), (***int)(new(new(new(1)))), `null`, (***int)(new((**int)(nil)))},
2121
2122 {Name(""), any(nil), `2`, float64(2)},
2123 {Name(""), (int)(1), `2`, float64(2)},
2124 {Name(""), (*int)(nil), `2`, float64(2)},
2125 {Name(""), (*int)(new(0)), `2`, (*int)(new(2))},
2126 {Name(""), (*int)(new(1)), `2`, (*int)(new(2))},
2127 {Name(""), (**int)(nil), `2`, float64(2)},
2128 {Name(""), (**int)(new((*int)(nil))), `2`, (**int)(new(new(2)))},
2129 {Name(""), (**int)(new(new(1))), `2`, (**int)(new(new(2)))},
2130 {Name(""), (***int)(nil), `2`, float64(2)},
2131 {Name(""), (***int)(new((**int)(nil))), `2`, (***int)(new(new(new(2))))},
2132 {Name(""), (***int)(new(new((*int)(nil)))), `2`, (***int)(new(new(new(2))))},
2133 {Name(""), (***int)(new(new(new(1)))), `2`, (***int)(new(new(new(2))))},
2134
2135 {Name(""), any(nil), `{}`, map[string]any{}},
2136 {Name(""), (int)(1), `{}`, map[string]any{}},
2137 {Name(""), (*int)(nil), `{}`, map[string]any{}},
2138 {Name(""), (*int)(new(0)), `{}`, errUnmarshal},
2139 {Name(""), (*int)(new(1)), `{}`, errUnmarshal},
2140 {Name(""), (**int)(nil), `{}`, map[string]any{}},
2141 {Name(""), (**int)(new((*int)(nil))), `{}`, errUnmarshal},
2142 {Name(""), (**int)(new(new(1))), `{}`, errUnmarshal},
2143 {Name(""), (***int)(nil), `{}`, map[string]any{}},
2144 {Name(""), (***int)(new((**int)(nil))), `{}`, errUnmarshal},
2145 {Name(""), (***int)(new(new((*int)(nil)))), `{}`, errUnmarshal},
2146 {Name(""), (***int)(new(new(new(1)))), `{}`, errUnmarshal},
2147 }
2148 for _, tt := range tests {
2149 t.Run(tt.Name, func(t *testing.T) {
2150 b := struct{ X any }{tt.pre}
2151 blob := `{"X":` + tt.json + `}`
2152 if err := Unmarshal([]byte(blob), &b); err != nil {
2153 if wantErr, _ := tt.post.(error); equalError(err, wantErr) {
2154 return
2155 }
2156 t.Fatalf("%s: Unmarshal(%#q) error: %v", tt.Where, blob, err)
2157 }
2158 if !reflect.DeepEqual(b.X, tt.post) {
2159 t.Errorf("%s: Unmarshal(%#q):\n\tpre.X: %#v\n\tgot.X: %#v\n\twant.X: %#v", tt.Where, blob, tt.pre, b.X, tt.post)
2160 }
2161 })
2162 }
2163 }
2164
2165 type NullTest struct {
2166 Bool bool
2167 Int int
2168 Int8 int8
2169 Int16 int16
2170 Int32 int32
2171 Int64 int64
2172 Uint uint
2173 Uint8 uint8
2174 Uint16 uint16
2175 Uint32 uint32
2176 Uint64 uint64
2177 Float32 float32
2178 Float64 float64
2179 String string
2180 PBool *bool
2181 Map map[string]string
2182 Slice []string
2183 Interface any
2184
2185 PRaw *RawMessage
2186 PTime *time.Time
2187 PBigInt *big.Int
2188 PText *MustNotUnmarshalText
2189 PBuffer *bytes.Buffer
2190 PStruct *struct{}
2191
2192 Raw RawMessage
2193 Time time.Time
2194 BigInt big.Int
2195 Text MustNotUnmarshalText
2196 Buffer bytes.Buffer
2197 Struct struct{}
2198 }
2199
2200
2201
2202 func TestUnmarshalNulls(t *testing.T) {
2203
2204
2205
2206
2207
2208
2209 jsonData := []byte(`{
2210 "Bool" : null,
2211 "Int" : null,
2212 "Int8" : null,
2213 "Int16" : null,
2214 "Int32" : null,
2215 "Int64" : null,
2216 "Uint" : null,
2217 "Uint8" : null,
2218 "Uint16" : null,
2219 "Uint32" : null,
2220 "Uint64" : null,
2221 "Float32" : null,
2222 "Float64" : null,
2223 "String" : null,
2224 "PBool": null,
2225 "Map": null,
2226 "Slice": null,
2227 "Interface": null,
2228 "PRaw": null,
2229 "PTime": null,
2230 "PBigInt": null,
2231 "PText": null,
2232 "PBuffer": null,
2233 "PStruct": null,
2234 "Raw": null,
2235 "Time": null,
2236 "BigInt": null,
2237 "Text": null,
2238 "Buffer": null,
2239 "Struct": null
2240 }`)
2241 nulls := NullTest{
2242 Bool: true,
2243 Int: 2,
2244 Int8: 3,
2245 Int16: 4,
2246 Int32: 5,
2247 Int64: 6,
2248 Uint: 7,
2249 Uint8: 8,
2250 Uint16: 9,
2251 Uint32: 10,
2252 Uint64: 11,
2253 Float32: 12.1,
2254 Float64: 13.1,
2255 String: "14",
2256 PBool: new(bool),
2257 Map: map[string]string{},
2258 Slice: []string{},
2259 Interface: new(MustNotUnmarshalJSON),
2260 PRaw: new(RawMessage),
2261 PTime: new(time.Time),
2262 PBigInt: new(big.Int),
2263 PText: new(MustNotUnmarshalText),
2264 PStruct: new(struct{}),
2265 PBuffer: new(bytes.Buffer),
2266 Raw: RawMessage("123"),
2267 Time: time.Unix(123456789, 0),
2268 BigInt: *big.NewInt(123),
2269 }
2270
2271 before := nulls.Time.String()
2272
2273 err := Unmarshal(jsonData, &nulls)
2274 if err != nil {
2275 t.Errorf("Unmarshal of null values failed: %v", err)
2276 }
2277 if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
2278 nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
2279 nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
2280 t.Errorf("Unmarshal of null values affected primitives")
2281 }
2282
2283 if nulls.PBool != nil {
2284 t.Errorf("Unmarshal of null did not clear nulls.PBool")
2285 }
2286 if nulls.Map != nil {
2287 t.Errorf("Unmarshal of null did not clear nulls.Map")
2288 }
2289 if nulls.Slice != nil {
2290 t.Errorf("Unmarshal of null did not clear nulls.Slice")
2291 }
2292 if nulls.Interface != nil {
2293 t.Errorf("Unmarshal of null did not clear nulls.Interface")
2294 }
2295 if nulls.PRaw != nil {
2296 t.Errorf("Unmarshal of null did not clear nulls.PRaw")
2297 }
2298 if nulls.PTime != nil {
2299 t.Errorf("Unmarshal of null did not clear nulls.PTime")
2300 }
2301 if nulls.PBigInt != nil {
2302 t.Errorf("Unmarshal of null did not clear nulls.PBigInt")
2303 }
2304 if nulls.PText != nil {
2305 t.Errorf("Unmarshal of null did not clear nulls.PText")
2306 }
2307 if nulls.PBuffer != nil {
2308 t.Errorf("Unmarshal of null did not clear nulls.PBuffer")
2309 }
2310 if nulls.PStruct != nil {
2311 t.Errorf("Unmarshal of null did not clear nulls.PStruct")
2312 }
2313
2314 if string(nulls.Raw) != "null" {
2315 t.Errorf("Unmarshal of RawMessage null did not record null: %v", string(nulls.Raw))
2316 }
2317 if nulls.Time.String() != before {
2318 t.Errorf("Unmarshal of time.Time null set time to %v", nulls.Time.String())
2319 }
2320 if nulls.BigInt.String() != "123" {
2321 t.Errorf("Unmarshal of big.Int null set int to %v", nulls.BigInt.String())
2322 }
2323 }
2324
2325 type MustNotUnmarshalJSON struct{}
2326
2327 func (x MustNotUnmarshalJSON) UnmarshalJSON(data []byte) error {
2328 return errors.New("MustNotUnmarshalJSON was used")
2329 }
2330
2331 type MustNotUnmarshalText struct{}
2332
2333 func (x MustNotUnmarshalText) UnmarshalText(text []byte) error {
2334 return errors.New("MustNotUnmarshalText was used")
2335 }
2336
2337 func TestStringKind(t *testing.T) {
2338 type stringKind string
2339 want := map[stringKind]int{"foo": 42}
2340 data, err := Marshal(want)
2341 if err != nil {
2342 t.Fatalf("Marshal error: %v", err)
2343 }
2344 var got map[stringKind]int
2345 err = Unmarshal(data, &got)
2346 if err != nil {
2347 t.Fatalf("Unmarshal error: %v", err)
2348 }
2349 if !maps.Equal(got, want) {
2350 t.Fatalf("Marshal/Unmarshal mismatch:\n\tgot: %v\n\twant: %v", got, want)
2351 }
2352 }
2353
2354
2355
2356
2357 func TestByteKind(t *testing.T) {
2358 type byteKind []byte
2359 want := byteKind("hello")
2360 data, err := Marshal(want)
2361 if err != nil {
2362 t.Fatalf("Marshal error: %v", err)
2363 }
2364 var got byteKind
2365 err = Unmarshal(data, &got)
2366 if err != nil {
2367 t.Fatalf("Unmarshal error: %v", err)
2368 }
2369 if !slices.Equal(got, want) {
2370 t.Fatalf("Marshal/Unmarshal mismatch:\n\tgot: %v\n\twant: %v", got, want)
2371 }
2372 }
2373
2374
2375
2376 func TestSliceOfCustomByte(t *testing.T) {
2377 type Uint8 uint8
2378 want := []Uint8("hello")
2379 data, err := Marshal(want)
2380 if err != nil {
2381 t.Fatalf("Marshal error: %v", err)
2382 }
2383 var got []Uint8
2384 err = Unmarshal(data, &got)
2385 if err != nil {
2386 t.Fatalf("Unmarshal error: %v", err)
2387 }
2388 if !slices.Equal(got, want) {
2389 t.Fatalf("Marshal/Unmarshal mismatch:\n\tgot: %v\n\twant: %v", got, want)
2390 }
2391 }
2392
2393 func TestUnmarshalTypeError(t *testing.T) {
2394 tests := []struct {
2395 CaseName
2396 dest any
2397 in string
2398 }{
2399 {Name(""), new(string), `{"user": "name"}`},
2400 {Name(""), new(error), `{}`},
2401 {Name(""), new(error), `[]`},
2402 {Name(""), new(error), `""`},
2403 {Name(""), new(error), `123`},
2404 {Name(""), new(error), `true`},
2405 }
2406 for _, tt := range tests {
2407 t.Run(tt.Name, func(t *testing.T) {
2408 err := Unmarshal([]byte(tt.in), tt.dest)
2409 if _, ok := err.(*UnmarshalTypeError); !ok {
2410 t.Errorf("%s: Unmarshal(%#q, %T):\n\tgot: %T\n\twant: %T",
2411 tt.Where, tt.in, tt.dest, err, new(UnmarshalTypeError))
2412 }
2413 })
2414 }
2415 }
2416
2417 func TestUnmarshalSyntax(t *testing.T) {
2418 var x any
2419 tests := []struct {
2420 CaseName
2421 in string
2422 }{
2423 {Name(""), "tru"},
2424 {Name(""), "fals"},
2425 {Name(""), "nul"},
2426 {Name(""), "123e"},
2427 {Name(""), `"hello`},
2428 {Name(""), `[1,2,3`},
2429 {Name(""), `{"key":1`},
2430 {Name(""), `{"key":1,`},
2431 }
2432 for _, tt := range tests {
2433 t.Run(tt.Name, func(t *testing.T) {
2434 err := Unmarshal([]byte(tt.in), &x)
2435 if _, ok := err.(*SyntaxError); !ok {
2436 t.Errorf("%s: Unmarshal(%#q, any):\n\tgot: %T\n\twant: %T",
2437 tt.Where, tt.in, err, new(SyntaxError))
2438 }
2439 })
2440 }
2441 }
2442
2443
2444
2445 type unexportedFields struct {
2446 Name string
2447 m map[string]any `json:"-"`
2448 m2 map[string]any `json:"abcd"`
2449
2450 s []int `json:"-"`
2451 }
2452
2453 func TestUnmarshalUnexported(t *testing.T) {
2454 input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}, "s": [2, 3]}`
2455 want := &unexportedFields{Name: "Bob"}
2456
2457 out := &unexportedFields{}
2458 err := Unmarshal([]byte(input), out)
2459 if err != nil {
2460 t.Errorf("Unmarshal error: %v", err)
2461 }
2462 if !reflect.DeepEqual(out, want) {
2463 t.Errorf("Unmarshal:\n\tgot: %+v\n\twant: %+v", out, want)
2464 }
2465 }
2466
2467
2468
2469 type Time3339 time.Time
2470
2471 func (t *Time3339) UnmarshalJSON(b []byte) error {
2472 if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
2473 return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b)
2474 }
2475 tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1]))
2476 if err != nil {
2477 return err
2478 }
2479 *t = Time3339(tm)
2480 return nil
2481 }
2482
2483 func TestUnmarshalJSONLiteralError(t *testing.T) {
2484 var t3 Time3339
2485 switch err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3); {
2486 case err == nil:
2487 t.Fatalf("Unmarshal error: got nil, want non-nil")
2488 case !strings.Contains(err.Error(), "range"):
2489 t.Errorf("Unmarshal error:\n\tgot: %v\n\twant: out of range", err)
2490 }
2491 }
2492
2493
2494
2495
2496 func TestSkipArrayObjects(t *testing.T) {
2497 json := `[{}]`
2498 var dest [0]any
2499
2500 err := Unmarshal([]byte(json), &dest)
2501 if err != nil {
2502 t.Errorf("Unmarshal error: %v", err)
2503 }
2504 }
2505
2506
2507
2508
2509 func TestPrefilled(t *testing.T) {
2510
2511 tests := []struct {
2512 CaseName
2513 in string
2514 ptr any
2515 out any
2516 wantErr error
2517 }{{
2518 CaseName: Name(""),
2519 in: `{"X": 1, "Y": 2}`,
2520 ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5},
2521 out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5},
2522 }, {
2523 CaseName: Name(""),
2524 in: `{"X": 1, "Y": 2}`,
2525 ptr: &map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5},
2526 out: &map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5},
2527 }, {
2528 CaseName: Name(""),
2529 in: `[2]`,
2530 ptr: &[]int{1},
2531 out: &[]int{2},
2532 }, {
2533 CaseName: Name(""),
2534 in: `[2, 3]`,
2535 ptr: &[]int{1},
2536 out: &[]int{2, 3},
2537 }, {
2538 CaseName: Name(""),
2539 in: `[2, 3]`,
2540 ptr: &[...]int{1},
2541 out: &[...]int{2},
2542 }, {
2543 CaseName: Name(""),
2544 in: `[3]`,
2545 ptr: &[...]int{1, 2},
2546 out: &[...]int{3, 0},
2547 }, {
2548 CaseName: Name(""),
2549 in: `1e1000`,
2550 ptr: new(float64(math.Pi)),
2551 out: new(float64(math.Pi)),
2552 wantErr: &UnmarshalTypeError{Value: "number 1e1000", Type: reflect.TypeFor[float64](), Offset: len64("1e1000")},
2553 }, {
2554 CaseName: Name(""),
2555 in: `1e1000`,
2556 ptr: new(any(float64(0))),
2557 out: new(any(float64(0))),
2558 wantErr: &UnmarshalTypeError{Value: "number 1e1000", Type: reflect.TypeFor[float64](), Offset: len64("1e1000") + 1},
2559 }}
2560 for _, tt := range tests {
2561 t.Run(tt.Name, func(t *testing.T) {
2562 ptrstr := fmt.Sprintf("%v", tt.ptr)
2563 err := Unmarshal([]byte(tt.in), tt.ptr)
2564 if !reflect.DeepEqual(tt.ptr, tt.out) {
2565 t.Errorf("%s: Unmarshal(%#q, %T):\n\tgot: %v\n\twant: %v", tt.Where, tt.in, ptrstr, tt.ptr, tt.out)
2566 }
2567 if !reflect.DeepEqual(err, tt.wantErr) {
2568 t.Errorf("%s: Unmarshal(%#q, %T) error:\n\tgot: %v\n\twant: %v", tt.Where, tt.in, ptrstr, err, tt.wantErr)
2569 }
2570 })
2571 }
2572 }
2573
2574 func TestInvalidUnmarshal(t *testing.T) {
2575 tests := []struct {
2576 CaseName
2577 in string
2578 v any
2579 wantErr error
2580 }{
2581 {Name(""), `{"a":"1"}`, nil, &InvalidUnmarshalError{}},
2582 {Name(""), `{"a":"1"}`, struct{}{}, &InvalidUnmarshalError{reflect.TypeFor[struct{}]()}},
2583 {Name(""), `{"a":"1"}`, (*int)(nil), &InvalidUnmarshalError{reflect.TypeFor[*int]()}},
2584 {Name(""), `123`, nil, &InvalidUnmarshalError{}},
2585 {Name(""), `123`, struct{}{}, &InvalidUnmarshalError{reflect.TypeFor[struct{}]()}},
2586 {Name(""), `123`, (*int)(nil), &InvalidUnmarshalError{reflect.TypeFor[*int]()}},
2587 {Name(""), `123`, new(net.IP), &UnmarshalTypeError{Value: "number", Type: reflect.TypeFor[*net.IP](), Offset: len64(`123`)}},
2588 }
2589 for _, tt := range tests {
2590 t.Run(tt.Name, func(t *testing.T) {
2591 switch gotErr := Unmarshal([]byte(tt.in), tt.v); {
2592 case gotErr == nil:
2593 t.Fatalf("%s: Unmarshal error: got nil, want non-nil", tt.Where)
2594 case !reflect.DeepEqual(gotErr, tt.wantErr):
2595 t.Errorf("%s: Unmarshal error:\n\tgot: %#v\n\twant: %#v", tt.Where, gotErr, tt.wantErr)
2596 }
2597 })
2598 }
2599 }
2600
2601
2602
2603 func TestInvalidStringOption(t *testing.T) {
2604 num := 0
2605 item := struct {
2606 T time.Time `json:",string"`
2607 M map[string]string `json:",string"`
2608 S []string `json:",string"`
2609 A [1]string `json:",string"`
2610 I any `json:",string"`
2611 P *int `json:",string"`
2612 }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num}
2613
2614 data, err := Marshal(item)
2615 if err != nil {
2616 t.Fatalf("Marshal error: %v", err)
2617 }
2618
2619 err = Unmarshal(data, &item)
2620 if err != nil {
2621 t.Fatalf("Unmarshal error: %v", err)
2622 }
2623 }
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635 func TestUnmarshalEmbeddedUnexported(t *testing.T) {
2636 type (
2637 embed1 struct{ Q int }
2638 embed2 struct{ Q int }
2639 embed3 struct {
2640 Q int64 `json:",string"`
2641 }
2642 S1 struct {
2643 *embed1
2644 R int
2645 }
2646 S2 struct {
2647 *embed1
2648 Q int
2649 }
2650 S3 struct {
2651 embed1
2652 R int
2653 }
2654 S4 struct {
2655 *embed1
2656 embed2
2657 }
2658 S5 struct {
2659 *embed3
2660 R int
2661 }
2662 S6 struct {
2663 embed1 `json:"embed1"`
2664 }
2665 S7 struct {
2666 embed1 `json:"embed1"`
2667 embed2
2668 }
2669 S8 struct {
2670 embed1 `json:"embed1"`
2671 embed2 `json:"embed2"`
2672 Q int
2673 }
2674 S9 struct {
2675 unexportedWithMethods `json:"embed"`
2676 }
2677 )
2678
2679 tests := []struct {
2680 CaseName
2681 in string
2682 ptr any
2683 out any
2684 err error
2685 }{{
2686
2687 CaseName: Name(""),
2688 in: `{"R":2,"Q":1}`,
2689 ptr: new(S1),
2690 out: &S1{R: 2},
2691 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json.embed1"),
2692 }, {
2693
2694 CaseName: Name(""),
2695 in: `{"Q":1}`,
2696 ptr: new(S2),
2697 out: &S2{Q: 1},
2698 }, {
2699
2700 CaseName: Name(""),
2701 in: `{"R":2,"Q":1}`,
2702 ptr: new(S3),
2703 out: &S3{embed1: embed1{Q: 1}, R: 2},
2704 }, {
2705
2706
2707 CaseName: Name(""),
2708 in: `{"R":2}`,
2709 ptr: new(S4),
2710 out: new(S4),
2711 }, {
2712
2713 CaseName: Name(""),
2714 in: `{"R":2,"Q":1}`,
2715 ptr: new(S5),
2716 out: &S5{R: 2},
2717 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json.embed3"),
2718 }, {
2719
2720 CaseName: Name(""),
2721 in: `{"embed1": {"Q": 1}}`,
2722 ptr: new(S6),
2723 out: &S6{embed1{1}},
2724 }, {
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737 CaseName: Name(""),
2738 in: `{"embed1": {"Q": 1}, "Q": 2}`,
2739 ptr: new(S7),
2740 out: &S7{embed1{1}, embed2{2}},
2741 }, {
2742
2743 CaseName: Name(""),
2744 in: `{"embed1": {"Q": 1}, "embed2": {"Q": 2}, "Q": 3}`,
2745 ptr: new(S8),
2746 out: &S8{embed1{1}, embed2{2}, 3},
2747 }, {
2748
2749 CaseName: Name(""),
2750 in: `{"embed": {}}`,
2751 ptr: new(S9),
2752 out: &S9{},
2753 }}
2754 for _, tt := range tests {
2755 t.Run(tt.Name, func(t *testing.T) {
2756 err := Unmarshal([]byte(tt.in), tt.ptr)
2757 if !equalError(err, tt.err) {
2758 t.Errorf("%s: Unmarshal error:\n\tgot: %v\n\twant: %v", tt.Where, err, tt.err)
2759 }
2760 if !reflect.DeepEqual(tt.ptr, tt.out) {
2761 t.Errorf("%s: Unmarshal:\n\tgot: %#+v\n\twant: %#+v", tt.Where, tt.ptr, tt.out)
2762 }
2763 })
2764 }
2765 }
2766
2767 func TestUnmarshalErrorAfterMultipleJSON(t *testing.T) {
2768 tests := []struct {
2769 CaseName
2770 in string
2771 err error
2772 }{{
2773 CaseName: Name(""),
2774 in: `1 false null :`,
2775 err: &SyntaxError{"invalid character ':' looking for beginning of value", len64(`1 false null :`)},
2776 }, {
2777 CaseName: Name(""),
2778 in: `1 [] [,]`,
2779 err: &SyntaxError{"invalid character ',' looking for beginning of value", len64(`1 [] [,`)},
2780 }, {
2781 CaseName: Name(""),
2782 in: `1 [] [true:]`,
2783 err: &SyntaxError{"invalid character ':' after array element", len64(`1 [] [true:`)},
2784 }, {
2785 CaseName: Name(""),
2786 in: `1 {} {"x"=}`,
2787 err: &SyntaxError{"invalid character '=' after object key", len64(`1 {} {"x"=`)},
2788 }, {
2789 CaseName: Name(""),
2790 in: `falsetruenul#`,
2791 err: &SyntaxError{"invalid character '#' in literal null (expecting 'l')", len64(`falsetruenul#`)},
2792 }}
2793 for _, tt := range tests {
2794 t.Run(tt.Name, func(t *testing.T) {
2795 dec := NewDecoder(strings.NewReader(tt.in))
2796 var err error
2797 for err == nil {
2798 var v any
2799 err = dec.Decode(&v)
2800 }
2801 if !reflect.DeepEqual(err, tt.err) {
2802 t.Errorf("%s: Decode error:\n\tgot: %v\n\twant: %v", tt.Where, err, tt.err)
2803 }
2804 })
2805 }
2806 }
2807
2808 type unmarshalPanic struct{}
2809
2810 func (unmarshalPanic) UnmarshalJSON([]byte) error { panic(0xdead) }
2811
2812 func TestUnmarshalPanic(t *testing.T) {
2813 defer func() {
2814 if got := recover(); !reflect.DeepEqual(got, 0xdead) {
2815 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
2816 }
2817 }()
2818 Unmarshal([]byte("{}"), &unmarshalPanic{})
2819 t.Fatalf("Unmarshal should have panicked")
2820 }
2821
2822
2823
2824 func TestUnmarshalRecursivePointer(t *testing.T) {
2825 var v any
2826 v = &v
2827 data := []byte(`{"a": "b"}`)
2828
2829 if err := Unmarshal(data, v); err != nil {
2830 t.Fatalf("Unmarshal error: %v", err)
2831 }
2832 }
2833
2834 type textUnmarshalerString string
2835
2836 func (m *textUnmarshalerString) UnmarshalText(text []byte) error {
2837 *m = textUnmarshalerString(strings.ToLower(string(text)))
2838 return nil
2839 }
2840
2841
2842
2843 func TestUnmarshalMapWithTextUnmarshalerStringKey(t *testing.T) {
2844 var p map[textUnmarshalerString]string
2845 if err := Unmarshal([]byte(`{"FOO": "1"}`), &p); err != nil {
2846 t.Fatalf("Unmarshal error: %v", err)
2847 }
2848
2849 if _, ok := p["foo"]; !ok {
2850 t.Errorf(`key "foo" missing in map: %v`, p)
2851 }
2852 }
2853
2854 func TestUnmarshalRescanLiteralMangledUnquote(t *testing.T) {
2855
2856 var p map[textUnmarshalerString]string
2857 if err := Unmarshal([]byte(`{"开源":"12345开源"}`), &p); err != nil {
2858 t.Fatalf("Unmarshal error: %v", err)
2859 }
2860 if _, ok := p["开源"]; !ok {
2861 t.Errorf(`key "开源" missing in map: %v`, p)
2862 }
2863
2864
2865 type T struct {
2866 F1 string `json:"F1,string"`
2867 }
2868 wantT := T{"aaa\tbbb"}
2869
2870 b, err := Marshal(wantT)
2871 if err != nil {
2872 t.Fatalf("Marshal error: %v", err)
2873 }
2874 var gotT T
2875 if err := Unmarshal(b, &gotT); err != nil {
2876 t.Fatalf("Unmarshal error: %v", err)
2877 }
2878 if gotT != wantT {
2879 t.Errorf("Marshal/Unmarshal roundtrip:\n\tgot: %q\n\twant: %q", gotT, wantT)
2880 }
2881
2882
2883 input := map[textUnmarshalerString]string{"FOO": "", `"`: ""}
2884
2885 encoded, err := Marshal(input)
2886 if err != nil {
2887 t.Fatalf("Marshal error: %v", err)
2888 }
2889 var got map[textUnmarshalerString]string
2890 if err := Unmarshal(encoded, &got); err != nil {
2891 t.Fatalf("Unmarshal error: %v", err)
2892 }
2893 want := map[textUnmarshalerString]string{"foo": "", `"`: ""}
2894 if !maps.Equal(got, want) {
2895 t.Errorf("Marshal/Unmarshal roundtrip:\n\tgot: %q\n\twant: %q", gotT, wantT)
2896 }
2897 }
2898
2899 func TestUnmarshalMaxDepth(t *testing.T) {
2900 tests := []struct {
2901 CaseName
2902 data string
2903 errMaxDepth bool
2904 }{{
2905 CaseName: Name("ArrayUnderMaxNestingDepth"),
2906 data: `{"a":` + strings.Repeat(`[`, 10000-1) + strings.Repeat(`]`, 10000-1) + `}`,
2907 errMaxDepth: false,
2908 }, {
2909 CaseName: Name("ArrayOverMaxNestingDepth"),
2910 data: `{"a":` + strings.Repeat(`[`, 10000) + strings.Repeat(`]`, 10000) + `}`,
2911 errMaxDepth: true,
2912 }, {
2913 CaseName: Name("ArrayOverStackDepth"),
2914 data: `{"a":` + strings.Repeat(`[`, 3000000) + strings.Repeat(`]`, 3000000) + `}`,
2915 errMaxDepth: true,
2916 }, {
2917 CaseName: Name("ObjectUnderMaxNestingDepth"),
2918 data: `{"a":` + strings.Repeat(`{"a":`, 10000-1) + `0` + strings.Repeat(`}`, 10000-1) + `}`,
2919 errMaxDepth: false,
2920 }, {
2921 CaseName: Name("ObjectOverMaxNestingDepth"),
2922 data: `{"a":` + strings.Repeat(`{"a":`, 10000) + `0` + strings.Repeat(`}`, 10000) + `}`,
2923 errMaxDepth: true,
2924 }, {
2925 CaseName: Name("ObjectOverStackDepth"),
2926 data: `{"a":` + strings.Repeat(`{"a":`, 3000000) + `0` + strings.Repeat(`}`, 3000000) + `}`,
2927 errMaxDepth: true,
2928 }}
2929
2930 targets := []struct {
2931 CaseName
2932 newValue func() any
2933 }{{
2934 CaseName: Name("unstructured"),
2935 newValue: func() any {
2936 var v any
2937 return &v
2938 },
2939 }, {
2940 CaseName: Name("typed named field"),
2941 newValue: func() any {
2942 v := struct {
2943 A any `json:"a"`
2944 }{}
2945 return &v
2946 },
2947 }, {
2948 CaseName: Name("typed missing field"),
2949 newValue: func() any {
2950 v := struct {
2951 B any `json:"b"`
2952 }{}
2953 return &v
2954 },
2955 }, {
2956 CaseName: Name("custom unmarshaler"),
2957 newValue: func() any {
2958 v := unmarshaler{}
2959 return &v
2960 },
2961 }}
2962
2963 for _, tt := range tests {
2964 for _, target := range targets {
2965 t.Run(target.Name+"-"+tt.Name, func(t *testing.T) {
2966 err := Unmarshal([]byte(tt.data), target.newValue())
2967 if !tt.errMaxDepth {
2968 if err != nil {
2969 t.Errorf("%s: %s: Unmarshal error: %v", tt.Where, target.Where, err)
2970 }
2971 } else {
2972 if err == nil || !strings.Contains(err.Error(), "exceeded max depth") {
2973 t.Errorf("%s: %s: Unmarshal error:\n\tgot: %v\n\twant: exceeded max depth", tt.Where, target.Where, err)
2974 }
2975 }
2976 })
2977 }
2978 }
2979 }
2980
View as plain text