Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/arshal_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json
6
7 import (
8 "bytes"
9 "encoding"
10 "encoding/base32"
11 "encoding/base64"
12 "encoding/hex"
13 "errors"
14 "fmt"
15 "io"
16 "math"
17 "net"
18 "path"
19 "reflect"
20 "runtime"
21 "strconv"
22 "strings"
23 "testing"
24 "time"
25 )
26
27 type testName struct {
28 name string
29 where pc
30 }
31
32 func name(s string) (t testName) {
33 t.name = s
34 runtime.Callers(2, t.where[:])
35 return t
36 }
37
38 type pc [1]uintptr
39
40 func (pc pc) String() string {
41 frames := runtime.CallersFrames(pc[:])
42 frame, _ := frames.Next()
43 return fmt.Sprintf("%s:%d", path.Base(frame.File), frame.Line)
44 }
45
46 type (
47 jsonObject = map[string]any
48 jsonArray = []any
49
50 namedAny any
51 namedBool bool
52 namedString string
53 namedBytes []byte
54 namedInt64 int64
55 namedUint64 uint64
56 namedFloat64 float64
57 namedByte byte
58
59 recursiveMap map[string]recursiveMap
60 recursiveSlice []recursiveSlice
61 recursivePointer struct{ P *recursivePointer }
62
63 structEmpty struct{}
64 structConflicting struct {
65 A string `json:"conflict"`
66 B string `json:"conflict"`
67 }
68 structNoneExported struct {
69 unexported string
70 }
71 structUnexportedIgnored struct {
72 ignored string `json:"-"`
73 }
74 structMalformedTag struct {
75 Malformed string `json:"\""`
76 }
77 structUnexportedTag struct {
78 unexported string `json:"name"`
79 }
80 structUnexportedEmbedded struct {
81 namedString
82 }
83 structIgnoredUnexportedEmbedded struct {
84 namedString `json:"-"`
85 }
86 structWeirdNames struct {
87 Empty string `json:"''"`
88 Comma string `json:"','"`
89 Quote string `json:"'\"'"`
90 }
91 structNoCase struct {
92 AaA string `json:",nocase"`
93 AAa string `json:",nocase"`
94 AAA string
95 }
96 structScalars struct {
97 unexported bool
98 Ignored bool `json:"-"`
99
100 Bool bool
101 String string
102 Bytes []byte
103 Int int64
104 Uint uint64
105 Float float64
106 }
107 structSlices struct {
108 unexported bool
109 Ignored bool `json:"-"`
110
111 SliceBool []bool
112 SliceString []string
113 SliceBytes [][]byte
114 SliceInt []int64
115 SliceUint []uint64
116 SliceFloat []float64
117 }
118 structMaps struct {
119 unexported bool
120 Ignored bool `json:"-"`
121
122 MapBool map[string]bool
123 MapString map[string]string
124 MapBytes map[string][]byte
125 MapInt map[string]int64
126 MapUint map[string]uint64
127 MapFloat map[string]float64
128 }
129 structAll struct {
130 Bool bool
131 String string
132 Bytes []byte
133 Int int64
134 Uint uint64
135 Float float64
136 Map map[string]string
137 StructScalars structScalars
138 StructMaps structMaps
139 StructSlices structSlices
140 Slice []string
141 Array [1]string
142 Pointer *structAll
143 Interface any
144 }
145 structStringifiedAll struct {
146 Bool bool `json:",string"`
147 String string `json:",string"`
148 Bytes []byte `json:",string"`
149 Int int64 `json:",string"`
150 Uint uint64 `json:",string"`
151 Float float64 `json:",string"`
152 Map map[string]string `json:",string"`
153 StructScalars structScalars `json:",string"`
154 StructMaps structMaps `json:",string"`
155 StructSlices structSlices `json:",string"`
156 Slice []string `json:",string"`
157 Array [1]string `json:",string"`
158 Pointer *structStringifiedAll `json:",string"`
159 Interface any `json:",string"`
160 }
161 structOmitZeroAll struct {
162 Bool bool `json:",omitzero"`
163 String string `json:",omitzero"`
164 Bytes []byte `json:",omitzero"`
165 Int int64 `json:",omitzero"`
166 Uint uint64 `json:",omitzero"`
167 Float float64 `json:",omitzero"`
168 Map map[string]string `json:",omitzero"`
169 StructScalars structScalars `json:",omitzero"`
170 StructMaps structMaps `json:",omitzero"`
171 StructSlices structSlices `json:",omitzero"`
172 Slice []string `json:",omitzero"`
173 Array [1]string `json:",omitzero"`
174 Pointer *structOmitZeroAll `json:",omitzero"`
175 Interface any `json:",omitzero"`
176 }
177 structOmitZeroMethodAll struct {
178 ValueAlwaysZero valueAlwaysZero `json:",omitzero"`
179 ValueNeverZero valueNeverZero `json:",omitzero"`
180 PointerAlwaysZero pointerAlwaysZero `json:",omitzero"`
181 PointerNeverZero pointerNeverZero `json:",omitzero"`
182 PointerValueAlwaysZero *valueAlwaysZero `json:",omitzero"`
183 PointerValueNeverZero *valueNeverZero `json:",omitzero"`
184 PointerPointerAlwaysZero *pointerAlwaysZero `json:",omitzero"`
185 PointerPointerNeverZero *pointerNeverZero `json:",omitzero"`
186 PointerPointerValueAlwaysZero **valueAlwaysZero `json:",omitzero"`
187 PointerPointerValueNeverZero **valueNeverZero `json:",omitzero"`
188 PointerPointerPointerAlwaysZero **pointerAlwaysZero `json:",omitzero"`
189 PointerPointerPointerNeverZero **pointerNeverZero `json:",omitzero"`
190 }
191 structOmitZeroMethodInterfaceAll struct {
192 ValueAlwaysZero isZeroer `json:",omitzero"`
193 ValueNeverZero isZeroer `json:",omitzero"`
194 PointerValueAlwaysZero isZeroer `json:",omitzero"`
195 PointerValueNeverZero isZeroer `json:",omitzero"`
196 PointerPointerAlwaysZero isZeroer `json:",omitzero"`
197 PointerPointerNeverZero isZeroer `json:",omitzero"`
198 }
199 structOmitEmptyAll struct {
200 Bool bool `json:",omitempty"`
201 PointerBool *bool `json:",omitempty"`
202 String string `json:",omitempty"`
203 StringEmpty stringMarshalEmpty `json:",omitempty"`
204 StringNonEmpty stringMarshalNonEmpty `json:",omitempty"`
205 PointerString *string `json:",omitempty"`
206 PointerStringEmpty *stringMarshalEmpty `json:",omitempty"`
207 PointerStringNonEmpty *stringMarshalNonEmpty `json:",omitempty"`
208 Bytes []byte `json:",omitempty"`
209 BytesEmpty bytesMarshalEmpty `json:",omitempty"`
210 BytesNonEmpty bytesMarshalNonEmpty `json:",omitempty"`
211 PointerBytes *[]byte `json:",omitempty"`
212 PointerBytesEmpty *bytesMarshalEmpty `json:",omitempty"`
213 PointerBytesNonEmpty *bytesMarshalNonEmpty `json:",omitempty"`
214 Float float64 `json:",omitempty"`
215 PointerFloat *float64 `json:",omitempty"`
216 Map map[string]string `json:",omitempty"`
217 MapEmpty mapMarshalEmpty `json:",omitempty"`
218 MapNonEmpty mapMarshalNonEmpty `json:",omitempty"`
219 PointerMap *map[string]string `json:",omitempty"`
220 PointerMapEmpty *mapMarshalEmpty `json:",omitempty"`
221 PointerMapNonEmpty *mapMarshalNonEmpty `json:",omitempty"`
222 Slice []string `json:",omitempty"`
223 SliceEmpty sliceMarshalEmpty `json:",omitempty"`
224 SliceNonEmpty sliceMarshalNonEmpty `json:",omitempty"`
225 PointerSlice *[]string `json:",omitempty"`
226 PointerSliceEmpty *sliceMarshalEmpty `json:",omitempty"`
227 PointerSliceNonEmpty *sliceMarshalNonEmpty `json:",omitempty"`
228 Pointer *structOmitZeroEmptyAll `json:",omitempty"`
229 Interface any `json:",omitempty"`
230 }
231 structOmitZeroEmptyAll struct {
232 Bool bool `json:",omitzero,omitempty"`
233 String string `json:",omitzero,omitempty"`
234 Bytes []byte `json:",omitzero,omitempty"`
235 Int int64 `json:",omitzero,omitempty"`
236 Uint uint64 `json:",omitzero,omitempty"`
237 Float float64 `json:",omitzero,omitempty"`
238 Map map[string]string `json:",omitzero,omitempty"`
239 Slice []string `json:",omitzero,omitempty"`
240 Array [1]string `json:",omitzero,omitempty"`
241 Pointer *structOmitZeroEmptyAll `json:",omitzero,omitempty"`
242 Interface any `json:",omitzero,omitempty"`
243 }
244 structFormatBytes struct {
245 Base16 []byte `json:",format:base16"`
246 Base32 []byte `json:",format:base32"`
247 Base32Hex []byte `json:",format:base32hex"`
248 Base64 []byte `json:",format:base64"`
249 Base64URL []byte `json:",format:base64url"`
250 Array []byte `json:",format:array"`
251 }
252 structFormatFloats struct {
253 NonFinite float64 `json:",format:nonfinite"`
254 PointerNonFinite *float64 `json:",format:nonfinite"`
255 }
256 structFormatMaps struct {
257 EmitNull map[string]string `json:",format:emitnull"`
258 PointerEmitNull *map[string]string `json:",format:emitnull"`
259 }
260 structFormatSlices struct {
261 EmitNull []string `json:",format:emitnull"`
262 PointerEmitNull *[]string `json:",format:emitnull"`
263 }
264 structFormatInvalid struct {
265 Bool bool `json:",omitzero,format:invalid"`
266 String string `json:",omitzero,format:invalid"`
267 Bytes []byte `json:",omitzero,format:invalid"`
268 Int int64 `json:",omitzero,format:invalid"`
269 Uint uint64 `json:",omitzero,format:invalid"`
270 Float float64 `json:",omitzero,format:invalid"`
271 Map map[string]string `json:",omitzero,format:invalid"`
272 Struct structAll `json:",omitzero,format:invalid"`
273 Slice []string `json:",omitzero,format:invalid"`
274 Array [1]string `json:",omitzero,format:invalid"`
275 Interface any `json:",omitzero,format:invalid"`
276 }
277 structTimeFormat struct {
278 T1 time.Time
279 T2 time.Time `json:",format:ANSIC"`
280 T3 time.Time `json:",format:UnixDate"`
281 T4 time.Time `json:",format:RubyDate"`
282 T5 time.Time `json:",format:RFC822"`
283 T6 time.Time `json:",format:RFC822Z"`
284 T7 time.Time `json:",format:RFC850"`
285 T8 time.Time `json:",format:RFC1123"`
286 T9 time.Time `json:",format:RFC1123Z"`
287 T10 time.Time `json:",format:RFC3339"`
288 T11 time.Time `json:",format:RFC3339Nano"`
289 T12 time.Time `json:",format:Kitchen"`
290 T13 time.Time `json:",format:Stamp"`
291 T14 time.Time `json:",format:StampMilli"`
292 T15 time.Time `json:",format:StampMicro"`
293 T16 time.Time `json:",format:StampNano"`
294 T17 time.Time `json:",format:'2006-01-02'"`
295 T18 time.Time `json:",format:'\"weird\"2006'"`
296 }
297 structInlined struct {
298 X structInlinedL1 `json:",inline"`
299 *StructEmbed2 // implicit inline
300 }
301 structInlinedL1 struct {
302 X *structInlinedL2 `json:",inline"`
303 StructEmbed1 `json:",inline"`
304 }
305 structInlinedL2 struct{ A, B, C string }
306 StructEmbed1 struct{ C, D, E string }
307 StructEmbed2 struct{ E, F, G string }
308 structUnknownRawValue struct {
309 A int `json:",omitzero"`
310 X RawValue `json:",unknown"`
311 B int `json:",omitzero"`
312 }
313 structInlineRawValue struct {
314 A int `json:",omitzero"`
315 X RawValue `json:",inline"`
316 B int `json:",omitzero"`
317 }
318 structInlinePointerRawValue struct {
319 A int `json:",omitzero"`
320 X *RawValue `json:",inline"`
321 B int `json:",omitzero"`
322 }
323 structInlinePointerInlineRawValue struct {
324 X *struct {
325 A int
326 X RawValue `json:",inline"`
327 } `json:",inline"`
328 }
329 structInlineInlinePointerRawValue struct {
330 X struct {
331 X *RawValue `json:",inline"`
332 } `json:",inline"`
333 }
334 structInlineMapStringAny struct {
335 A int `json:",omitzero"`
336 X jsonObject `json:",inline"`
337 B int `json:",omitzero"`
338 }
339 structInlinePointerMapStringAny struct {
340 A int `json:",omitzero"`
341 X *jsonObject `json:",inline"`
342 B int `json:",omitzero"`
343 }
344 structInlinePointerInlineMapStringAny struct {
345 X *struct {
346 A int
347 X jsonObject `json:",inline"`
348 } `json:",inline"`
349 }
350 structInlineInlinePointerMapStringAny struct {
351 X struct {
352 X *jsonObject `json:",inline"`
353 } `json:",inline"`
354 }
355 structInlineMapStringInt struct {
356 X map[string]int `json:",inline"`
357 }
358 structNoCaseInlineRawValue struct {
359 AAA string `json:",omitempty"`
360 AaA string `json:",omitempty,nocase"`
361 AAa string `json:",omitempty,nocase"`
362 Aaa string `json:",omitempty"`
363 X RawValue `json:",inline"`
364 }
365 structNoCaseInlineMapStringAny struct {
366 AAA string `json:",omitempty"`
367 AaA string `json:",omitempty,nocase"`
368 AAa string `json:",omitempty,nocase"`
369 Aaa string `json:",omitempty"`
370 X jsonObject `json:",inline"`
371 }
372
373 allMethods struct {
374 method string // the method that was called
375 value []byte // the raw value to provide or store
376 }
377 allMethodsExceptJSONv2 struct {
378 allMethods
379 MarshalNextJSON struct{} // cancel out MarshalNextJSON method with collision
380 UnmarshalNextJSON struct{} // cancel out UnmarshalNextJSON method with collision
381 }
382 allMethodsExceptJSONv1 struct {
383 allMethods
384 MarshalJSON struct{} // cancel out MarshalJSON method with collision
385 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
386 }
387 allMethodsExceptText struct {
388 allMethods
389 MarshalText struct{} // cancel out MarshalText method with collision
390 UnmarshalText struct{} // cancel out UnmarshalText method with collision
391 }
392 onlyMethodJSONv2 struct {
393 allMethods
394 MarshalJSON struct{} // cancel out MarshalJSON method with collision
395 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
396 MarshalText struct{} // cancel out MarshalText method with collision
397 UnmarshalText struct{} // cancel out UnmarshalText method with collision
398 }
399 onlyMethodJSONv1 struct {
400 allMethods
401 MarshalNextJSON struct{} // cancel out MarshalNextJSON method with collision
402 UnmarshalNextJSON struct{} // cancel out UnmarshalNextJSON method with collision
403 MarshalText struct{} // cancel out MarshalText method with collision
404 UnmarshalText struct{} // cancel out UnmarshalText method with collision
405 }
406 onlyMethodText struct {
407 allMethods
408 MarshalNextJSON struct{} // cancel out MarshalNextJSON method with collision
409 UnmarshalNextJSON struct{} // cancel out UnmarshalNextJSON method with collision
410 MarshalJSON struct{} // cancel out MarshalJSON method with collision
411 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
412 }
413
414 structMethodJSONv2 struct{ value string }
415 structMethodJSONv1 struct{ value string }
416 structMethodText struct{ value string }
417
418 marshalJSONv2Func func(MarshalOptions, *Encoder) error
419 marshalJSONv1Func func() ([]byte, error)
420 marshalTextFunc func() ([]byte, error)
421 unmarshalJSONv2Func func(UnmarshalOptions, *Decoder) error
422 unmarshalJSONv1Func func([]byte) error
423 unmarshalTextFunc func([]byte) error
424
425 nocaseString string
426
427 stringMarshalEmpty string
428 stringMarshalNonEmpty string
429 bytesMarshalEmpty []byte
430 bytesMarshalNonEmpty []byte
431 mapMarshalEmpty map[string]string
432 mapMarshalNonEmpty map[string]string
433 sliceMarshalEmpty []string
434 sliceMarshalNonEmpty []string
435
436 valueAlwaysZero string
437 valueNeverZero string
438 pointerAlwaysZero string
439 pointerNeverZero string
440
441 valueStringer struct{}
442 pointerStringer struct{}
443
444 cyclicA struct {
445 B1 cyclicB `json:",inline"`
446 B2 cyclicB `json:",inline"`
447 }
448 cyclicB struct {
449 F int
450 A *cyclicA `json:",inline"`
451 }
452 )
453
454 func (p *allMethods) MarshalNextJSON(mo MarshalOptions, enc *Encoder) error {
455 if got, want := "MarshalNextJSON", p.method; got != want {
456 return fmt.Errorf("called wrong method: got %v, want %v", got, want)
457 }
458 return enc.WriteValue(p.value)
459 }
460 func (p *allMethods) MarshalJSON() ([]byte, error) {
461 if got, want := "MarshalJSON", p.method; got != want {
462 return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
463 }
464 return p.value, nil
465 }
466 func (p *allMethods) MarshalText() ([]byte, error) {
467 if got, want := "MarshalText", p.method; got != want {
468 return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
469 }
470 return p.value, nil
471 }
472
473 func (p *allMethods) UnmarshalNextJSON(uo UnmarshalOptions, dec *Decoder) error {
474 p.method = "UnmarshalNextJSON"
475 val, err := dec.ReadValue()
476 p.value = val
477 return err
478 }
479 func (p *allMethods) UnmarshalJSON(val []byte) error {
480 p.method = "UnmarshalJSON"
481 p.value = val
482 return nil
483 }
484 func (p *allMethods) UnmarshalText(val []byte) error {
485 p.method = "UnmarshalText"
486 p.value = val
487 return nil
488 }
489
490 func (s structMethodJSONv2) MarshalNextJSON(mo MarshalOptions, enc *Encoder) error {
491 return enc.WriteToken(String(s.value))
492 }
493 func (s *structMethodJSONv2) UnmarshalNextJSON(uo UnmarshalOptions, dec *Decoder) error {
494 tok, err := dec.ReadToken()
495 if err != nil {
496 return err
497 }
498 if k := tok.Kind(); k != '"' {
499 return &SemanticError{action: "unmarshal", JSONKind: k, GoType: structMethodJSONv2Type}
500 }
501 s.value = tok.String()
502 return nil
503 }
504
505 func (s structMethodJSONv1) MarshalJSON() ([]byte, error) {
506 return appendString(nil, s.value, false, nil)
507 }
508 func (s *structMethodJSONv1) UnmarshalJSON(b []byte) error {
509 if k := RawValue(b).Kind(); k != '"' {
510 return &SemanticError{action: "unmarshal", JSONKind: k, GoType: structMethodJSONv1Type}
511 }
512 b, _ = unescapeString(nil, b)
513 s.value = string(b)
514 return nil
515 }
516
517 func (s structMethodText) MarshalText() ([]byte, error) {
518 return []byte(s.value), nil
519 }
520 func (s *structMethodText) UnmarshalText(b []byte) error {
521 s.value = string(b)
522 return nil
523 }
524
525 func (f marshalJSONv2Func) MarshalNextJSON(mo MarshalOptions, enc *Encoder) error {
526 return f(mo, enc)
527 }
528 func (f marshalJSONv1Func) MarshalJSON() ([]byte, error) {
529 return f()
530 }
531 func (f marshalTextFunc) MarshalText() ([]byte, error) {
532 return f()
533 }
534 func (f unmarshalJSONv2Func) UnmarshalNextJSON(uo UnmarshalOptions, dec *Decoder) error {
535 return f(uo, dec)
536 }
537 func (f unmarshalJSONv1Func) UnmarshalJSON(b []byte) error {
538 return f(b)
539 }
540 func (f unmarshalTextFunc) UnmarshalText(b []byte) error {
541 return f(b)
542 }
543
544 func (k nocaseString) MarshalText() ([]byte, error) {
545 return []byte(strings.ToLower(string(k))), nil
546 }
547 func (k *nocaseString) UnmarshalText(b []byte) error {
548 *k = nocaseString(strings.ToLower(string(b)))
549 return nil
550 }
551
552 func (stringMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`""`), nil }
553 func (stringMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`"value"`), nil }
554 func (bytesMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
555 func (bytesMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
556 func (mapMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`{}`), nil }
557 func (mapMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`{"key":"value"}`), nil }
558 func (sliceMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
559 func (sliceMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
560
561 func (valueAlwaysZero) IsZero() bool { return true }
562 func (valueNeverZero) IsZero() bool { return false }
563 func (*pointerAlwaysZero) IsZero() bool { return true }
564 func (*pointerNeverZero) IsZero() bool { return false }
565
566 func (valueStringer) String() string { return "" }
567 func (*pointerStringer) String() string { return "" }
568
569 var (
570 namedBoolType = reflect.TypeOf((*namedBool)(nil)).Elem()
571 intType = reflect.TypeOf((*int)(nil)).Elem()
572 int8Type = reflect.TypeOf((*int8)(nil)).Elem()
573 int16Type = reflect.TypeOf((*int16)(nil)).Elem()
574 int32Type = reflect.TypeOf((*int32)(nil)).Elem()
575 int64Type = reflect.TypeOf((*int64)(nil)).Elem()
576 uintType = reflect.TypeOf((*uint)(nil)).Elem()
577 uint8Type = reflect.TypeOf((*uint8)(nil)).Elem()
578 uint16Type = reflect.TypeOf((*uint16)(nil)).Elem()
579 uint32Type = reflect.TypeOf((*uint32)(nil)).Elem()
580 uint64Type = reflect.TypeOf((*uint64)(nil)).Elem()
581 sliceStringType = reflect.TypeOf((*[]string)(nil)).Elem()
582 array1StringType = reflect.TypeOf((*[1]string)(nil)).Elem()
583 array0ByteType = reflect.TypeOf((*[0]byte)(nil)).Elem()
584 array1ByteType = reflect.TypeOf((*[1]byte)(nil)).Elem()
585 array2ByteType = reflect.TypeOf((*[2]byte)(nil)).Elem()
586 array3ByteType = reflect.TypeOf((*[3]byte)(nil)).Elem()
587 array4ByteType = reflect.TypeOf((*[4]byte)(nil)).Elem()
588 mapStringStringType = reflect.TypeOf((*map[string]string)(nil)).Elem()
589 structAllType = reflect.TypeOf((*structAll)(nil)).Elem()
590 structConflictingType = reflect.TypeOf((*structConflicting)(nil)).Elem()
591 structNoneExportedType = reflect.TypeOf((*structNoneExported)(nil)).Elem()
592 structMalformedTagType = reflect.TypeOf((*structMalformedTag)(nil)).Elem()
593 structUnexportedTagType = reflect.TypeOf((*structUnexportedTag)(nil)).Elem()
594 structUnexportedEmbeddedType = reflect.TypeOf((*structUnexportedEmbedded)(nil)).Elem()
595 structUnknownRawValueType = reflect.TypeOf((*structUnknownRawValue)(nil)).Elem()
596 allMethodsType = reflect.TypeOf((*allMethods)(nil)).Elem()
597 allMethodsExceptJSONv2Type = reflect.TypeOf((*allMethodsExceptJSONv2)(nil)).Elem()
598 allMethodsExceptJSONv1Type = reflect.TypeOf((*allMethodsExceptJSONv1)(nil)).Elem()
599 allMethodsExceptTextType = reflect.TypeOf((*allMethodsExceptText)(nil)).Elem()
600 onlyMethodJSONv2Type = reflect.TypeOf((*onlyMethodJSONv2)(nil)).Elem()
601 onlyMethodJSONv1Type = reflect.TypeOf((*onlyMethodJSONv1)(nil)).Elem()
602 onlyMethodTextType = reflect.TypeOf((*onlyMethodText)(nil)).Elem()
603 structMethodJSONv2Type = reflect.TypeOf((*structMethodJSONv2)(nil)).Elem()
604 structMethodJSONv1Type = reflect.TypeOf((*structMethodJSONv1)(nil)).Elem()
605 structMethodTextType = reflect.TypeOf((*structMethodText)(nil)).Elem()
606 marshalJSONv2FuncType = reflect.TypeOf((*marshalJSONv2Func)(nil)).Elem()
607 marshalJSONv1FuncType = reflect.TypeOf((*marshalJSONv1Func)(nil)).Elem()
608 marshalTextFuncType = reflect.TypeOf((*marshalTextFunc)(nil)).Elem()
609 unmarshalJSONv2FuncType = reflect.TypeOf((*unmarshalJSONv2Func)(nil)).Elem()
610 unmarshalJSONv1FuncType = reflect.TypeOf((*unmarshalJSONv1Func)(nil)).Elem()
611 unmarshalTextFuncType = reflect.TypeOf((*unmarshalTextFunc)(nil)).Elem()
612 nocaseStringType = reflect.TypeOf((*nocaseString)(nil)).Elem()
613 ioReaderType = reflect.TypeOf((*io.Reader)(nil)).Elem()
614 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
615 chanStringType = reflect.TypeOf((*chan string)(nil)).Elem()
616 )
617
618 func addr[T any](v T) *T {
619 return &v
620 }
621
622 func mustParseTime(layout, value string) time.Time {
623 t, err := time.Parse(layout, value)
624 if err != nil {
625 panic(err)
626 }
627 return t
628 }
629
630 func TestMarshal(t *testing.T) {
631 tests := []struct {
632 name testName
633 mopts MarshalOptions
634 eopts EncodeOptions
635 in any
636 want string
637 wantErr error
638
639 canonicalize bool // canonicalize the output before comparing?
640 useWriter bool // call MarshalFull instead of Marshal
641 }{{
642 name: name("Nil"),
643 in: nil,
644 want: `null`,
645 }, {
646 name: name("Bools"),
647 in: []bool{false, true},
648 want: `[false,true]`,
649 }, {
650 name: name("Bools/Named"),
651 in: []namedBool{false, true},
652 want: `[false,true]`,
653 }, {
654 name: name("Bools/NotStringified"),
655 mopts: MarshalOptions{StringifyNumbers: true},
656 in: []bool{false, true},
657 want: `[false,true]`,
658 }, {
659 name: name("Bools/IgnoreInvalidFormat"),
660 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
661 in: true,
662 want: `true`,
663 }, {
664 name: name("Strings"),
665 in: []string{"", "hello", "世界"},
666 want: `["","hello","世界"]`,
667 }, {
668 name: name("Strings/Named"),
669 in: []namedString{"", "hello", "世界"},
670 want: `["","hello","世界"]`,
671 }, {
672 name: name("Strings/IgnoreInvalidFormat"),
673 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
674 in: "string",
675 want: `"string"`,
676 }, {
677 name: name("Bytes"),
678 in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
679 want: `["","","AQ==","AQI=","AQID"]`,
680 }, {
681 name: name("Bytes/Large"),
682 in: []byte("the quick brown fox jumped over the lazy dog and ate the homework that I spent so much time on."),
683 want: `"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgYW5kIGF0ZSB0aGUgaG9tZXdvcmsgdGhhdCBJIHNwZW50IHNvIG11Y2ggdGltZSBvbi4="`,
684 }, {
685 name: name("Bytes/Named"),
686 in: []namedBytes{nil, {}, {1}, {1, 2}, {1, 2, 3}},
687 want: `["","","AQ==","AQI=","AQID"]`,
688 }, {
689 name: name("Bytes/NotStringified"),
690 mopts: MarshalOptions{StringifyNumbers: true},
691 in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
692 want: `["","","AQ==","AQI=","AQID"]`,
693 }, {
694 // NOTE: []namedByte is not assignable to []byte,
695 // so the following should be treated as a slice of uints.
696 name: name("Bytes/Invariant"),
697 in: [][]namedByte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
698 want: `[[],[],[1],[1,2],[1,2,3]]`,
699 }, {
700 // NOTE: This differs in behavior from v1,
701 // but keeps the representation of slices and arrays more consistent.
702 name: name("Bytes/ByteArray"),
703 in: [5]byte{'h', 'e', 'l', 'l', 'o'},
704 want: `"aGVsbG8="`,
705 }, {
706 // NOTE: []namedByte is not assignable to []byte,
707 // so the following should be treated as an array of uints.
708 name: name("Bytes/NamedByteArray"),
709 in: [5]namedByte{'h', 'e', 'l', 'l', 'o'},
710 want: `[104,101,108,108,111]`,
711 }, {
712 name: name("Bytes/IgnoreInvalidFormat"),
713 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
714 in: []byte("hello"),
715 want: `"aGVsbG8="`,
716 }, {
717 name: name("Ints"),
718 in: []any{
719 int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
720 },
721 want: `[0,-128,-32768,-2147483648,-9223372036854775808,-6464]`,
722 }, {
723 name: name("Ints/Stringified"),
724 mopts: MarshalOptions{StringifyNumbers: true},
725 in: []any{
726 int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
727 },
728 want: `["0","-128","-32768","-2147483648","-9223372036854775808","-6464"]`,
729 }, {
730 name: name("Ints/IgnoreInvalidFormat"),
731 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
732 in: int(0),
733 want: `0`,
734 }, {
735 name: name("Uints"),
736 in: []any{
737 uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464),
738 },
739 want: `[0,255,65535,4294967295,18446744073709551615,6464]`,
740 }, {
741 name: name("Uints/Stringified"),
742 mopts: MarshalOptions{StringifyNumbers: true},
743 in: []any{
744 uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464),
745 },
746 want: `["0","255","65535","4294967295","18446744073709551615","6464"]`,
747 }, {
748 name: name("Uints/IgnoreInvalidFormat"),
749 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
750 in: uint(0),
751 want: `0`,
752 }, {
753 name: name("Floats"),
754 in: []any{
755 float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
756 },
757 want: `[3.4028235e+38,1.7976931348623157e+308,64.64]`,
758 }, {
759 name: name("Floats/Stringified"),
760 mopts: MarshalOptions{StringifyNumbers: true},
761 in: []any{
762 float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
763 },
764 want: `["3.4028235e+38","1.7976931348623157e+308","64.64"]`,
765 }, {
766 name: name("Floats/Invalid/NaN"),
767 mopts: MarshalOptions{StringifyNumbers: true},
768 in: math.NaN(),
769 wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.NaN())},
770 }, {
771 name: name("Floats/Invalid/PositiveInfinity"),
772 in: math.Inf(+1),
773 wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.Inf(+1))},
774 }, {
775 name: name("Floats/Invalid/NegativeInfinity"),
776 in: math.Inf(-1),
777 wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: fmt.Errorf("invalid value: %v", math.Inf(-1))},
778 }, {
779 name: name("Floats/IgnoreInvalidFormat"),
780 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
781 in: float64(0),
782 want: `0`,
783 }, {
784 name: name("Maps/InvalidKey/Bool"),
785 in: map[bool]string{false: "value"},
786 want: `{`,
787 wantErr: errMissingName,
788 }, {
789 name: name("Maps/InvalidKey/NamedBool"),
790 in: map[namedBool]string{false: "value"},
791 want: `{`,
792 wantErr: errMissingName,
793 }, {
794 name: name("Maps/InvalidKey/Array"),
795 in: map[[1]string]string{{"key"}: "value"},
796 want: `{`,
797 wantErr: errMissingName,
798 }, {
799 name: name("Maps/InvalidKey/Channel"),
800 in: map[chan string]string{make(chan string): "value"},
801 want: `{`,
802 wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
803 }, {
804 name: name("Maps/ValidKey/Int"),
805 in: map[int64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
806 canonicalize: true,
807 want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
808 }, {
809 name: name("Maps/ValidKey/NamedInt"),
810 in: map[namedInt64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
811 canonicalize: true,
812 want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
813 }, {
814 name: name("Maps/ValidKey/Uint"),
815 in: map[uint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
816 canonicalize: true,
817 want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
818 }, {
819 name: name("Maps/ValidKey/NamedUint"),
820 in: map[namedUint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
821 canonicalize: true,
822 want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
823 }, {
824 name: name("Maps/ValidKey/Float"),
825 in: map[float64]string{3.14159: "value"},
826 want: `{"3.14159":"value"}`,
827 }, {
828 name: name("Maps/InvalidKey/Float/NaN"),
829 in: map[float64]string{math.NaN(): "NaN", math.NaN(): "NaN"},
830 want: `{`,
831 wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: errors.New("invalid value: NaN")},
832 }, {
833 name: name("Maps/ValidKey/Interface"),
834 in: map[any]any{
835 "key": "key",
836 namedInt64(-64): int32(-32),
837 namedUint64(+64): uint32(+32),
838 namedFloat64(64.64): float32(32.32),
839 },
840 canonicalize: true,
841 want: `{"-64":-32,"64":32,"64.64":32.32,"key":"key"}`,
842 }, {
843 name: name("Maps/DuplicateName/String/AllowInvalidUTF8+AllowDuplicateNames"),
844 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true},
845 in: map[string]string{"\x80": "", "\x81": ""},
846 want: `{"�":"","�":""}`,
847 }, {
848 name: name("Maps/DuplicateName/String/AllowInvalidUTF8"),
849 eopts: EncodeOptions{AllowInvalidUTF8: true},
850 in: map[string]string{"\x80": "", "\x81": ""},
851 want: `{"�":""`,
852 wantErr: &SyntacticError{str: `duplicate name "�" in object`},
853 }, {
854 name: name("Maps/DuplicateName/NoCaseString/AllowDuplicateNames"),
855 eopts: EncodeOptions{AllowDuplicateNames: true},
856 in: map[nocaseString]string{"hello": "", "HELLO": ""},
857 want: `{"hello":"","hello":""}`,
858 }, {
859 name: name("Maps/DuplicateName/NoCaseString"),
860 in: map[nocaseString]string{"hello": "", "HELLO": ""},
861 want: `{"hello":""`,
862 wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: reflect.TypeOf(nocaseString("")), Err: &SyntacticError{str: `duplicate name "hello" in object`}},
863 }, {
864 name: name("Maps/InvalidValue/Channel"),
865 in: map[string]chan string{
866 "key": nil,
867 },
868 want: `{"key"`,
869 wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
870 }, {
871 name: name("Maps/String/Deterministic"),
872 mopts: MarshalOptions{Deterministic: true},
873 in: map[string]int{"a": 0, "b": 1, "c": 2},
874 want: `{"a":0,"b":1,"c":2}`,
875 }, {
876 name: name("Maps/String/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
877 mopts: MarshalOptions{Deterministic: true},
878 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: false},
879 in: map[string]int{"\xff": 0, "\xfe": 1},
880 want: `{"�":1`,
881 wantErr: &SyntacticError{str: `duplicate name "�" in object`},
882 }, {
883 name: name("Maps/String/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
884 mopts: MarshalOptions{Deterministic: true},
885 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true},
886 in: map[string]int{"\xff": 0, "\xfe": 1},
887 want: `{"�":1,"�":0}`,
888 }, {
889 name: name("Maps/String/Deterministic+MarshalFuncs"),
890 mopts: MarshalOptions{
891 Deterministic: true,
892 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v string) error {
893 if p := enc.StackPointer(); p != "/X" {
894 return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
895 }
896 switch v {
897 case "a":
898 return enc.WriteToken(String("b"))
899 case "b":
900 return enc.WriteToken(String("a"))
901 default:
902 return fmt.Errorf("invalid value: %q", v)
903 }
904 }),
905 },
906 in: map[namedString]map[string]int{"X": {"a": -1, "b": 1}},
907 want: `{"X":{"a":1,"b":-1}}`,
908 }, {
909 name: name("Maps/String/Deterministic+MarshalFuncs+RejectDuplicateNames"),
910 mopts: MarshalOptions{
911 Deterministic: true,
912 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v string) error {
913 if p := enc.StackPointer(); p != "/X" {
914 return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
915 }
916 switch v {
917 case "a", "b":
918 return enc.WriteToken(String("x"))
919 default:
920 return fmt.Errorf("invalid value: %q", v)
921 }
922 }),
923 },
924 eopts: EncodeOptions{AllowDuplicateNames: false},
925 in: map[namedString]map[string]int{"X": {"a": 1, "b": 1}},
926 want: `{"X":{"x":1`,
927 wantErr: &SyntacticError{str: `duplicate name "x" in object`},
928 }, {
929 name: name("Maps/String/Deterministic+MarshalFuncs+AllowDuplicateNames"),
930 mopts: MarshalOptions{
931 Deterministic: true,
932 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v string) error {
933 if p := enc.StackPointer(); p != "/0" {
934 return fmt.Errorf("invalid stack pointer: got %s, want /0", p)
935 }
936 switch v {
937 case "a", "b":
938 return enc.WriteToken(String("x"))
939 default:
940 return fmt.Errorf("invalid value: %q", v)
941 }
942 }),
943 },
944 eopts: EncodeOptions{AllowDuplicateNames: true},
945 in: map[namedString]map[string]int{"X": {"a": 1, "b": 1}},
946 // NOTE: Since the names are identical, the exact values may be
947 // non-deterministic since sort cannot distinguish between members.
948 want: `{"X":{"x":1,"x":1}}`,
949 }, {
950 name: name("Maps/RecursiveMap"),
951 in: recursiveMap{
952 "fizz": {
953 "foo": {},
954 "bar": nil,
955 },
956 "buzz": nil,
957 },
958 canonicalize: true,
959 want: `{"buzz":{},"fizz":{"bar":{},"foo":{}}}`,
960 }, {
961 name: name("Maps/CyclicMap"),
962 in: func() recursiveMap {
963 m := recursiveMap{"k": nil}
964 m["k"] = m
965 return m
966 }(),
967 want: strings.Repeat(`{"k":`, startDetectingCyclesAfter) + `{"k"`,
968 wantErr: &SemanticError{action: "marshal", GoType: reflect.TypeOf(recursiveMap{}), Err: errors.New("encountered a cycle")},
969 }, {
970 name: name("Maps/IgnoreInvalidFormat"),
971 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
972 in: map[string]string{},
973 want: `{}`,
974 }, {
975 name: name("Structs/Empty"),
976 in: structEmpty{},
977 want: `{}`,
978 }, {
979 name: name("Structs/UnexportedIgnored"),
980 in: structUnexportedIgnored{ignored: "ignored"},
981 want: `{}`,
982 }, {
983 name: name("Structs/IgnoredUnexportedEmbedded"),
984 in: structIgnoredUnexportedEmbedded{namedString: "ignored"},
985 want: `{}`,
986 }, {
987 name: name("Structs/WeirdNames"),
988 in: structWeirdNames{Empty: "empty", Comma: "comma", Quote: "quote"},
989 want: `{"":"empty",",":"comma","\"":"quote"}`,
990 }, {
991 name: name("Structs/EscapedNames"),
992 eopts: EncodeOptions{EscapeRune: func(rune) bool { return true }},
993 in: structWeirdNames{Empty: "empty", Comma: "comma", Quote: "quote"},
994 want: `{"":"\u0065\u006d\u0070\u0074\u0079","\u002c":"\u0063\u006f\u006d\u006d\u0061","\u0022":"\u0071\u0075\u006f\u0074\u0065"}`,
995 }, {
996 name: name("Structs/NoCase"),
997 in: structNoCase{AaA: "AaA", AAa: "AAa", AAA: "AAA"},
998 want: `{"AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
999 }, {
1000 name: name("Structs/Normal"),
1001 eopts: EncodeOptions{Indent: "\t"},
1002 in: structAll{
1003 Bool: true,
1004 String: "hello",
1005 Bytes: []byte{1, 2, 3},
1006 Int: -64,
1007 Uint: +64,
1008 Float: 3.14159,
1009 Map: map[string]string{"key": "value"},
1010 StructScalars: structScalars{
1011 Bool: true,
1012 String: "hello",
1013 Bytes: []byte{1, 2, 3},
1014 Int: -64,
1015 Uint: +64,
1016 Float: 3.14159,
1017 },
1018 StructMaps: structMaps{
1019 MapBool: map[string]bool{"": true},
1020 MapString: map[string]string{"": "hello"},
1021 MapBytes: map[string][]byte{"": {1, 2, 3}},
1022 MapInt: map[string]int64{"": -64},
1023 MapUint: map[string]uint64{"": +64},
1024 MapFloat: map[string]float64{"": 3.14159},
1025 },
1026 StructSlices: structSlices{
1027 SliceBool: []bool{true},
1028 SliceString: []string{"hello"},
1029 SliceBytes: [][]byte{{1, 2, 3}},
1030 SliceInt: []int64{-64},
1031 SliceUint: []uint64{+64},
1032 SliceFloat: []float64{3.14159},
1033 },
1034 Slice: []string{"fizz", "buzz"},
1035 Array: [1]string{"goodbye"},
1036 Pointer: new(structAll),
1037 Interface: (*structAll)(nil),
1038 },
1039 want: `{
1040 "Bool": true,
1041 "String": "hello",
1042 "Bytes": "AQID",
1043 "Int": -64,
1044 "Uint": 64,
1045 "Float": 3.14159,
1046 "Map": {
1047 "key": "value"
1048 },
1049 "StructScalars": {
1050 "Bool": true,
1051 "String": "hello",
1052 "Bytes": "AQID",
1053 "Int": -64,
1054 "Uint": 64,
1055 "Float": 3.14159
1056 },
1057 "StructMaps": {
1058 "MapBool": {
1059 "": true
1060 },
1061 "MapString": {
1062 "": "hello"
1063 },
1064 "MapBytes": {
1065 "": "AQID"
1066 },
1067 "MapInt": {
1068 "": -64
1069 },
1070 "MapUint": {
1071 "": 64
1072 },
1073 "MapFloat": {
1074 "": 3.14159
1075 }
1076 },
1077 "StructSlices": {
1078 "SliceBool": [
1079 true
1080 ],
1081 "SliceString": [
1082 "hello"
1083 ],
1084 "SliceBytes": [
1085 "AQID"
1086 ],
1087 "SliceInt": [
1088 -64
1089 ],
1090 "SliceUint": [
1091 64
1092 ],
1093 "SliceFloat": [
1094 3.14159
1095 ]
1096 },
1097 "Slice": [
1098 "fizz",
1099 "buzz"
1100 ],
1101 "Array": [
1102 "goodbye"
1103 ],
1104 "Pointer": {
1105 "Bool": false,
1106 "String": "",
1107 "Bytes": "",
1108 "Int": 0,
1109 "Uint": 0,
1110 "Float": 0,
1111 "Map": {},
1112 "StructScalars": {
1113 "Bool": false,
1114 "String": "",
1115 "Bytes": "",
1116 "Int": 0,
1117 "Uint": 0,
1118 "Float": 0
1119 },
1120 "StructMaps": {
1121 "MapBool": {},
1122 "MapString": {},
1123 "MapBytes": {},
1124 "MapInt": {},
1125 "MapUint": {},
1126 "MapFloat": {}
1127 },
1128 "StructSlices": {
1129 "SliceBool": [],
1130 "SliceString": [],
1131 "SliceBytes": [],
1132 "SliceInt": [],
1133 "SliceUint": [],
1134 "SliceFloat": []
1135 },
1136 "Slice": [],
1137 "Array": [
1138 ""
1139 ],
1140 "Pointer": null,
1141 "Interface": null
1142 },
1143 "Interface": null
1144 }`,
1145 }, {
1146 name: name("Structs/Stringified"),
1147 eopts: EncodeOptions{Indent: "\t"},
1148 in: structStringifiedAll{
1149 Bool: true,
1150 String: "hello",
1151 Bytes: []byte{1, 2, 3},
1152 Int: -64, // should be stringified
1153 Uint: +64, // should be stringified
1154 Float: 3.14159, // should be stringified
1155 Map: map[string]string{"key": "value"},
1156 StructScalars: structScalars{
1157 Bool: true,
1158 String: "hello",
1159 Bytes: []byte{1, 2, 3},
1160 Int: -64, // should be stringified
1161 Uint: +64, // should be stringified
1162 Float: 3.14159, // should be stringified
1163 },
1164 StructMaps: structMaps{
1165 MapBool: map[string]bool{"": true},
1166 MapString: map[string]string{"": "hello"},
1167 MapBytes: map[string][]byte{"": {1, 2, 3}},
1168 MapInt: map[string]int64{"": -64}, // should be stringified
1169 MapUint: map[string]uint64{"": +64}, // should be stringified
1170 MapFloat: map[string]float64{"": 3.14159}, // should be stringified
1171 },
1172 StructSlices: structSlices{
1173 SliceBool: []bool{true},
1174 SliceString: []string{"hello"},
1175 SliceBytes: [][]byte{{1, 2, 3}},
1176 SliceInt: []int64{-64}, // should be stringified
1177 SliceUint: []uint64{+64}, // should be stringified
1178 SliceFloat: []float64{3.14159}, // should be stringified
1179 },
1180 Slice: []string{"fizz", "buzz"},
1181 Array: [1]string{"goodbye"},
1182 Pointer: new(structStringifiedAll), // should be stringified
1183 Interface: (*structStringifiedAll)(nil),
1184 },
1185 want: `{
1186 "Bool": true,
1187 "String": "hello",
1188 "Bytes": "AQID",
1189 "Int": "-64",
1190 "Uint": "64",
1191 "Float": "3.14159",
1192 "Map": {
1193 "key": "value"
1194 },
1195 "StructScalars": {
1196 "Bool": true,
1197 "String": "hello",
1198 "Bytes": "AQID",
1199 "Int": "-64",
1200 "Uint": "64",
1201 "Float": "3.14159"
1202 },
1203 "StructMaps": {
1204 "MapBool": {
1205 "": true
1206 },
1207 "MapString": {
1208 "": "hello"
1209 },
1210 "MapBytes": {
1211 "": "AQID"
1212 },
1213 "MapInt": {
1214 "": "-64"
1215 },
1216 "MapUint": {
1217 "": "64"
1218 },
1219 "MapFloat": {
1220 "": "3.14159"
1221 }
1222 },
1223 "StructSlices": {
1224 "SliceBool": [
1225 true
1226 ],
1227 "SliceString": [
1228 "hello"
1229 ],
1230 "SliceBytes": [
1231 "AQID"
1232 ],
1233 "SliceInt": [
1234 "-64"
1235 ],
1236 "SliceUint": [
1237 "64"
1238 ],
1239 "SliceFloat": [
1240 "3.14159"
1241 ]
1242 },
1243 "Slice": [
1244 "fizz",
1245 "buzz"
1246 ],
1247 "Array": [
1248 "goodbye"
1249 ],
1250 "Pointer": {
1251 "Bool": false,
1252 "String": "",
1253 "Bytes": "",
1254 "Int": "0",
1255 "Uint": "0",
1256 "Float": "0",
1257 "Map": {},
1258 "StructScalars": {
1259 "Bool": false,
1260 "String": "",
1261 "Bytes": "",
1262 "Int": "0",
1263 "Uint": "0",
1264 "Float": "0"
1265 },
1266 "StructMaps": {
1267 "MapBool": {},
1268 "MapString": {},
1269 "MapBytes": {},
1270 "MapInt": {},
1271 "MapUint": {},
1272 "MapFloat": {}
1273 },
1274 "StructSlices": {
1275 "SliceBool": [],
1276 "SliceString": [],
1277 "SliceBytes": [],
1278 "SliceInt": [],
1279 "SliceUint": [],
1280 "SliceFloat": []
1281 },
1282 "Slice": [],
1283 "Array": [
1284 ""
1285 ],
1286 "Pointer": null,
1287 "Interface": null
1288 },
1289 "Interface": null
1290 }`,
1291 }, {
1292 name: name("Structs/Stringified/Escaped"),
1293 eopts: EncodeOptions{Indent: "\t", EscapeRune: func(rune) bool { return true }},
1294 in: structStringifiedAll{
1295 Bool: true,
1296 String: "hello",
1297 Bytes: []byte{1, 2, 3},
1298 Int: -64, // should be stringified and escaped
1299 Uint: +64, // should be stringified and escaped
1300 Float: 3.14159, // should be stringified and escaped
1301 },
1302 want: `{
1303 "\u0042\u006f\u006f\u006c": true,
1304 "\u0053\u0074\u0072\u0069\u006e\u0067": "\u0068\u0065\u006c\u006c\u006f",
1305 "\u0042\u0079\u0074\u0065\u0073": "\u0041\u0051\u0049\u0044",
1306 "\u0049\u006e\u0074": "\u002d\u0036\u0034",
1307 "\u0055\u0069\u006e\u0074": "\u0036\u0034",
1308 "\u0046\u006c\u006f\u0061\u0074": "\u0033\u002e\u0031\u0034\u0031\u0035\u0039",
1309 "\u004d\u0061\u0070": {},
1310 "\u0053\u0074\u0072\u0075\u0063\u0074\u0053\u0063\u0061\u006c\u0061\u0072\u0073": {
1311 "\u0042\u006f\u006f\u006c": false,
1312 "\u0053\u0074\u0072\u0069\u006e\u0067": "",
1313 "\u0042\u0079\u0074\u0065\u0073": "",
1314 "\u0049\u006e\u0074": "\u0030",
1315 "\u0055\u0069\u006e\u0074": "\u0030",
1316 "\u0046\u006c\u006f\u0061\u0074": "\u0030"
1317 },
1318 "\u0053\u0074\u0072\u0075\u0063\u0074\u004d\u0061\u0070\u0073": {
1319 "\u004d\u0061\u0070\u0042\u006f\u006f\u006c": {},
1320 "\u004d\u0061\u0070\u0053\u0074\u0072\u0069\u006e\u0067": {},
1321 "\u004d\u0061\u0070\u0042\u0079\u0074\u0065\u0073": {},
1322 "\u004d\u0061\u0070\u0049\u006e\u0074": {},
1323 "\u004d\u0061\u0070\u0055\u0069\u006e\u0074": {},
1324 "\u004d\u0061\u0070\u0046\u006c\u006f\u0061\u0074": {}
1325 },
1326 "\u0053\u0074\u0072\u0075\u0063\u0074\u0053\u006c\u0069\u0063\u0065\u0073": {
1327 "\u0053\u006c\u0069\u0063\u0065\u0042\u006f\u006f\u006c": [],
1328 "\u0053\u006c\u0069\u0063\u0065\u0053\u0074\u0072\u0069\u006e\u0067": [],
1329 "\u0053\u006c\u0069\u0063\u0065\u0042\u0079\u0074\u0065\u0073": [],
1330 "\u0053\u006c\u0069\u0063\u0065\u0049\u006e\u0074": [],
1331 "\u0053\u006c\u0069\u0063\u0065\u0055\u0069\u006e\u0074": [],
1332 "\u0053\u006c\u0069\u0063\u0065\u0046\u006c\u006f\u0061\u0074": []
1333 },
1334 "\u0053\u006c\u0069\u0063\u0065": [],
1335 "\u0041\u0072\u0072\u0061\u0079": [
1336 ""
1337 ],
1338 "\u0050\u006f\u0069\u006e\u0074\u0065\u0072": null,
1339 "\u0049\u006e\u0074\u0065\u0072\u0066\u0061\u0063\u0065": null
1340 }`,
1341 }, {
1342 name: name("Structs/OmitZero/Zero"),
1343 in: structOmitZeroAll{},
1344 want: `{}`,
1345 }, {
1346 name: name("Structs/OmitZero/NonZero"),
1347 eopts: EncodeOptions{Indent: "\t"},
1348 in: structOmitZeroAll{
1349 Bool: true, // not omitted since true is non-zero
1350 String: " ", // not omitted since non-empty string is non-zero
1351 Bytes: []byte{}, // not omitted since allocated slice is non-zero
1352 Int: 1, // not omitted since 1 is non-zero
1353 Uint: 1, // not omitted since 1 is non-zero
1354 Float: math.SmallestNonzeroFloat64, // not omitted since still slightly above zero
1355 Map: map[string]string{}, // not omitted since allocated map is non-zero
1356 StructScalars: structScalars{unexported: true}, // not omitted since unexported is non-zero
1357 StructSlices: structSlices{Ignored: true}, // not omitted since Ignored is non-zero
1358 StructMaps: structMaps{MapBool: map[string]bool{}}, // not omitted since MapBool is non-zero
1359 Slice: []string{}, // not omitted since allocated slice is non-zero
1360 Array: [1]string{" "}, // not omitted since single array element is non-zero
1361 Pointer: new(structOmitZeroAll), // not omitted since pointer is non-zero (even if all fields of the struct value are zero)
1362 Interface: (*structOmitZeroAll)(nil), // not omitted since interface value is non-zero (even if interface value is a nil pointer)
1363 },
1364 want: `{
1365 "Bool": true,
1366 "String": " ",
1367 "Bytes": "",
1368 "Int": 1,
1369 "Uint": 1,
1370 "Float": 5e-324,
1371 "Map": {},
1372 "StructScalars": {
1373 "Bool": false,
1374 "String": "",
1375 "Bytes": "",
1376 "Int": 0,
1377 "Uint": 0,
1378 "Float": 0
1379 },
1380 "StructMaps": {
1381 "MapBool": {},
1382 "MapString": {},
1383 "MapBytes": {},
1384 "MapInt": {},
1385 "MapUint": {},
1386 "MapFloat": {}
1387 },
1388 "StructSlices": {
1389 "SliceBool": [],
1390 "SliceString": [],
1391 "SliceBytes": [],
1392 "SliceInt": [],
1393 "SliceUint": [],
1394 "SliceFloat": []
1395 },
1396 "Slice": [],
1397 "Array": [
1398 " "
1399 ],
1400 "Pointer": {},
1401 "Interface": null
1402 }`,
1403 }, {
1404 name: name("Structs/OmitZeroMethod/Zero"),
1405 in: structOmitZeroMethodAll{},
1406 want: `{"ValueNeverZero":"","PointerNeverZero":""}`,
1407 }, {
1408 name: name("Structs/OmitZeroMethod/NonZero"),
1409 eopts: EncodeOptions{Indent: "\t"},
1410 in: structOmitZeroMethodAll{
1411 ValueAlwaysZero: valueAlwaysZero("nonzero"),
1412 ValueNeverZero: valueNeverZero("nonzero"),
1413 PointerAlwaysZero: pointerAlwaysZero("nonzero"),
1414 PointerNeverZero: pointerNeverZero("nonzero"),
1415 PointerValueAlwaysZero: addr(valueAlwaysZero("nonzero")),
1416 PointerValueNeverZero: addr(valueNeverZero("nonzero")),
1417 PointerPointerAlwaysZero: addr(pointerAlwaysZero("nonzero")),
1418 PointerPointerNeverZero: addr(pointerNeverZero("nonzero")),
1419 PointerPointerValueAlwaysZero: addr(addr(valueAlwaysZero("nonzero"))), // marshaled since **valueAlwaysZero does not implement IsZero
1420 PointerPointerValueNeverZero: addr(addr(valueNeverZero("nonzero"))),
1421 PointerPointerPointerAlwaysZero: addr(addr(pointerAlwaysZero("nonzero"))), // marshaled since **pointerAlwaysZero does not implement IsZero
1422 PointerPointerPointerNeverZero: addr(addr(pointerNeverZero("nonzero"))),
1423 },
1424 want: `{
1425 "ValueNeverZero": "nonzero",
1426 "PointerNeverZero": "nonzero",
1427 "PointerValueNeverZero": "nonzero",
1428 "PointerPointerNeverZero": "nonzero",
1429 "PointerPointerValueAlwaysZero": "nonzero",
1430 "PointerPointerValueNeverZero": "nonzero",
1431 "PointerPointerPointerAlwaysZero": "nonzero",
1432 "PointerPointerPointerNeverZero": "nonzero"
1433 }`,
1434 }, {
1435 name: name("Structs/OmitZeroMethod/Interface/Zero"),
1436 eopts: EncodeOptions{Indent: "\t"},
1437 in: structOmitZeroMethodInterfaceAll{},
1438 want: `{}`,
1439 }, {
1440 name: name("Structs/OmitZeroMethod/Interface/PartialZero"),
1441 eopts: EncodeOptions{Indent: "\t"},
1442 in: structOmitZeroMethodInterfaceAll{
1443 ValueAlwaysZero: valueAlwaysZero(""),
1444 ValueNeverZero: valueNeverZero(""),
1445 PointerValueAlwaysZero: (*valueAlwaysZero)(nil),
1446 PointerValueNeverZero: (*valueNeverZero)(nil), // nil pointer, so method not called
1447 PointerPointerAlwaysZero: (*pointerAlwaysZero)(nil),
1448 PointerPointerNeverZero: (*pointerNeverZero)(nil), // nil pointer, so method not called
1449 },
1450 want: `{
1451 "ValueNeverZero": ""
1452 }`,
1453 }, {
1454 name: name("Structs/OmitZeroMethod/Interface/NonZero"),
1455 eopts: EncodeOptions{Indent: "\t"},
1456 in: structOmitZeroMethodInterfaceAll{
1457 ValueAlwaysZero: valueAlwaysZero("nonzero"),
1458 ValueNeverZero: valueNeverZero("nonzero"),
1459 PointerValueAlwaysZero: addr(valueAlwaysZero("nonzero")),
1460 PointerValueNeverZero: addr(valueNeverZero("nonzero")),
1461 PointerPointerAlwaysZero: addr(pointerAlwaysZero("nonzero")),
1462 PointerPointerNeverZero: addr(pointerNeverZero("nonzero")),
1463 },
1464 want: `{
1465 "ValueNeverZero": "nonzero",
1466 "PointerValueNeverZero": "nonzero",
1467 "PointerPointerNeverZero": "nonzero"
1468 }`,
1469 }, {
1470 name: name("Structs/OmitEmpty/Zero"),
1471 eopts: EncodeOptions{Indent: "\t"},
1472 in: structOmitEmptyAll{},
1473 want: `{
1474 "Bool": false,
1475 "StringNonEmpty": "value",
1476 "BytesNonEmpty": [
1477 "value"
1478 ],
1479 "Float": 0,
1480 "MapNonEmpty": {
1481 "key": "value"
1482 },
1483 "SliceNonEmpty": [
1484 "value"
1485 ]
1486 }`,
1487 }, {
1488 name: name("Structs/OmitEmpty/EmptyNonZero"),
1489 eopts: EncodeOptions{Indent: "\t"},
1490 in: structOmitEmptyAll{
1491 String: string(""),
1492 StringEmpty: stringMarshalEmpty(""),
1493 StringNonEmpty: stringMarshalNonEmpty(""),
1494 PointerString: addr(string("")),
1495 PointerStringEmpty: addr(stringMarshalEmpty("")),
1496 PointerStringNonEmpty: addr(stringMarshalNonEmpty("")),
1497 Bytes: []byte(""),
1498 BytesEmpty: bytesMarshalEmpty([]byte("")),
1499 BytesNonEmpty: bytesMarshalNonEmpty([]byte("")),
1500 PointerBytes: addr([]byte("")),
1501 PointerBytesEmpty: addr(bytesMarshalEmpty([]byte(""))),
1502 PointerBytesNonEmpty: addr(bytesMarshalNonEmpty([]byte(""))),
1503 Map: map[string]string{},
1504 MapEmpty: mapMarshalEmpty{},
1505 MapNonEmpty: mapMarshalNonEmpty{},
1506 PointerMap: addr(map[string]string{}),
1507 PointerMapEmpty: addr(mapMarshalEmpty{}),
1508 PointerMapNonEmpty: addr(mapMarshalNonEmpty{}),
1509 Slice: []string{},
1510 SliceEmpty: sliceMarshalEmpty{},
1511 SliceNonEmpty: sliceMarshalNonEmpty{},
1512 PointerSlice: addr([]string{}),
1513 PointerSliceEmpty: addr(sliceMarshalEmpty{}),
1514 PointerSliceNonEmpty: addr(sliceMarshalNonEmpty{}),
1515 Pointer: &structOmitZeroEmptyAll{},
1516 Interface: []string{},
1517 },
1518 want: `{
1519 "Bool": false,
1520 "StringNonEmpty": "value",
1521 "PointerStringNonEmpty": "value",
1522 "BytesNonEmpty": [
1523 "value"
1524 ],
1525 "PointerBytesNonEmpty": [
1526 "value"
1527 ],
1528 "Float": 0,
1529 "MapNonEmpty": {
1530 "key": "value"
1531 },
1532 "PointerMapNonEmpty": {
1533 "key": "value"
1534 },
1535 "SliceNonEmpty": [
1536 "value"
1537 ],
1538 "PointerSliceNonEmpty": [
1539 "value"
1540 ]
1541 }`,
1542 }, {
1543 name: name("Structs/OmitEmpty/NonEmpty"),
1544 eopts: EncodeOptions{Indent: "\t"},
1545 in: structOmitEmptyAll{
1546 Bool: true,
1547 PointerBool: addr(true),
1548 String: string("value"),
1549 StringEmpty: stringMarshalEmpty("value"),
1550 StringNonEmpty: stringMarshalNonEmpty("value"),
1551 PointerString: addr(string("value")),
1552 PointerStringEmpty: addr(stringMarshalEmpty("value")),
1553 PointerStringNonEmpty: addr(stringMarshalNonEmpty("value")),
1554 Bytes: []byte("value"),
1555 BytesEmpty: bytesMarshalEmpty([]byte("value")),
1556 BytesNonEmpty: bytesMarshalNonEmpty([]byte("value")),
1557 PointerBytes: addr([]byte("value")),
1558 PointerBytesEmpty: addr(bytesMarshalEmpty([]byte("value"))),
1559 PointerBytesNonEmpty: addr(bytesMarshalNonEmpty([]byte("value"))),
1560 Float: math.Copysign(0, -1),
1561 PointerFloat: addr(math.Copysign(0, -1)),
1562 Map: map[string]string{"": ""},
1563 MapEmpty: mapMarshalEmpty{"key": "value"},
1564 MapNonEmpty: mapMarshalNonEmpty{"key": "value"},
1565 PointerMap: addr(map[string]string{"": ""}),
1566 PointerMapEmpty: addr(mapMarshalEmpty{"key": "value"}),
1567 PointerMapNonEmpty: addr(mapMarshalNonEmpty{"key": "value"}),
1568 Slice: []string{""},
1569 SliceEmpty: sliceMarshalEmpty{"value"},
1570 SliceNonEmpty: sliceMarshalNonEmpty{"value"},
1571 PointerSlice: addr([]string{""}),
1572 PointerSliceEmpty: addr(sliceMarshalEmpty{"value"}),
1573 PointerSliceNonEmpty: addr(sliceMarshalNonEmpty{"value"}),
1574 Pointer: &structOmitZeroEmptyAll{Float: math.SmallestNonzeroFloat64},
1575 Interface: []string{""},
1576 },
1577 want: `{
1578 "Bool": true,
1579 "PointerBool": true,
1580 "String": "value",
1581 "StringNonEmpty": "value",
1582 "PointerString": "value",
1583 "PointerStringNonEmpty": "value",
1584 "Bytes": "dmFsdWU=",
1585 "BytesNonEmpty": [
1586 "value"
1587 ],
1588 "PointerBytes": "dmFsdWU=",
1589 "PointerBytesNonEmpty": [
1590 "value"
1591 ],
1592 "Float": -0,
1593 "PointerFloat": -0,
1594 "Map": {
1595 "": ""
1596 },
1597 "MapNonEmpty": {
1598 "key": "value"
1599 },
1600 "PointerMap": {
1601 "": ""
1602 },
1603 "PointerMapNonEmpty": {
1604 "key": "value"
1605 },
1606 "Slice": [
1607 ""
1608 ],
1609 "SliceNonEmpty": [
1610 "value"
1611 ],
1612 "PointerSlice": [
1613 ""
1614 ],
1615 "PointerSliceNonEmpty": [
1616 "value"
1617 ],
1618 "Pointer": {
1619 "Float": 5e-324
1620 },
1621 "Interface": [
1622 ""
1623 ]
1624 }`,
1625 }, {
1626 name: name("Structs/OmitEmpty/NonEmptyString"),
1627 in: struct {
1628 X string `json:",omitempty"`
1629 }{`"`},
1630 want: `{"X":"\""}`,
1631 }, {
1632 name: name("Structs/OmitZeroEmpty/Zero"),
1633 in: structOmitZeroEmptyAll{},
1634 want: `{}`,
1635 }, {
1636 name: name("Structs/OmitZeroEmpty/Empty"),
1637 in: structOmitZeroEmptyAll{
1638 Bytes: []byte{},
1639 Map: map[string]string{},
1640 Slice: []string{},
1641 Pointer: &structOmitZeroEmptyAll{},
1642 Interface: []string{},
1643 },
1644 want: `{}`,
1645 }, {
1646 name: name("Structs/OmitEmpty/PathologicalDepth"),
1647 in: func() any {
1648 type X struct {
1649 X *X `json:",omitempty"`
1650 }
1651 var make func(int) *X
1652 make = func(n int) *X {
1653 if n == 0 {
1654 return nil
1655 }
1656 return &X{make(n - 1)}
1657 }
1658 return make(100)
1659 }(),
1660 want: `{}`,
1661 useWriter: true,
1662 }, {
1663 name: name("Structs/OmitEmpty/PathologicalBreadth"),
1664 in: func() any {
1665 var fields []reflect.StructField
1666 for i := 0; i < 100; i++ {
1667 fields = append(fields, reflect.StructField{
1668 Name: fmt.Sprintf("X%d", i),
1669 Type: reflect.TypeOf(stringMarshalEmpty("")),
1670 Tag: `json:",omitempty"`,
1671 })
1672 }
1673 return reflect.New(reflect.StructOf(fields)).Interface()
1674 }(),
1675 want: `{}`,
1676 useWriter: true,
1677 }, {
1678 name: name("Structs/OmitEmpty/PathologicalTree"),
1679 in: func() any {
1680 type X struct {
1681 XL, XR *X `json:",omitempty"`
1682 }
1683 var make func(int) *X
1684 make = func(n int) *X {
1685 if n == 0 {
1686 return nil
1687 }
1688 return &X{make(n - 1), make(n - 1)}
1689 }
1690 return make(8)
1691 }(),
1692 want: `{}`,
1693 useWriter: true,
1694 }, {
1695 name: name("Structs/OmitZeroEmpty/NonEmpty"),
1696 in: structOmitZeroEmptyAll{
1697 Bytes: []byte("value"),
1698 Map: map[string]string{"": ""},
1699 Slice: []string{""},
1700 Pointer: &structOmitZeroEmptyAll{Bool: true},
1701 Interface: []string{""},
1702 },
1703 want: `{"Bytes":"dmFsdWU=","Map":{"":""},"Slice":[""],"Pointer":{"Bool":true},"Interface":[""]}`,
1704 }, {
1705 name: name("Structs/Format/Bytes"),
1706 eopts: EncodeOptions{Indent: "\t"},
1707 in: structFormatBytes{
1708 Base16: []byte("\x01\x23\x45\x67\x89\xab\xcd\xef"),
1709 Base32: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
1710 Base32Hex: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
1711 Base64: []byte("\x00\x10\x83\x10Q\x87 \x92\x8b0ӏA\x14\x93QU\x97a\x96\x9bqן\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2ۯ\xc3\x1c\xb3\xd3]\xb7㞻\xf3߿"),
1712 Base64URL: []byte("\x00\x10\x83\x10Q\x87 \x92\x8b0ӏA\x14\x93QU\x97a\x96\x9bqן\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2ۯ\xc3\x1c\xb3\xd3]\xb7㞻\xf3߿"),
1713 Array: []byte{1, 2, 3, 4},
1714 },
1715 want: `{
1716 "Base16": "0123456789abcdef",
1717 "Base32": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
1718 "Base32Hex": "0123456789ABCDEFGHIJKLMNOPQRSTUV",
1719 "Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
1720 "Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
1721 "Array": [
1722 1,
1723 2,
1724 3,
1725 4
1726 ]
1727 }`}, {
1728 name: name("Structs/Format/Bytes/Array"),
1729 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(in byte) ([]byte, error) {
1730 if in > 3 {
1731 return []byte("true"), nil
1732 } else {
1733 return []byte("false"), nil
1734 }
1735 })},
1736 in: struct {
1737 Array []byte `json:",format:array"`
1738 }{
1739 Array: []byte{1, 6, 2, 5, 3, 4},
1740 },
1741 want: `{"Array":[false,true,false,true,false,true]}`,
1742 }, {
1743 name: name("Structs/Format/Floats"),
1744 eopts: EncodeOptions{Indent: "\t"},
1745 in: []structFormatFloats{
1746 {NonFinite: math.Pi, PointerNonFinite: addr(math.Pi)},
1747 {NonFinite: math.NaN(), PointerNonFinite: addr(math.NaN())},
1748 {NonFinite: math.Inf(-1), PointerNonFinite: addr(math.Inf(-1))},
1749 {NonFinite: math.Inf(+1), PointerNonFinite: addr(math.Inf(+1))},
1750 },
1751 want: `[
1752 {
1753 "NonFinite": 3.141592653589793,
1754 "PointerNonFinite": 3.141592653589793
1755 },
1756 {
1757 "NonFinite": "NaN",
1758 "PointerNonFinite": "NaN"
1759 },
1760 {
1761 "NonFinite": "-Infinity",
1762 "PointerNonFinite": "-Infinity"
1763 },
1764 {
1765 "NonFinite": "Infinity",
1766 "PointerNonFinite": "Infinity"
1767 }
1768 ]`,
1769 }, {
1770 name: name("Structs/Format/Maps"),
1771 eopts: EncodeOptions{Indent: "\t"},
1772 in: []structFormatMaps{
1773 {EmitNull: nil, PointerEmitNull: new(map[string]string)},
1774 {EmitNull: map[string]string{}, PointerEmitNull: addr(map[string]string{})},
1775 {EmitNull: map[string]string{"k": "v"}, PointerEmitNull: addr(map[string]string{"k": "v"})},
1776 },
1777 want: `[
1778 {
1779 "EmitNull": null,
1780 "PointerEmitNull": null
1781 },
1782 {
1783 "EmitNull": {},
1784 "PointerEmitNull": {}
1785 },
1786 {
1787 "EmitNull": {
1788 "k": "v"
1789 },
1790 "PointerEmitNull": {
1791 "k": "v"
1792 }
1793 }
1794 ]`,
1795 }, {
1796 name: name("Structs/Format/Slices"),
1797 eopts: EncodeOptions{Indent: "\t"},
1798 in: []structFormatSlices{
1799 {EmitNull: nil, PointerEmitNull: new([]string)},
1800 {EmitNull: []string{}, PointerEmitNull: addr([]string{})},
1801 {EmitNull: []string{"v"}, PointerEmitNull: addr([]string{"v"})},
1802 },
1803 want: `[
1804 {
1805 "EmitNull": null,
1806 "PointerEmitNull": null
1807 },
1808 {
1809 "EmitNull": [],
1810 "PointerEmitNull": []
1811 },
1812 {
1813 "EmitNull": [
1814 "v"
1815 ],
1816 "PointerEmitNull": [
1817 "v"
1818 ]
1819 }
1820 ]`,
1821 }, {
1822 name: name("Structs/Format/Invalid/Bool"),
1823 in: structFormatInvalid{Bool: true},
1824 want: `{"Bool"`,
1825 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New(`invalid format flag: "invalid"`)},
1826 }, {
1827 name: name("Structs/Format/Invalid/String"),
1828 in: structFormatInvalid{String: "string"},
1829 want: `{"String"`,
1830 wantErr: &SemanticError{action: "marshal", GoType: stringType, Err: errors.New(`invalid format flag: "invalid"`)},
1831 }, {
1832 name: name("Structs/Format/Invalid/Bytes"),
1833 in: structFormatInvalid{Bytes: []byte("bytes")},
1834 want: `{"Bytes"`,
1835 wantErr: &SemanticError{action: "marshal", GoType: bytesType, Err: errors.New(`invalid format flag: "invalid"`)},
1836 }, {
1837 name: name("Structs/Format/Invalid/Int"),
1838 in: structFormatInvalid{Int: 1},
1839 want: `{"Int"`,
1840 wantErr: &SemanticError{action: "marshal", GoType: int64Type, Err: errors.New(`invalid format flag: "invalid"`)},
1841 }, {
1842 name: name("Structs/Format/Invalid/Uint"),
1843 in: structFormatInvalid{Uint: 1},
1844 want: `{"Uint"`,
1845 wantErr: &SemanticError{action: "marshal", GoType: uint64Type, Err: errors.New(`invalid format flag: "invalid"`)},
1846 }, {
1847 name: name("Structs/Format/Invalid/Float"),
1848 in: structFormatInvalid{Float: 1},
1849 want: `{"Float"`,
1850 wantErr: &SemanticError{action: "marshal", GoType: float64Type, Err: errors.New(`invalid format flag: "invalid"`)},
1851 }, {
1852 name: name("Structs/Format/Invalid/Map"),
1853 in: structFormatInvalid{Map: map[string]string{}},
1854 want: `{"Map"`,
1855 wantErr: &SemanticError{action: "marshal", GoType: mapStringStringType, Err: errors.New(`invalid format flag: "invalid"`)},
1856 }, {
1857 name: name("Structs/Format/Invalid/Struct"),
1858 in: structFormatInvalid{Struct: structAll{Bool: true}},
1859 want: `{"Struct"`,
1860 wantErr: &SemanticError{action: "marshal", GoType: structAllType, Err: errors.New(`invalid format flag: "invalid"`)},
1861 }, {
1862 name: name("Structs/Format/Invalid/Slice"),
1863 in: structFormatInvalid{Slice: []string{}},
1864 want: `{"Slice"`,
1865 wantErr: &SemanticError{action: "marshal", GoType: sliceStringType, Err: errors.New(`invalid format flag: "invalid"`)},
1866 }, {
1867 name: name("Structs/Format/Invalid/Array"),
1868 in: structFormatInvalid{Array: [1]string{"string"}},
1869 want: `{"Array"`,
1870 wantErr: &SemanticError{action: "marshal", GoType: array1StringType, Err: errors.New(`invalid format flag: "invalid"`)},
1871 }, {
1872 name: name("Structs/Format/Invalid/Interface"),
1873 in: structFormatInvalid{Interface: "anything"},
1874 want: `{"Interface"`,
1875 wantErr: &SemanticError{action: "marshal", GoType: anyType, Err: errors.New(`invalid format flag: "invalid"`)},
1876 }, {
1877 name: name("Structs/Inline/Zero"),
1878 in: structInlined{},
1879 want: `{"D":""}`,
1880 }, {
1881 name: name("Structs/Inline/Alloc"),
1882 in: structInlined{
1883 X: structInlinedL1{
1884 X: &structInlinedL2{},
1885 StructEmbed1: StructEmbed1{},
1886 },
1887 StructEmbed2: &StructEmbed2{},
1888 },
1889 want: `{"A":"","B":"","D":"","E":"","F":"","G":""}`,
1890 }, {
1891 name: name("Structs/Inline/NonZero"),
1892 in: structInlined{
1893 X: structInlinedL1{
1894 X: &structInlinedL2{A: "A1", B: "B1", C: "C1"},
1895 StructEmbed1: StructEmbed1{C: "C2", D: "D2", E: "E2"},
1896 },
1897 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
1898 },
1899 want: `{"A":"A1","B":"B1","D":"D2","E":"E3","F":"F3","G":"G3"}`,
1900 }, {
1901 name: name("Structs/Inline/DualCycle"),
1902 in: cyclicA{
1903 B1: cyclicB{F: 1}, // B1.F ignored since it conflicts with B2.F
1904 B2: cyclicB{F: 2}, // B2.F ignored since it conflicts with B1.F
1905 },
1906 want: `{}`,
1907 }, {
1908 name: name("Structs/InlinedFallback/RawValue/Nil"),
1909 in: structInlineRawValue{X: RawValue(nil)},
1910 want: `{}`,
1911 }, {
1912 name: name("Structs/InlinedFallback/RawValue/Empty"),
1913 in: structInlineRawValue{X: RawValue("")},
1914 want: `{}`,
1915 }, {
1916 name: name("Structs/InlinedFallback/RawValue/NonEmptyN1"),
1917 in: structInlineRawValue{X: RawValue(` { "fizz" : "buzz" } `)},
1918 want: `{"fizz":"buzz"}`,
1919 }, {
1920 name: name("Structs/InlinedFallback/RawValue/NonEmptyN2"),
1921 in: structInlineRawValue{X: RawValue(` { "fizz" : "buzz" , "foo" : "bar" } `)},
1922 want: `{"fizz":"buzz","foo":"bar"}`,
1923 }, {
1924 name: name("Structs/InlinedFallback/RawValue/NonEmptyWithOthers"),
1925 in: structInlineRawValue{
1926 A: 1,
1927 X: RawValue(` { "fizz" : "buzz" , "foo" : "bar" } `),
1928 B: 2,
1929 },
1930 // NOTE: Inlined fallback fields are always serialized last.
1931 want: `{"A":1,"B":2,"fizz":"buzz","foo":"bar"}`,
1932 }, {
1933 name: name("Structs/InlinedFallback/RawValue/RejectDuplicateNames"),
1934 eopts: EncodeOptions{AllowDuplicateNames: false},
1935 in: structInlineRawValue{X: RawValue(` { "fizz" : "buzz" , "fizz" : "buzz" } `)},
1936 want: `{"fizz":"buzz"`,
1937 wantErr: &SyntacticError{str: `duplicate name "fizz" in object`},
1938 }, {
1939 name: name("Structs/InlinedFallback/RawValue/AllowDuplicateNames"),
1940 eopts: EncodeOptions{AllowDuplicateNames: true},
1941 in: structInlineRawValue{X: RawValue(` { "fizz" : "buzz" , "fizz" : "buzz" } `)},
1942 want: `{"fizz":"buzz","fizz":"buzz"}`,
1943 }, {
1944 name: name("Structs/InlinedFallback/RawValue/RejectInvalidUTF8"),
1945 eopts: EncodeOptions{AllowInvalidUTF8: false},
1946 in: structInlineRawValue{X: RawValue(`{"` + "\xde\xad\xbe\xef" + `":"value"}`)},
1947 want: `{`,
1948 wantErr: &SyntacticError{str: "invalid UTF-8 within string"},
1949 }, {
1950 name: name("Structs/InlinedFallback/RawValue/AllowInvalidUTF8"),
1951 eopts: EncodeOptions{AllowInvalidUTF8: true},
1952 in: structInlineRawValue{X: RawValue(`{"` + "\xde\xad\xbe\xef" + `":"value"}`)},
1953 want: `{"ޭ��":"value"}`,
1954 }, {
1955 name: name("Structs/InlinedFallback/RawValue/InvalidWhitespace"),
1956 in: structInlineRawValue{X: RawValue("\n\r\t ")},
1957 want: `{`,
1958 wantErr: &SemanticError{action: "marshal", GoType: rawValueType, Err: io.EOF},
1959 }, {
1960 name: name("Structs/InlinedFallback/RawValue/InvalidObject"),
1961 in: structInlineRawValue{X: RawValue(` true `)},
1962 want: `{`,
1963 wantErr: &SemanticError{action: "marshal", JSONKind: 't', GoType: rawValueType, Err: errors.New("inlined raw value must be a JSON object")},
1964 }, {
1965 name: name("Structs/InlinedFallback/RawValue/InvalidObjectName"),
1966 in: structInlineRawValue{X: RawValue(` { true : false } `)},
1967 want: `{`,
1968 wantErr: &SemanticError{action: "marshal", GoType: rawValueType, Err: errMissingName.withOffset(int64(len(" { ")))},
1969 }, {
1970 name: name("Structs/InlinedFallback/RawValue/InvalidObjectEnd"),
1971 in: structInlineRawValue{X: RawValue(` { "name" : false , } `)},
1972 want: `{"name":false`,
1973 wantErr: &SemanticError{action: "marshal", GoType: rawValueType, Err: newInvalidCharacterError([]byte(","), "before next token").withOffset(int64(len(` { "name" : false `)))},
1974 }, {
1975 name: name("Structs/InlinedFallback/RawValue/InvalidDualObject"),
1976 in: structInlineRawValue{X: RawValue(`{}{}`)},
1977 want: `{`,
1978 wantErr: &SemanticError{action: "marshal", GoType: rawValueType, Err: newInvalidCharacterError([]byte("{"), "after top-level value")},
1979 }, {
1980 name: name("Structs/InlinedFallback/RawValue/Nested/Nil"),
1981 in: structInlinePointerInlineRawValue{},
1982 want: `{}`,
1983 }, {
1984 name: name("Structs/InlinedFallback/PointerRawValue/Nil"),
1985 in: structInlinePointerRawValue{},
1986 want: `{}`,
1987 }, {
1988 name: name("Structs/InlinedFallback/PointerRawValue/NonEmpty"),
1989 in: structInlinePointerRawValue{X: addr(RawValue(` { "fizz" : "buzz" } `))},
1990 want: `{"fizz":"buzz"}`,
1991 }, {
1992 name: name("Structs/InlinedFallback/PointerRawValue/Nested/Nil"),
1993 in: structInlineInlinePointerRawValue{},
1994 want: `{}`,
1995 }, {
1996 name: name("Structs/InlinedFallback/MapStringAny/Nil"),
1997 in: structInlineMapStringAny{X: nil},
1998 want: `{}`,
1999 }, {
2000 name: name("Structs/InlinedFallback/MapStringAny/Empty"),
2001 in: structInlineMapStringAny{X: make(jsonObject)},
2002 want: `{}`,
2003 }, {
2004 name: name("Structs/InlinedFallback/MapStringAny/NonEmptyN1"),
2005 in: structInlineMapStringAny{X: jsonObject{"fizz": nil}},
2006 want: `{"fizz":null}`,
2007 }, {
2008 name: name("Structs/InlinedFallback/MapStringAny/NonEmptyN2"),
2009 in: structInlineMapStringAny{X: jsonObject{"fizz": time.Time{}, "buzz": math.Pi}},
2010 want: `{"buzz":3.141592653589793,"fizz":"0001-01-01T00:00:00Z"}`,
2011 canonicalize: true,
2012 }, {
2013 name: name("Structs/InlinedFallback/MapStringAny/NonEmptyWithOthers"),
2014 in: structInlineMapStringAny{
2015 A: 1,
2016 X: jsonObject{"fizz": nil},
2017 B: 2,
2018 },
2019 // NOTE: Inlined fallback fields are always serialized last.
2020 want: `{"A":1,"B":2,"fizz":null}`,
2021 }, {
2022 name: name("Structs/InlinedFallback/MapStringAny/RejectInvalidUTF8"),
2023 eopts: EncodeOptions{AllowInvalidUTF8: false},
2024 in: structInlineMapStringAny{X: jsonObject{"\xde\xad\xbe\xef": nil}},
2025 want: `{`,
2026 wantErr: &SyntacticError{str: "invalid UTF-8 within string"},
2027 }, {
2028 name: name("Structs/InlinedFallback/MapStringAny/AllowInvalidUTF8"),
2029 eopts: EncodeOptions{AllowInvalidUTF8: true},
2030 in: structInlineMapStringAny{X: jsonObject{"\xde\xad\xbe\xef": nil}},
2031 want: `{"ޭ��":null}`,
2032 }, {
2033 name: name("Structs/InlinedFallback/MapStringAny/InvalidValue"),
2034 eopts: EncodeOptions{AllowInvalidUTF8: true},
2035 in: structInlineMapStringAny{X: jsonObject{"name": make(chan string)}},
2036 want: `{"name"`,
2037 wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
2038 }, {
2039 name: name("Structs/InlinedFallback/MapStringAny/Nested/Nil"),
2040 in: structInlinePointerInlineMapStringAny{},
2041 want: `{}`,
2042 }, {
2043 name: name("Structs/InlinedFallback/MapStringAny/MarshalFuncV1"),
2044 mopts: MarshalOptions{
2045 Marshalers: MarshalFuncV1(func(v float64) ([]byte, error) {
2046 return []byte(fmt.Sprintf(`"%v"`, v)), nil
2047 }),
2048 },
2049 in: structInlineMapStringAny{X: jsonObject{"fizz": 3.14159}},
2050 want: `{"fizz":"3.14159"}`,
2051 }, {
2052 name: name("Structs/InlinedFallback/PointerMapStringAny/Nil"),
2053 in: structInlinePointerMapStringAny{X: nil},
2054 want: `{}`,
2055 }, {
2056 name: name("Structs/InlinedFallback/PointerMapStringAny/NonEmpty"),
2057 in: structInlinePointerMapStringAny{X: addr(jsonObject{"name": "value"})},
2058 want: `{"name":"value"}`,
2059 }, {
2060 name: name("Structs/InlinedFallback/PointerMapStringAny/Nested/Nil"),
2061 in: structInlineInlinePointerMapStringAny{},
2062 want: `{}`,
2063 }, {
2064 name: name("Structs/InlinedFallback/MapStringInt"),
2065 in: structInlineMapStringInt{
2066 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2067 },
2068 want: `{"one":1,"two":2,"zero":0}`,
2069 canonicalize: true,
2070 }, {
2071 name: name("Structs/InlinedFallback/MapStringInt/Deterministic"),
2072 mopts: MarshalOptions{Deterministic: true},
2073 in: structInlineMapStringInt{
2074 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2075 },
2076 want: `{"one":1,"two":2,"zero":0}`,
2077 }, {
2078 name: name("Structs/InlinedFallback/MapStringInt/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
2079 mopts: MarshalOptions{Deterministic: true},
2080 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: false},
2081 in: structInlineMapStringInt{
2082 X: map[string]int{"\xff": 0, "\xfe": 1},
2083 },
2084 want: `{"�":1`,
2085 wantErr: &SyntacticError{str: `duplicate name "�" in object`},
2086 }, {
2087 name: name("Structs/InlinedFallback/MapStringInt/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
2088 mopts: MarshalOptions{Deterministic: true},
2089 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true},
2090 in: structInlineMapStringInt{
2091 X: map[string]int{"\xff": 0, "\xfe": 1},
2092 },
2093 want: `{"�":1,"�":0}`,
2094 }, {
2095 name: name("Structs/InlinedFallback/MapStringInt/StringifiedNumbers"),
2096 mopts: MarshalOptions{StringifyNumbers: true},
2097 in: structInlineMapStringInt{
2098 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2099 },
2100 want: `{"one":"1","two":"2","zero":"0"}`,
2101 canonicalize: true,
2102 }, {
2103 name: name("Structs/InlinedFallback/MapStringInt/MarshalFuncV1"),
2104 mopts: MarshalOptions{
2105 Marshalers: NewMarshalers(
2106 // Marshalers do not affect the string key of inlined maps.
2107 MarshalFuncV1(func(v string) ([]byte, error) {
2108 return []byte(fmt.Sprintf(`"%q"`, strings.ToUpper(v))), nil
2109 }),
2110 MarshalFuncV1(func(v int) ([]byte, error) {
2111 return []byte(fmt.Sprintf(`"%v"`, v)), nil
2112 }),
2113 ),
2114 },
2115 in: structInlineMapStringInt{
2116 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2117 },
2118 want: `{"one":"1","two":"2","zero":"0"}`,
2119 canonicalize: true,
2120 }, {
2121 name: name("Structs/InlinedFallback/DiscardUnknownMembers"),
2122 mopts: MarshalOptions{DiscardUnknownMembers: true},
2123 in: structInlineRawValue{
2124 A: 1,
2125 X: RawValue(` { "fizz" : "buzz" } `),
2126 B: 2,
2127 },
2128 // NOTE: DiscardUnknownMembers has no effect since this is "inline".
2129 want: `{"A":1,"B":2,"fizz":"buzz"}`,
2130 }, {
2131 name: name("Structs/UnknownFallback/DiscardUnknownMembers"),
2132 mopts: MarshalOptions{DiscardUnknownMembers: true},
2133 in: structUnknownRawValue{
2134 A: 1,
2135 X: RawValue(` { "fizz" : "buzz" } `),
2136 B: 2,
2137 },
2138 want: `{"A":1,"B":2}`,
2139 }, {
2140 name: name("Structs/UnknownFallback"),
2141 in: structUnknownRawValue{
2142 A: 1,
2143 X: RawValue(` { "fizz" : "buzz" } `),
2144 B: 2,
2145 },
2146 want: `{"A":1,"B":2,"fizz":"buzz"}`,
2147 }, {
2148 name: name("Structs/DuplicateName/NoCaseInlineRawValue/Other"),
2149 in: structNoCaseInlineRawValue{
2150 X: RawValue(`{"dupe":"","dupe":""}`),
2151 },
2152 want: `{"dupe":""`,
2153 wantErr: &SyntacticError{str: `duplicate name "dupe" in object`},
2154 }, {
2155 name: name("Structs/DuplicateName/NoCaseInlineRawValue/Other/AllowDuplicateNames"),
2156 eopts: EncodeOptions{AllowDuplicateNames: true},
2157 in: structNoCaseInlineRawValue{
2158 X: RawValue(`{"dupe": "", "dupe": ""}`),
2159 },
2160 want: `{"dupe":"","dupe":""}`,
2161 }, {
2162 name: name("Structs/DuplicateName/NoCaseInlineRawValue/ExactDifferent"),
2163 in: structNoCaseInlineRawValue{
2164 X: RawValue(`{"Aaa": "", "AaA": "", "AAa": "", "AAA": ""}`),
2165 },
2166 want: `{"Aaa":"","AaA":"","AAa":"","AAA":""}`,
2167 }, {
2168 name: name("Structs/DuplicateName/NoCaseInlineRawValue/ExactConflict"),
2169 in: structNoCaseInlineRawValue{
2170 X: RawValue(`{"Aaa": "", "Aaa": ""}`),
2171 },
2172 want: `{"Aaa":""`,
2173 wantErr: &SyntacticError{str: `duplicate name "Aaa" in object`},
2174 }, {
2175 name: name("Structs/DuplicateName/NoCaseInlineRawValue/ExactConflict/AllowDuplicateNames"),
2176 eopts: EncodeOptions{AllowDuplicateNames: true},
2177 in: structNoCaseInlineRawValue{
2178 X: RawValue(`{"Aaa": "", "Aaa": ""}`),
2179 },
2180 want: `{"Aaa":"","Aaa":""}`,
2181 }, {
2182 name: name("Structs/DuplicateName/NoCaseInlineRawValue/NoCaseConflict"),
2183 in: structNoCaseInlineRawValue{
2184 X: RawValue(`{"Aaa": "", "AaA": "", "aaa": ""}`),
2185 },
2186 want: `{"Aaa":"","AaA":""`,
2187 wantErr: &SyntacticError{str: `duplicate name "aaa" in object`},
2188 }, {
2189 name: name("Structs/DuplicateName/NoCaseInlineRawValue/NoCaseConflict/AllowDuplicateNames"),
2190 eopts: EncodeOptions{AllowDuplicateNames: true},
2191 in: structNoCaseInlineRawValue{
2192 X: RawValue(`{"Aaa": "", "AaA": "", "aaa": ""}`),
2193 },
2194 want: `{"Aaa":"","AaA":"","aaa":""}`,
2195 }, {
2196 name: name("Structs/DuplicateName/NoCaseInlineRawValue/ExactDifferentWithField"),
2197 in: structNoCaseInlineRawValue{
2198 AAA: "x",
2199 AaA: "x",
2200 X: RawValue(`{"Aaa": ""}`),
2201 },
2202 want: `{"AAA":"x","AaA":"x","Aaa":""}`,
2203 }, {
2204 name: name("Structs/DuplicateName/NoCaseInlineRawValue/ExactConflictWithField"),
2205 in: structNoCaseInlineRawValue{
2206 AAA: "x",
2207 AaA: "x",
2208 X: RawValue(`{"AAA": ""}`),
2209 },
2210 want: `{"AAA":"x","AaA":"x"`,
2211 wantErr: &SyntacticError{str: `duplicate name "AAA" in object`},
2212 }, {
2213 name: name("Structs/DuplicateName/NoCaseInlineRawValue/NoCaseConflictWithField"),
2214 in: structNoCaseInlineRawValue{
2215 AAA: "x",
2216 AaA: "x",
2217 X: RawValue(`{"aaa": ""}`),
2218 },
2219 want: `{"AAA":"x","AaA":"x"`,
2220 wantErr: &SyntacticError{str: `duplicate name "aaa" in object`},
2221 }, {
2222 name: name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactDifferent"),
2223 in: structNoCaseInlineMapStringAny{
2224 X: jsonObject{"Aaa": "", "AaA": "", "AAa": "", "AAA": ""},
2225 },
2226 want: `{"AAA":"","AAa":"","AaA":"","Aaa":""}`,
2227 canonicalize: true,
2228 }, {
2229 name: name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactDifferentWithField"),
2230 in: structNoCaseInlineMapStringAny{
2231 AAA: "x",
2232 AaA: "x",
2233 X: jsonObject{"Aaa": ""},
2234 },
2235 want: `{"AAA":"x","AaA":"x","Aaa":""}`,
2236 }, {
2237 name: name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactConflictWithField"),
2238 in: structNoCaseInlineMapStringAny{
2239 AAA: "x",
2240 AaA: "x",
2241 X: jsonObject{"AAA": ""},
2242 },
2243 want: `{"AAA":"x","AaA":"x"`,
2244 wantErr: &SyntacticError{str: `duplicate name "AAA" in object`},
2245 }, {
2246 name: name("Structs/DuplicateName/NoCaseInlineMapStringAny/NoCaseConflictWithField"),
2247 in: structNoCaseInlineMapStringAny{
2248 AAA: "x",
2249 AaA: "x",
2250 X: jsonObject{"aaa": ""},
2251 },
2252 want: `{"AAA":"x","AaA":"x"`,
2253 wantErr: &SyntacticError{str: `duplicate name "aaa" in object`},
2254 }, {
2255 name: name("Structs/Invalid/Conflicting"),
2256 in: structConflicting{},
2257 want: ``,
2258 wantErr: &SemanticError{action: "marshal", GoType: structConflictingType, Err: errors.New("Go struct fields A and B conflict over JSON object name \"conflict\"")},
2259 }, {
2260 name: name("Structs/Invalid/NoneExported"),
2261 in: structNoneExported{},
2262 want: ``,
2263 wantErr: &SemanticError{action: "marshal", GoType: structNoneExportedType, Err: errors.New("Go struct has no exported fields")},
2264 }, {
2265 name: name("Structs/Invalid/MalformedTag"),
2266 in: structMalformedTag{},
2267 want: ``,
2268 wantErr: &SemanticError{action: "marshal", GoType: structMalformedTagType, Err: errors.New("Go struct field Malformed has malformed `json` tag: invalid character '\"' at start of option (expecting Unicode letter or single quote)")},
2269 }, {
2270 name: name("Structs/Invalid/UnexportedTag"),
2271 in: structUnexportedTag{},
2272 want: ``,
2273 wantErr: &SemanticError{action: "marshal", GoType: structUnexportedTagType, Err: errors.New("unexported Go struct field unexported cannot have non-ignored `json:\"name\"` tag")},
2274 }, {
2275 name: name("Structs/Invalid/UnexportedEmbedded"),
2276 in: structUnexportedEmbedded{},
2277 want: ``,
2278 wantErr: &SemanticError{action: "marshal", GoType: structUnexportedEmbeddedType, Err: errors.New("embedded Go struct field namedString of an unexported type must be explicitly ignored with a `json:\"-\"` tag")},
2279 }, {
2280 name: name("Structs/IgnoreInvalidFormat"),
2281 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
2282 in: struct{}{},
2283 want: `{}`,
2284 }, {
2285 name: name("Slices/Interface"),
2286 in: []any{
2287 false, true,
2288 "hello", []byte("world"),
2289 int32(-32), namedInt64(-64),
2290 uint32(+32), namedUint64(+64),
2291 float32(32.32), namedFloat64(64.64),
2292 },
2293 want: `[false,true,"hello","d29ybGQ=",-32,-64,32,64,32.32,64.64]`,
2294 }, {
2295 name: name("Slices/Invalid/Channel"),
2296 in: [](chan string){nil},
2297 want: `[`,
2298 wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
2299 }, {
2300 name: name("Slices/RecursiveSlice"),
2301 in: recursiveSlice{
2302 nil,
2303 {},
2304 {nil},
2305 {nil, {}},
2306 },
2307 want: `[[],[],[[]],[[],[]]]`,
2308 }, {
2309 name: name("Slices/CyclicSlice"),
2310 in: func() recursiveSlice {
2311 s := recursiveSlice{{}}
2312 s[0] = s
2313 return s
2314 }(),
2315 want: strings.Repeat(`[`, startDetectingCyclesAfter) + `[`,
2316 wantErr: &SemanticError{action: "marshal", GoType: reflect.TypeOf(recursiveSlice{}), Err: errors.New("encountered a cycle")},
2317 }, {
2318 name: name("Slices/IgnoreInvalidFormat"),
2319 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
2320 in: []string{"hello", "goodbye"},
2321 want: `["hello","goodbye"]`,
2322 }, {
2323 name: name("Arrays/Empty"),
2324 in: [0]struct{}{},
2325 want: `[]`,
2326 }, {
2327 name: name("Arrays/Bool"),
2328 in: [2]bool{false, true},
2329 want: `[false,true]`,
2330 }, {
2331 name: name("Arrays/String"),
2332 in: [2]string{"hello", "goodbye"},
2333 want: `["hello","goodbye"]`,
2334 }, {
2335 name: name("Arrays/Bytes"),
2336 in: [2][]byte{[]byte("hello"), []byte("goodbye")},
2337 want: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
2338 }, {
2339 name: name("Arrays/Int"),
2340 in: [2]int64{math.MinInt64, math.MaxInt64},
2341 want: `[-9223372036854775808,9223372036854775807]`,
2342 }, {
2343 name: name("Arrays/Uint"),
2344 in: [2]uint64{0, math.MaxUint64},
2345 want: `[0,18446744073709551615]`,
2346 }, {
2347 name: name("Arrays/Float"),
2348 in: [2]float64{-math.MaxFloat64, +math.MaxFloat64},
2349 want: `[-1.7976931348623157e+308,1.7976931348623157e+308]`,
2350 }, {
2351 name: name("Arrays/Invalid/Channel"),
2352 in: new([1]chan string),
2353 want: `[`,
2354 wantErr: &SemanticError{action: "marshal", GoType: chanStringType},
2355 }, {
2356 name: name("Arrays/IgnoreInvalidFormat"),
2357 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
2358 in: [2]string{"hello", "goodbye"},
2359 want: `["hello","goodbye"]`,
2360 }, {
2361 name: name("Pointers/NilL0"),
2362 in: (*int)(nil),
2363 want: `null`,
2364 }, {
2365 name: name("Pointers/NilL1"),
2366 in: new(*int),
2367 want: `null`,
2368 }, {
2369 name: name("Pointers/Bool"),
2370 in: addr(addr(bool(true))),
2371 want: `true`,
2372 }, {
2373 name: name("Pointers/String"),
2374 in: addr(addr(string("string"))),
2375 want: `"string"`,
2376 }, {
2377 name: name("Pointers/Bytes"),
2378 in: addr(addr([]byte("bytes"))),
2379 want: `"Ynl0ZXM="`,
2380 }, {
2381 name: name("Pointers/Int"),
2382 in: addr(addr(int(-100))),
2383 want: `-100`,
2384 }, {
2385 name: name("Pointers/Uint"),
2386 in: addr(addr(uint(100))),
2387 want: `100`,
2388 }, {
2389 name: name("Pointers/Float"),
2390 in: addr(addr(float64(3.14159))),
2391 want: `3.14159`,
2392 }, {
2393 name: name("Pointers/CyclicPointer"),
2394 in: func() *recursivePointer {
2395 p := new(recursivePointer)
2396 p.P = p
2397 return p
2398 }(),
2399 want: strings.Repeat(`{"P":`, startDetectingCyclesAfter) + `{"P"`,
2400 wantErr: &SemanticError{action: "marshal", GoType: reflect.TypeOf((*recursivePointer)(nil)), Err: errors.New("encountered a cycle")},
2401 }, {
2402 name: name("Pointers/IgnoreInvalidFormat"),
2403 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
2404 in: addr(addr(bool(true))),
2405 want: `true`,
2406 }, {
2407 name: name("Interfaces/Nil/Empty"),
2408 in: [1]any{nil},
2409 want: `[null]`,
2410 }, {
2411 name: name("Interfaces/Nil/NonEmpty"),
2412 in: [1]io.Reader{nil},
2413 want: `[null]`,
2414 }, {
2415 name: name("Interfaces/IgnoreInvalidFormat"),
2416 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
2417 in: [1]io.Reader{nil},
2418 want: `[null]`,
2419 }, {
2420 name: name("Interfaces/Any"),
2421 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}, [8]byte{}}},
2422 want: `{"X":[null,false,"",0,{},[],"AAAAAAAAAAA="]}`,
2423 }, {
2424 name: name("Interfaces/Any/Named"),
2425 in: struct{ X namedAny }{[]namedAny{nil, false, "", 0.0, map[string]namedAny{}, []namedAny{}, [8]byte{}}},
2426 want: `{"X":[null,false,"",0,{},[],"AAAAAAAAAAA="]}`,
2427 }, {
2428 name: name("Interfaces/Any/Stringified"),
2429 mopts: MarshalOptions{StringifyNumbers: true},
2430 in: struct{ X any }{0.0},
2431 want: `{"X":"0"}`,
2432 }, {
2433 name: name("Interfaces/Any/MarshalFunc/Any"),
2434 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v any) ([]byte, error) {
2435 return []byte(`"called"`), nil
2436 })},
2437 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2438 want: `"called"`,
2439 }, {
2440 name: name("Interfaces/Any/MarshalFunc/Bool"),
2441 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v bool) ([]byte, error) {
2442 return []byte(`"called"`), nil
2443 })},
2444 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2445 want: `{"X":[null,"called","",0,{},[]]}`,
2446 }, {
2447 name: name("Interfaces/Any/MarshalFunc/String"),
2448 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v string) ([]byte, error) {
2449 return []byte(`"called"`), nil
2450 })},
2451 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2452 want: `{"X":[null,false,"called",0,{},[]]}`,
2453 }, {
2454 name: name("Interfaces/Any/MarshalFunc/Float64"),
2455 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v float64) ([]byte, error) {
2456 return []byte(`"called"`), nil
2457 })},
2458 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2459 want: `{"X":[null,false,"","called",{},[]]}`,
2460 }, {
2461 name: name("Interfaces/Any/MarshalFunc/MapStringAny"),
2462 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v map[string]any) ([]byte, error) {
2463 return []byte(`"called"`), nil
2464 })},
2465 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2466 want: `{"X":[null,false,"",0,"called",[]]}`,
2467 }, {
2468 name: name("Interfaces/Any/MarshalFunc/SliceAny"),
2469 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v []any) ([]byte, error) {
2470 return []byte(`"called"`), nil
2471 })},
2472 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
2473 want: `{"X":"called"}`,
2474 }, {
2475 name: name("Interfaces/Any/MarshalFunc/Bytes"),
2476 mopts: MarshalOptions{Marshalers: MarshalFuncV1(func(v [8]byte) ([]byte, error) {
2477 return []byte(`"called"`), nil
2478 })},
2479 in: struct{ X any }{[8]byte{}},
2480 want: `{"X":"called"}`,
2481 }, {
2482 name: name("Interfaces/Any/Maps/Empty"),
2483 in: struct{ X any }{map[string]any{}},
2484 want: `{"X":{}}`,
2485 }, {
2486 name: name("Interfaces/Any/Maps/Empty/Multiline"),
2487 eopts: EncodeOptions{multiline: true},
2488 in: struct{ X any }{map[string]any{}},
2489 want: "{\n\"X\": {}\n}",
2490 }, {
2491 name: name("Interfaces/Any/Maps/NonEmpty"),
2492 in: struct{ X any }{map[string]any{"fizz": "buzz"}},
2493 want: `{"X":{"fizz":"buzz"}}`,
2494 }, {
2495 name: name("Interfaces/Any/Maps/Deterministic"),
2496 mopts: MarshalOptions{Deterministic: true},
2497 in: struct{ X any }{map[string]any{"alpha": "", "bravo": ""}},
2498 want: `{"X":{"alpha":"","bravo":""}}`,
2499 }, {
2500 name: name("Interfaces/Any/Maps/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
2501 mopts: MarshalOptions{Deterministic: true},
2502 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: false},
2503 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
2504 want: `{"X":{"�":""`,
2505 wantErr: &SyntacticError{str: `duplicate name "�" in object`},
2506 }, {
2507 name: name("Interfaces/Any/Maps/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
2508 mopts: MarshalOptions{Deterministic: true},
2509 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true},
2510 in: struct{ X any }{map[string]any{"\xff": "alpha", "\xfe": "bravo"}},
2511 want: `{"X":{"�":"bravo","�":"alpha"}}`,
2512 }, {
2513 name: name("Interfaces/Any/Maps/RejectInvalidUTF8"),
2514 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
2515 want: `{"X":{`,
2516 wantErr: &SyntacticError{str: "invalid UTF-8 within string"},
2517 }, {
2518 name: name("Interfaces/Any/Maps/AllowInvalidUTF8+RejectDuplicateNames"),
2519 eopts: EncodeOptions{AllowInvalidUTF8: true},
2520 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
2521 want: `{"X":{"�":""`,
2522 wantErr: &SyntacticError{str: `duplicate name "�" in object`},
2523 }, {
2524 name: name("Interfaces/Any/Maps/AllowInvalidUTF8+AllowDuplicateNames"),
2525 eopts: EncodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true},
2526 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
2527 want: `{"X":{"�":"","�":""}}`,
2528 }, {
2529 name: name("Interfaces/Any/Maps/Cyclic"),
2530 in: func() any {
2531 m := map[string]any{}
2532 m[""] = m
2533 return struct{ X any }{m}
2534 }(),
2535 want: `{"X"` + strings.Repeat(`:{""`, startDetectingCyclesAfter),
2536 wantErr: &SemanticError{action: "marshal", GoType: mapStringAnyType, Err: errors.New("encountered a cycle")},
2537 }, {
2538 name: name("Interfaces/Any/Slices/Empty"),
2539 in: struct{ X any }{[]any{}},
2540 want: `{"X":[]}`,
2541 }, {
2542 name: name("Interfaces/Any/Slices/Empty/Multiline"),
2543 eopts: EncodeOptions{multiline: true},
2544 in: struct{ X any }{[]any{}},
2545 want: "{\n\"X\": []\n}",
2546 }, {
2547 name: name("Interfaces/Any/Slices/NonEmpty"),
2548 in: struct{ X any }{[]any{"fizz", "buzz"}},
2549 want: `{"X":["fizz","buzz"]}`,
2550 }, {
2551 name: name("Interfaces/Any/Slices/Cyclic"),
2552 in: func() any {
2553 s := make([]any, 1)
2554 s[0] = s
2555 return struct{ X any }{s}
2556 }(),
2557 want: `{"X":` + strings.Repeat(`[`, startDetectingCyclesAfter),
2558 wantErr: &SemanticError{action: "marshal", GoType: sliceAnyType, Err: errors.New("encountered a cycle")},
2559 }, {
2560 name: name("Methods/NilPointer"),
2561 in: struct{ X *allMethods }{X: (*allMethods)(nil)}, // method should not be called
2562 want: `{"X":null}`,
2563 }, {
2564 // NOTE: Fixes https://github.com/dominikh/go-tools/issues/975.
2565 name: name("Methods/NilInterface"),
2566 in: struct{ X MarshalerV2 }{X: (*allMethods)(nil)}, // method should not be called
2567 want: `{"X":null}`,
2568 }, {
2569 name: name("Methods/AllMethods"),
2570 in: struct{ X *allMethods }{X: &allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)}},
2571 want: `{"X":"hello"}`,
2572 }, {
2573 name: name("Methods/AllMethodsExceptJSONv2"),
2574 in: struct{ X *allMethodsExceptJSONv2 }{X: &allMethodsExceptJSONv2{allMethods: allMethods{method: "MarshalJSON", value: []byte(`"hello"`)}}},
2575 want: `{"X":"hello"}`,
2576 }, {
2577 name: name("Methods/AllMethodsExceptJSONv1"),
2578 in: struct{ X *allMethodsExceptJSONv1 }{X: &allMethodsExceptJSONv1{allMethods: allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)}}},
2579 want: `{"X":"hello"}`,
2580 }, {
2581 name: name("Methods/AllMethodsExceptText"),
2582 in: struct{ X *allMethodsExceptText }{X: &allMethodsExceptText{allMethods: allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)}}},
2583 want: `{"X":"hello"}`,
2584 }, {
2585 name: name("Methods/OnlyMethodJSONv2"),
2586 in: struct{ X *onlyMethodJSONv2 }{X: &onlyMethodJSONv2{allMethods: allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)}}},
2587 want: `{"X":"hello"}`,
2588 }, {
2589 name: name("Methods/OnlyMethodJSONv1"),
2590 in: struct{ X *onlyMethodJSONv1 }{X: &onlyMethodJSONv1{allMethods: allMethods{method: "MarshalJSON", value: []byte(`"hello"`)}}},
2591 want: `{"X":"hello"}`,
2592 }, {
2593 name: name("Methods/OnlyMethodText"),
2594 in: struct{ X *onlyMethodText }{X: &onlyMethodText{allMethods: allMethods{method: "MarshalText", value: []byte(`hello`)}}},
2595 want: `{"X":"hello"}`,
2596 }, {
2597 name: name("Methods/IP"),
2598 in: net.IPv4(192, 168, 0, 100),
2599 want: `"192.168.0.100"`,
2600 }, {
2601 // NOTE: Fixes https://go.dev/issue/46516.
2602 name: name("Methods/Anonymous"),
2603 in: struct{ X struct{ allMethods } }{X: struct{ allMethods }{allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)}}},
2604 want: `{"X":"hello"}`,
2605 }, {
2606 // NOTE: Fixes https://go.dev/issue/22967.
2607 name: name("Methods/Addressable"),
2608 in: struct {
2609 V allMethods
2610 M map[string]allMethods
2611 I any
2612 }{
2613 V: allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)},
2614 M: map[string]allMethods{"K": {method: "MarshalNextJSON", value: []byte(`"hello"`)}},
2615 I: allMethods{method: "MarshalNextJSON", value: []byte(`"hello"`)},
2616 },
2617 want: `{"V":"hello","M":{"K":"hello"},"I":"hello"}`,
2618 }, {
2619 // NOTE: Fixes https://go.dev/issue/29732.
2620 name: name("Methods/MapKey/JSONv2"),
2621 in: map[structMethodJSONv2]string{{"k1"}: "v1", {"k2"}: "v2"},
2622 want: `{"k1":"v1","k2":"v2"}`,
2623 canonicalize: true,
2624 }, {
2625 // NOTE: Fixes https://go.dev/issue/29732.
2626 name: name("Methods/MapKey/JSONv1"),
2627 in: map[structMethodJSONv1]string{{"k1"}: "v1", {"k2"}: "v2"},
2628 want: `{"k1":"v1","k2":"v2"}`,
2629 canonicalize: true,
2630 }, {
2631 name: name("Methods/MapKey/Text"),
2632 in: map[structMethodText]string{{"k1"}: "v1", {"k2"}: "v2"},
2633 want: `{"k1":"v1","k2":"v2"}`,
2634 canonicalize: true,
2635 }, {
2636 name: name("Methods/Invalid/JSONv2/Error"),
2637 in: marshalJSONv2Func(func(MarshalOptions, *Encoder) error {
2638 return errors.New("some error")
2639 }),
2640 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv2FuncType, Err: errors.New("some error")},
2641 }, {
2642 name: name("Methods/Invalid/JSONv2/TooFew"),
2643 in: marshalJSONv2Func(func(MarshalOptions, *Encoder) error {
2644 return nil // do nothing
2645 }),
2646 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv2FuncType, Err: errors.New("must write exactly one JSON value")},
2647 }, {
2648 name: name("Methods/Invalid/JSONv2/TooMany"),
2649 in: marshalJSONv2Func(func(mo MarshalOptions, enc *Encoder) error {
2650 enc.WriteToken(Null)
2651 enc.WriteToken(Null)
2652 return nil
2653 }),
2654 want: `nullnull`,
2655 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv2FuncType, Err: errors.New("must write exactly one JSON value")},
2656 }, {
2657 name: name("Methods/Invalid/JSONv2/SkipFunc"),
2658 in: marshalJSONv2Func(func(mo MarshalOptions, enc *Encoder) error {
2659 return SkipFunc
2660 }),
2661 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv2FuncType, Err: errors.New("marshal method cannot be skipped")},
2662 }, {
2663 name: name("Methods/Invalid/JSONv1/Error"),
2664 in: marshalJSONv1Func(func() ([]byte, error) {
2665 return nil, errors.New("some error")
2666 }),
2667 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv1FuncType, Err: errors.New("some error")},
2668 }, {
2669 name: name("Methods/Invalid/JSONv1/Syntax"),
2670 in: marshalJSONv1Func(func() ([]byte, error) {
2671 return []byte("invalid"), nil
2672 }),
2673 wantErr: &SemanticError{action: "marshal", JSONKind: 'i', GoType: marshalJSONv1FuncType, Err: newInvalidCharacterError([]byte("i"), "at start of value")},
2674 }, {
2675 name: name("Methods/Invalid/JSONv1/SkipFunc"),
2676 in: marshalJSONv1Func(func() ([]byte, error) {
2677 return nil, SkipFunc
2678 }),
2679 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv1FuncType, Err: errors.New("marshal method cannot be skipped")},
2680 }, {
2681 name: name("Methods/Invalid/Text/Error"),
2682 in: marshalTextFunc(func() ([]byte, error) {
2683 return nil, errors.New("some error")
2684 }),
2685 wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: marshalTextFuncType, Err: errors.New("some error")},
2686 }, {
2687 name: name("Methods/Invalid/Text/UTF8"),
2688 in: marshalTextFunc(func() ([]byte, error) {
2689 return []byte("\xde\xad\xbe\xef"), nil
2690 }),
2691 wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: marshalTextFuncType, Err: &SyntacticError{str: "invalid UTF-8 within string"}},
2692 }, {
2693 name: name("Methods/Invalid/Text/SkipFunc"),
2694 in: marshalTextFunc(func() ([]byte, error) {
2695 return nil, SkipFunc
2696 }),
2697 wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: marshalTextFuncType, Err: errors.New("marshal method cannot be skipped")},
2698 }, {
2699 name: name("Methods/Invalid/MapKey/JSONv2/Syntax"),
2700 in: map[any]string{
2701 addr(marshalJSONv2Func(func(mo MarshalOptions, enc *Encoder) error {
2702 return enc.WriteToken(Null)
2703 })): "invalid",
2704 },
2705 want: `{`,
2706 wantErr: &SemanticError{action: "marshal", GoType: marshalJSONv2FuncType, Err: errMissingName},
2707 }, {
2708 name: name("Methods/Invalid/MapKey/JSONv1/Syntax"),
2709 in: map[any]string{
2710 addr(marshalJSONv1Func(func() ([]byte, error) {
2711 return []byte(`null`), nil
2712 })): "invalid",
2713 },
2714 want: `{`,
2715 wantErr: &SemanticError{action: "marshal", JSONKind: 'n', GoType: marshalJSONv1FuncType, Err: errMissingName},
2716 }, {
2717 name: name("Functions/Bool/V1"),
2718 mopts: MarshalOptions{
2719 Marshalers: MarshalFuncV1(func(bool) ([]byte, error) {
2720 return []byte(`"called"`), nil
2721 }),
2722 },
2723 in: true,
2724 want: `"called"`,
2725 }, {
2726 name: name("Functions/NamedBool/V1/NoMatch"),
2727 mopts: MarshalOptions{
2728 Marshalers: MarshalFuncV1(func(namedBool) ([]byte, error) {
2729 return nil, errors.New("must not be called")
2730 }),
2731 },
2732 in: true,
2733 want: `true`,
2734 }, {
2735 name: name("Functions/NamedBool/V1/Match"),
2736 mopts: MarshalOptions{
2737 Marshalers: MarshalFuncV1(func(namedBool) ([]byte, error) {
2738 return []byte(`"called"`), nil
2739 }),
2740 },
2741 in: namedBool(true),
2742 want: `"called"`,
2743 }, {
2744 name: name("Functions/PointerBool/V1/Match"),
2745 mopts: MarshalOptions{
2746 Marshalers: MarshalFuncV1(func(v *bool) ([]byte, error) {
2747 _ = *v // must be a non-nil pointer
2748 return []byte(`"called"`), nil
2749 }),
2750 },
2751 in: true,
2752 want: `"called"`,
2753 }, {
2754 name: name("Functions/Bool/V2"),
2755 mopts: MarshalOptions{
2756 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2757 return enc.WriteToken(String("called"))
2758 }),
2759 },
2760 in: true,
2761 want: `"called"`,
2762 }, {
2763 name: name("Functions/NamedBool/V2/NoMatch"),
2764 mopts: MarshalOptions{
2765 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v namedBool) error {
2766 return errors.New("must not be called")
2767 }),
2768 },
2769 in: true,
2770 want: `true`,
2771 }, {
2772 name: name("Functions/NamedBool/V2/Match"),
2773 mopts: MarshalOptions{
2774 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v namedBool) error {
2775 return enc.WriteToken(String("called"))
2776 }),
2777 },
2778 in: namedBool(true),
2779 want: `"called"`,
2780 }, {
2781 name: name("Functions/PointerBool/V2/Match"),
2782 mopts: MarshalOptions{
2783 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *bool) error {
2784 _ = *v // must be a non-nil pointer
2785 return enc.WriteToken(String("called"))
2786 }),
2787 },
2788 in: true,
2789 want: `"called"`,
2790 }, {
2791 name: name("Functions/Bool/Empty1/NoMatch"),
2792 mopts: MarshalOptions{
2793 Marshalers: new(Marshalers),
2794 },
2795 in: true,
2796 want: `true`,
2797 }, {
2798 name: name("Functions/Bool/Empty2/NoMatch"),
2799 mopts: MarshalOptions{
2800 Marshalers: NewMarshalers(),
2801 },
2802 in: true,
2803 want: `true`,
2804 }, {
2805 name: name("Functions/Bool/V1/DirectError"),
2806 mopts: MarshalOptions{
2807 Marshalers: MarshalFuncV1(func(bool) ([]byte, error) {
2808 return nil, errors.New("some error")
2809 }),
2810 },
2811 in: true,
2812 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("some error")},
2813 }, {
2814 name: name("Functions/Bool/V1/SkipError"),
2815 mopts: MarshalOptions{
2816 Marshalers: MarshalFuncV1(func(bool) ([]byte, error) {
2817 return nil, SkipFunc
2818 }),
2819 },
2820 in: true,
2821 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("marshal function of type func(T) ([]byte, error) cannot be skipped")},
2822 }, {
2823 name: name("Functions/Bool/V1/InvalidValue"),
2824 mopts: MarshalOptions{
2825 Marshalers: MarshalFuncV1(func(bool) ([]byte, error) {
2826 return []byte("invalid"), nil
2827 }),
2828 },
2829 in: true,
2830 wantErr: &SemanticError{action: "marshal", JSONKind: 'i', GoType: boolType, Err: &SyntacticError{str: "invalid character 'i' at start of value"}},
2831 }, {
2832 name: name("Functions/Bool/V2/DirectError"),
2833 mopts: MarshalOptions{
2834 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2835 return errors.New("some error")
2836 }),
2837 },
2838 in: true,
2839 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("some error")},
2840 }, {
2841 name: name("Functions/Bool/V2/TooFew"),
2842 mopts: MarshalOptions{
2843 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2844 return nil
2845 }),
2846 },
2847 in: true,
2848 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("must write exactly one JSON value")},
2849 }, {
2850 name: name("Functions/Bool/V2/TooMany"),
2851 mopts: MarshalOptions{
2852 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2853 enc.WriteValue([]byte(`"hello"`))
2854 enc.WriteValue([]byte(`"world"`))
2855 return nil
2856 }),
2857 },
2858 in: true,
2859 want: `"hello""world"`,
2860 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("must write exactly one JSON value")},
2861 }, {
2862 name: name("Functions/Bool/V2/Skipped"),
2863 mopts: MarshalOptions{
2864 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2865 return SkipFunc
2866 }),
2867 },
2868 in: true,
2869 want: `true`,
2870 }, {
2871 name: name("Functions/Bool/V2/ProcessBeforeSkip"),
2872 mopts: MarshalOptions{
2873 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2874 enc.WriteValue([]byte(`"hello"`))
2875 return SkipFunc
2876 }),
2877 },
2878 in: true,
2879 want: `"hello"`,
2880 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: errors.New("must not write any JSON tokens when skipping")},
2881 }, {
2882 name: name("Functions/Bool/V2/WrappedSkipError"),
2883 mopts: MarshalOptions{
2884 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
2885 return fmt.Errorf("wrap: %w", SkipFunc)
2886 }),
2887 },
2888 in: true,
2889 wantErr: &SemanticError{action: "marshal", GoType: boolType, Err: fmt.Errorf("wrap: %w", SkipFunc)},
2890 }, {
2891 name: name("Functions/Map/Key/NoCaseString/V1"),
2892 mopts: MarshalOptions{
2893 Marshalers: MarshalFuncV1(func(v nocaseString) ([]byte, error) {
2894 return []byte(`"called"`), nil
2895 }),
2896 },
2897 in: map[nocaseString]string{"hello": "world"},
2898 want: `{"called":"world"}`,
2899 }, {
2900 name: name("Functions/Map/Key/PointerNoCaseString/V1"),
2901 mopts: MarshalOptions{
2902 Marshalers: MarshalFuncV1(func(v *nocaseString) ([]byte, error) {
2903 _ = *v // must be a non-nil pointer
2904 return []byte(`"called"`), nil
2905 }),
2906 },
2907 in: map[nocaseString]string{"hello": "world"},
2908 want: `{"called":"world"}`,
2909 }, {
2910 name: name("Functions/Map/Key/TextMarshaler/V1"),
2911 mopts: MarshalOptions{
2912 Marshalers: MarshalFuncV1(func(v encoding.TextMarshaler) ([]byte, error) {
2913 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
2914 return []byte(`"called"`), nil
2915 }),
2916 },
2917 in: map[nocaseString]string{"hello": "world"},
2918 want: `{"called":"world"}`,
2919 }, {
2920 name: name("Functions/Map/Key/NoCaseString/V1/InvalidValue"),
2921 mopts: MarshalOptions{
2922 Marshalers: MarshalFuncV1(func(v nocaseString) ([]byte, error) {
2923 return []byte(`null`), nil
2924 }),
2925 },
2926 in: map[nocaseString]string{"hello": "world"},
2927 want: `{`,
2928 wantErr: &SemanticError{action: "marshal", JSONKind: 'n', GoType: nocaseStringType, Err: errMissingName},
2929 }, {
2930 name: name("Functions/Map/Key/NoCaseString/V2/InvalidKind"),
2931 mopts: MarshalOptions{
2932 Marshalers: MarshalFuncV1(func(v nocaseString) ([]byte, error) {
2933 return []byte(`null`), nil
2934 }),
2935 },
2936 in: map[nocaseString]string{"hello": "world"},
2937 want: `{`,
2938 wantErr: &SemanticError{action: "marshal", JSONKind: 'n', GoType: nocaseStringType, Err: errMissingName},
2939 }, {
2940 name: name("Functions/Map/Key/String/V1/DuplicateName"),
2941 mopts: MarshalOptions{
2942 Marshalers: MarshalFuncV1(func(v string) ([]byte, error) {
2943 return []byte(`"name"`), nil
2944 }),
2945 },
2946 in: map[string]string{"name1": "value", "name2": "value"},
2947 want: `{"name":"name"`,
2948 wantErr: &SemanticError{action: "marshal", JSONKind: '"', GoType: stringType, Err: &SyntacticError{str: `duplicate name "name" in object`}},
2949 }, {
2950 name: name("Functions/Map/Key/NoCaseString/V2"),
2951 mopts: MarshalOptions{
2952 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v nocaseString) error {
2953 return enc.WriteValue([]byte(`"called"`))
2954 }),
2955 },
2956 in: map[nocaseString]string{"hello": "world"},
2957 want: `{"called":"world"}`,
2958 }, {
2959 name: name("Functions/Map/Key/PointerNoCaseString/V2"),
2960 mopts: MarshalOptions{
2961 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *nocaseString) error {
2962 _ = *v // must be a non-nil pointer
2963 return enc.WriteValue([]byte(`"called"`))
2964 }),
2965 },
2966 in: map[nocaseString]string{"hello": "world"},
2967 want: `{"called":"world"}`,
2968 }, {
2969 name: name("Functions/Map/Key/TextMarshaler/V2"),
2970 mopts: MarshalOptions{
2971 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v encoding.TextMarshaler) error {
2972 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
2973 return enc.WriteValue([]byte(`"called"`))
2974 }),
2975 },
2976 in: map[nocaseString]string{"hello": "world"},
2977 want: `{"called":"world"}`,
2978 }, {
2979 name: name("Functions/Map/Key/NoCaseString/V2/InvalidToken"),
2980 mopts: MarshalOptions{
2981 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v nocaseString) error {
2982 return enc.WriteToken(Null)
2983 }),
2984 },
2985 in: map[nocaseString]string{"hello": "world"},
2986 want: `{`,
2987 wantErr: &SemanticError{action: "marshal", GoType: nocaseStringType, Err: errMissingName},
2988 }, {
2989 name: name("Functions/Map/Key/NoCaseString/V2/InvalidValue"),
2990 mopts: MarshalOptions{
2991 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v nocaseString) error {
2992 return enc.WriteValue([]byte(`null`))
2993 }),
2994 },
2995 in: map[nocaseString]string{"hello": "world"},
2996 want: `{`,
2997 wantErr: &SemanticError{action: "marshal", GoType: nocaseStringType, Err: errMissingName},
2998 }, {
2999 name: name("Functions/Map/Value/NoCaseString/V1"),
3000 mopts: MarshalOptions{
3001 Marshalers: MarshalFuncV1(func(v nocaseString) ([]byte, error) {
3002 return []byte(`"called"`), nil
3003 }),
3004 },
3005 in: map[string]nocaseString{"hello": "world"},
3006 want: `{"hello":"called"}`,
3007 }, {
3008 name: name("Functions/Map/Value/PointerNoCaseString/V1"),
3009 mopts: MarshalOptions{
3010 Marshalers: MarshalFuncV1(func(v *nocaseString) ([]byte, error) {
3011 _ = *v // must be a non-nil pointer
3012 return []byte(`"called"`), nil
3013 }),
3014 },
3015 in: map[string]nocaseString{"hello": "world"},
3016 want: `{"hello":"called"}`,
3017 }, {
3018 name: name("Functions/Map/Value/TextMarshaler/V1"),
3019 mopts: MarshalOptions{
3020 Marshalers: MarshalFuncV1(func(v encoding.TextMarshaler) ([]byte, error) {
3021 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3022 return []byte(`"called"`), nil
3023 }),
3024 },
3025 in: map[string]nocaseString{"hello": "world"},
3026 want: `{"hello":"called"}`,
3027 }, {
3028 name: name("Functions/Map/Value/NoCaseString/V2"),
3029 mopts: MarshalOptions{
3030 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v nocaseString) error {
3031 return enc.WriteValue([]byte(`"called"`))
3032 }),
3033 },
3034 in: map[string]nocaseString{"hello": "world"},
3035 want: `{"hello":"called"}`,
3036 }, {
3037 name: name("Functions/Map/Value/PointerNoCaseString/V2"),
3038 mopts: MarshalOptions{
3039 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *nocaseString) error {
3040 _ = *v // must be a non-nil pointer
3041 return enc.WriteValue([]byte(`"called"`))
3042 }),
3043 },
3044 in: map[string]nocaseString{"hello": "world"},
3045 want: `{"hello":"called"}`,
3046 }, {
3047 name: name("Functions/Map/Value/TextMarshaler/V2"),
3048 mopts: MarshalOptions{
3049 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v encoding.TextMarshaler) error {
3050 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3051 return enc.WriteValue([]byte(`"called"`))
3052 }),
3053 },
3054 in: map[string]nocaseString{"hello": "world"},
3055 want: `{"hello":"called"}`,
3056 }, {
3057 name: name("Funtions/Struct/Fields"),
3058 mopts: MarshalOptions{
3059 Marshalers: NewMarshalers(
3060 MarshalFuncV1(func(v bool) ([]byte, error) {
3061 return []byte(`"called1"`), nil
3062 }),
3063 MarshalFuncV1(func(v *string) ([]byte, error) {
3064 return []byte(`"called2"`), nil
3065 }),
3066 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v []byte) error {
3067 return enc.WriteValue([]byte(`"called3"`))
3068 }),
3069 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *int64) error {
3070 return enc.WriteValue([]byte(`"called4"`))
3071 }),
3072 ),
3073 },
3074 in: structScalars{},
3075 want: `{"Bool":"called1","String":"called2","Bytes":"called3","Int":"called4","Uint":0,"Float":0}`,
3076 }, {
3077 name: name("Functions/Struct/OmitEmpty"),
3078 mopts: MarshalOptions{
3079 Marshalers: NewMarshalers(
3080 MarshalFuncV1(func(v bool) ([]byte, error) {
3081 return []byte(`null`), nil
3082 }),
3083 MarshalFuncV1(func(v string) ([]byte, error) {
3084 return []byte(`"called1"`), nil
3085 }),
3086 MarshalFuncV1(func(v *stringMarshalNonEmpty) ([]byte, error) {
3087 return []byte(`""`), nil
3088 }),
3089 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bytesMarshalNonEmpty) error {
3090 return enc.WriteValue([]byte(`{}`))
3091 }),
3092 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *float64) error {
3093 return enc.WriteValue([]byte(`[]`))
3094 }),
3095 MarshalFuncV1(func(v mapMarshalNonEmpty) ([]byte, error) {
3096 return []byte(`"called2"`), nil
3097 }),
3098 MarshalFuncV1(func(v []string) ([]byte, error) {
3099 return []byte(`"called3"`), nil
3100 }),
3101 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *sliceMarshalNonEmpty) error {
3102 return enc.WriteValue([]byte(`"called4"`))
3103 }),
3104 ),
3105 },
3106 in: structOmitEmptyAll{},
3107 want: `{"String":"called1","MapNonEmpty":"called2","Slice":"called3","SliceNonEmpty":"called4"}`,
3108 }, {
3109 name: name("Functions/Struct/OmitZero"),
3110 mopts: MarshalOptions{
3111 Marshalers: NewMarshalers(
3112 MarshalFuncV1(func(v bool) ([]byte, error) {
3113 panic("should not be called")
3114 }),
3115 MarshalFuncV1(func(v *string) ([]byte, error) {
3116 panic("should not be called")
3117 }),
3118 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v []byte) error {
3119 panic("should not be called")
3120 }),
3121 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *int64) error {
3122 panic("should not be called")
3123 }),
3124 ),
3125 },
3126 in: structOmitZeroAll{},
3127 want: `{}`,
3128 }, {
3129 name: name("Functions/Struct/Inlined"),
3130 mopts: MarshalOptions{
3131 Marshalers: NewMarshalers(
3132 MarshalFuncV1(func(v structInlinedL1) ([]byte, error) {
3133 panic("should not be called")
3134 }),
3135 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *StructEmbed2) error {
3136 panic("should not be called")
3137 }),
3138 ),
3139 },
3140 in: structInlined{},
3141 want: `{"D":""}`,
3142 }, {
3143 name: name("Functions/Slice/Elem"),
3144 mopts: MarshalOptions{
3145 Marshalers: MarshalFuncV1(func(v bool) ([]byte, error) {
3146 return []byte(`"` + strconv.FormatBool(v) + `"`), nil
3147 }),
3148 },
3149 in: []bool{true, false},
3150 want: `["true","false"]`,
3151 }, {
3152 name: name("Functions/Array/Elem"),
3153 mopts: MarshalOptions{
3154 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *bool) error {
3155 return enc.WriteValue([]byte(`"` + strconv.FormatBool(*v) + `"`))
3156 }),
3157 },
3158 in: [2]bool{true, false},
3159 want: `["true","false"]`,
3160 }, {
3161 name: name("Functions/Pointer/Nil"),
3162 mopts: MarshalOptions{
3163 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *bool) error {
3164 panic("should not be called")
3165 }),
3166 },
3167 in: struct{ X *bool }{nil},
3168 want: `{"X":null}`,
3169 }, {
3170 name: name("Functions/Pointer/NonNil"),
3171 mopts: MarshalOptions{
3172 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *bool) error {
3173 return enc.WriteValue([]byte(`"called"`))
3174 }),
3175 },
3176 in: struct{ X *bool }{addr(false)},
3177 want: `{"X":"called"}`,
3178 }, {
3179 name: name("Functions/Interface/Nil"),
3180 mopts: MarshalOptions{
3181 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v fmt.Stringer) error {
3182 panic("should not be called")
3183 }),
3184 },
3185 in: struct{ X fmt.Stringer }{nil},
3186 want: `{"X":null}`,
3187 }, {
3188 name: name("Functions/Interface/NonNil/MatchInterface"),
3189 mopts: MarshalOptions{
3190 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v fmt.Stringer) error {
3191 return enc.WriteValue([]byte(`"called"`))
3192 }),
3193 },
3194 in: struct{ X fmt.Stringer }{valueStringer{}},
3195 want: `{"X":"called"}`,
3196 }, {
3197 name: name("Functions/Interface/NonNil/MatchConcrete"),
3198 mopts: MarshalOptions{
3199 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v valueStringer) error {
3200 return enc.WriteValue([]byte(`"called"`))
3201 }),
3202 },
3203 in: struct{ X fmt.Stringer }{valueStringer{}},
3204 want: `{"X":"called"}`,
3205 }, {
3206 name: name("Functions/Interface/NonNil/MatchPointer"),
3207 mopts: MarshalOptions{
3208 Marshalers: MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *valueStringer) error {
3209 return enc.WriteValue([]byte(`"called"`))
3210 }),
3211 },
3212 in: struct{ X fmt.Stringer }{valueStringer{}},
3213 want: `{"X":"called"}`,
3214 }, {
3215 name: name("Functions/Interface/Any"),
3216 in: []any{
3217 nil, // nil
3218 valueStringer{}, // T
3219 (*valueStringer)(nil), // *T
3220 addr(valueStringer{}), // *T
3221 (**valueStringer)(nil), // **T
3222 addr((*valueStringer)(nil)), // **T
3223 addr(addr(valueStringer{})), // **T
3224 pointerStringer{}, // T
3225 (*pointerStringer)(nil), // *T
3226 addr(pointerStringer{}), // *T
3227 (**pointerStringer)(nil), // **T
3228 addr((*pointerStringer)(nil)), // **T
3229 addr(addr(pointerStringer{})), // **T
3230 "LAST",
3231 },
3232 want: `[null,{},null,{},null,null,{},{},null,{},null,null,{},"LAST"]`,
3233 mopts: MarshalOptions{
3234 Marshalers: func() *Marshalers {
3235 type P [2]int
3236 type PV struct {
3237 P P
3238 V any
3239 }
3240
3241 var lastChecks []func() error
3242 checkLast := func() error {
3243 for _, fn := range lastChecks {
3244 if err := fn(); err != nil {
3245 return err
3246 }
3247 }
3248 return SkipFunc
3249 }
3250 makeValueChecker := func(name string, want []PV) func(e *Encoder, v any) error {
3251 checkNext := func(e *Encoder, v any) error {
3252 p := P{len(e.tokens.stack), e.tokens.last.length()}
3253 rv := reflect.ValueOf(v)
3254 pv := PV{p, v}
3255 switch {
3256 case len(want) == 0:
3257 return fmt.Errorf("%s: %v: got more values than expected", name, p)
3258 case !rv.IsValid() || rv.Kind() != reflect.Pointer || rv.IsNil():
3259 return fmt.Errorf("%s: %v: got %#v, want non-nil pointer type", name, p, v)
3260 case !reflect.DeepEqual(pv, want[0]):
3261 return fmt.Errorf("%s:\n\tgot %#v\n\twant %#v", name, pv, want[0])
3262 default:
3263 want = want[1:]
3264 return SkipFunc
3265 }
3266 }
3267 lastChecks = append(lastChecks, func() error {
3268 if len(want) > 0 {
3269 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
3270 }
3271 return nil
3272 })
3273 return checkNext
3274 }
3275 makePositionChecker := func(name string, want []P) func(e *Encoder, v any) error {
3276 checkNext := func(e *Encoder, v any) error {
3277 p := P{len(e.tokens.stack), e.tokens.last.length()}
3278 switch {
3279 case len(want) == 0:
3280 return fmt.Errorf("%s: %v: got more values than wanted", name, p)
3281 case p != want[0]:
3282 return fmt.Errorf("%s: got %v, want %v", name, p, want[0])
3283 default:
3284 want = want[1:]
3285 return SkipFunc
3286 }
3287 }
3288 lastChecks = append(lastChecks, func() error {
3289 if len(want) > 0 {
3290 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
3291 }
3292 return nil
3293 })
3294 return checkNext
3295 }
3296
3297 wantAny := []PV{
3298 {P{0, 0}, addr([]any{
3299 nil,
3300 valueStringer{},
3301 (*valueStringer)(nil),
3302 addr(valueStringer{}),
3303 (**valueStringer)(nil),
3304 addr((*valueStringer)(nil)),
3305 addr(addr(valueStringer{})),
3306 pointerStringer{},
3307 (*pointerStringer)(nil),
3308 addr(pointerStringer{}),
3309 (**pointerStringer)(nil),
3310 addr((*pointerStringer)(nil)),
3311 addr(addr(pointerStringer{})),
3312 "LAST",
3313 })},
3314 {P{1, 0}, addr(any(nil))},
3315 {P{1, 1}, addr(any(valueStringer{}))},
3316 {P{1, 1}, addr(valueStringer{})},
3317 {P{1, 2}, addr(any((*valueStringer)(nil)))},
3318 {P{1, 2}, addr((*valueStringer)(nil))},
3319 {P{1, 3}, addr(any(addr(valueStringer{})))},
3320 {P{1, 3}, addr(addr(valueStringer{}))},
3321 {P{1, 3}, addr(valueStringer{})},
3322 {P{1, 4}, addr(any((**valueStringer)(nil)))},
3323 {P{1, 4}, addr((**valueStringer)(nil))},
3324 {P{1, 5}, addr(any(addr((*valueStringer)(nil))))},
3325 {P{1, 5}, addr(addr((*valueStringer)(nil)))},
3326 {P{1, 5}, addr((*valueStringer)(nil))},
3327 {P{1, 6}, addr(any(addr(addr(valueStringer{}))))},
3328 {P{1, 6}, addr(addr(addr(valueStringer{})))},
3329 {P{1, 6}, addr(addr(valueStringer{}))},
3330 {P{1, 6}, addr(valueStringer{})},
3331 {P{1, 7}, addr(any(pointerStringer{}))},
3332 {P{1, 7}, addr(pointerStringer{})},
3333 {P{1, 8}, addr(any((*pointerStringer)(nil)))},
3334 {P{1, 8}, addr((*pointerStringer)(nil))},
3335 {P{1, 9}, addr(any(addr(pointerStringer{})))},
3336 {P{1, 9}, addr(addr(pointerStringer{}))},
3337 {P{1, 9}, addr(pointerStringer{})},
3338 {P{1, 10}, addr(any((**pointerStringer)(nil)))},
3339 {P{1, 10}, addr((**pointerStringer)(nil))},
3340 {P{1, 11}, addr(any(addr((*pointerStringer)(nil))))},
3341 {P{1, 11}, addr(addr((*pointerStringer)(nil)))},
3342 {P{1, 11}, addr((*pointerStringer)(nil))},
3343 {P{1, 12}, addr(any(addr(addr(pointerStringer{}))))},
3344 {P{1, 12}, addr(addr(addr(pointerStringer{})))},
3345 {P{1, 12}, addr(addr(pointerStringer{}))},
3346 {P{1, 12}, addr(pointerStringer{})},
3347 {P{1, 13}, addr(any("LAST"))},
3348 {P{1, 13}, addr("LAST")},
3349 }
3350 checkAny := makeValueChecker("any", wantAny)
3351 anyMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v any) error {
3352 return checkAny(enc, v)
3353 })
3354
3355 var wantPointerAny []PV
3356 for _, v := range wantAny {
3357 if _, ok := v.V.(*any); ok {
3358 wantPointerAny = append(wantPointerAny, v)
3359 }
3360 }
3361 checkPointerAny := makeValueChecker("*any", wantPointerAny)
3362 pointerAnyMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *any) error {
3363 return checkPointerAny(enc, v)
3364 })
3365
3366 checkNamedAny := makeValueChecker("namedAny", wantAny)
3367 namedAnyMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v namedAny) error {
3368 return checkNamedAny(enc, v)
3369 })
3370
3371 checkPointerNamedAny := makeValueChecker("*namedAny", nil)
3372 pointerNamedAnyMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *namedAny) error {
3373 return checkPointerNamedAny(enc, v)
3374 })
3375
3376 type stringer = fmt.Stringer
3377 var wantStringer []PV
3378 for _, v := range wantAny {
3379 if _, ok := v.V.(stringer); ok {
3380 wantStringer = append(wantStringer, v)
3381 }
3382 }
3383 checkStringer := makeValueChecker("stringer", wantStringer)
3384 stringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v stringer) error {
3385 return checkStringer(enc, v)
3386 })
3387
3388 checkPointerStringer := makeValueChecker("*stringer", nil)
3389 pointerStringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *stringer) error {
3390 return checkPointerStringer(enc, v)
3391 })
3392
3393 wantValueStringer := []P{{1, 1}, {1, 3}, {1, 6}}
3394 checkValueValueStringer := makePositionChecker("valueStringer", wantValueStringer)
3395 valueValueStringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v valueStringer) error {
3396 return checkValueValueStringer(enc, v)
3397 })
3398
3399 checkPointerValueStringer := makePositionChecker("*valueStringer", wantValueStringer)
3400 pointerValueStringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *valueStringer) error {
3401 return checkPointerValueStringer(enc, v)
3402 })
3403
3404 wantPointerStringer := []P{{1, 7}, {1, 9}, {1, 12}}
3405 checkValuePointerStringer := makePositionChecker("pointerStringer", wantPointerStringer)
3406 valuePointerStringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v pointerStringer) error {
3407 return checkValuePointerStringer(enc, v)
3408 })
3409
3410 checkPointerPointerStringer := makePositionChecker("*pointerStringer", wantPointerStringer)
3411 pointerPointerStringerMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v *pointerStringer) error {
3412 return checkPointerPointerStringer(enc, v)
3413 })
3414
3415 lastMarshaler := MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v string) error {
3416 return checkLast()
3417 })
3418
3419 return NewMarshalers(
3420 anyMarshaler,
3421 pointerAnyMarshaler,
3422 namedAnyMarshaler,
3423 pointerNamedAnyMarshaler, // never called
3424 stringerMarshaler,
3425 pointerStringerMarshaler, // never called
3426 valueValueStringerMarshaler,
3427 pointerValueStringerMarshaler,
3428 valuePointerStringerMarshaler,
3429 pointerPointerStringerMarshaler,
3430 lastMarshaler,
3431 )
3432 }(),
3433 },
3434 }, {
3435 name: name("Functions/Precedence/V1First"),
3436 mopts: MarshalOptions{
3437 Marshalers: NewMarshalers(
3438 MarshalFuncV1(func(bool) ([]byte, error) {
3439 return []byte(`"called"`), nil
3440 }),
3441 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
3442 panic("should not be called")
3443 }),
3444 ),
3445 },
3446 in: true,
3447 want: `"called"`,
3448 }, {
3449 name: name("Functions/Precedence/V2First"),
3450 mopts: MarshalOptions{
3451 Marshalers: NewMarshalers(
3452 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
3453 return enc.WriteToken(String("called"))
3454 }),
3455 MarshalFuncV1(func(bool) ([]byte, error) {
3456 panic("should not be called")
3457 }),
3458 ),
3459 },
3460 in: true,
3461 want: `"called"`,
3462 }, {
3463 name: name("Functions/Precedence/V2Skipped"),
3464 mopts: MarshalOptions{
3465 Marshalers: NewMarshalers(
3466 MarshalFuncV2(func(mo MarshalOptions, enc *Encoder, v bool) error {
3467 return SkipFunc
3468 }),
3469 MarshalFuncV1(func(bool) ([]byte, error) {
3470 return []byte(`"called"`), nil
3471 }),
3472 ),
3473 },
3474 in: true,
3475 want: `"called"`,
3476 }, {
3477 name: name("Functions/Precedence/NestedFirst"),
3478 mopts: MarshalOptions{
3479 Marshalers: NewMarshalers(
3480 NewMarshalers(
3481 MarshalFuncV1(func(bool) ([]byte, error) {
3482 return []byte(`"called"`), nil
3483 }),
3484 ),
3485 MarshalFuncV1(func(bool) ([]byte, error) {
3486 panic("should not be called")
3487 }),
3488 ),
3489 },
3490 in: true,
3491 want: `"called"`,
3492 }, {
3493 name: name("Functions/Precedence/NestedLast"),
3494 mopts: MarshalOptions{
3495 Marshalers: NewMarshalers(
3496 MarshalFuncV1(func(bool) ([]byte, error) {
3497 return []byte(`"called"`), nil
3498 }),
3499 NewMarshalers(
3500 MarshalFuncV1(func(bool) ([]byte, error) {
3501 panic("should not be called")
3502 }),
3503 ),
3504 ),
3505 },
3506 in: true,
3507 want: `"called"`,
3508 }, {
3509 name: name("Duration/Zero"),
3510 in: struct {
3511 D1 time.Duration
3512 D2 time.Duration `json:",format:nanos"`
3513 }{0, 0},
3514 want: `{"D1":"0s","D2":0}`,
3515 }, {
3516 name: name("Duration/Positive"),
3517 in: struct {
3518 D1 time.Duration
3519 D2 time.Duration `json:",format:nanos"`
3520 }{
3521 123456789123456789,
3522 123456789123456789,
3523 },
3524 want: `{"D1":"34293h33m9.123456789s","D2":123456789123456789}`,
3525 }, {
3526 name: name("Duration/Negative"),
3527 in: struct {
3528 D1 time.Duration
3529 D2 time.Duration `json:",format:nanos"`
3530 }{
3531 -123456789123456789,
3532 -123456789123456789,
3533 },
3534 want: `{"D1":"-34293h33m9.123456789s","D2":-123456789123456789}`,
3535 }, {
3536 name: name("Duration/Nanos/String"),
3537 in: struct {
3538 D1 time.Duration `json:",string,format:nanos"`
3539 D2 time.Duration `json:",string,format:nanos"`
3540 D3 time.Duration `json:",string,format:nanos"`
3541 }{
3542 math.MinInt64,
3543 0,
3544 math.MaxInt64,
3545 },
3546 want: `{"D1":"-9223372036854775808","D2":"0","D3":"9223372036854775807"}`,
3547 }, {
3548 name: name("Duration/Format/Invalid"),
3549 in: struct {
3550 D time.Duration `json:",format:invalid"`
3551 }{},
3552 want: `{"D"`,
3553 wantErr: &SemanticError{action: "marshal", GoType: timeDurationType, Err: errors.New(`invalid format flag: "invalid"`)},
3554 }, {
3555 name: name("Duration/IgnoreInvalidFormat"),
3556 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
3557 in: time.Duration(0),
3558 want: `"0s"`,
3559 }, {
3560 name: name("Time/Zero"),
3561 in: struct {
3562 T1 time.Time
3563 T2 time.Time `json:",format:RFC822"`
3564 T3 time.Time `json:",format:'2006-01-02'"`
3565 T4 time.Time `json:",omitzero"`
3566 T5 time.Time `json:",omitempty"`
3567 }{
3568 time.Time{},
3569 time.Time{},
3570 time.Time{},
3571 // This is zero according to time.Time.IsZero,
3572 // but non-zero according to reflect.Value.IsZero.
3573 time.Date(1, 1, 1, 0, 0, 0, 0, time.FixedZone("UTC", 0)),
3574 time.Time{},
3575 },
3576 want: `{"T1":"0001-01-01T00:00:00Z","T2":"01 Jan 01 00:00 UTC","T3":"0001-01-01","T5":"0001-01-01T00:00:00Z"}`,
3577 }, {
3578 name: name("Time/Format"),
3579 eopts: EncodeOptions{Indent: "\t"},
3580 in: structTimeFormat{
3581 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3582 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3583 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3584 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3585 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3586 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3587 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3588 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3589 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3590 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3591 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3592 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3593 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3594 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3595 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3596 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3597 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3598 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
3599 },
3600 want: `{
3601 "T1": "1234-01-02T03:04:05.000000006Z",
3602 "T2": "Mon Jan 2 03:04:05 1234",
3603 "T3": "Mon Jan 2 03:04:05 UTC 1234",
3604 "T4": "Mon Jan 02 03:04:05 +0000 1234",
3605 "T5": "02 Jan 34 03:04 UTC",
3606 "T6": "02 Jan 34 03:04 +0000",
3607 "T7": "Monday, 02-Jan-34 03:04:05 UTC",
3608 "T8": "Mon, 02 Jan 1234 03:04:05 UTC",
3609 "T9": "Mon, 02 Jan 1234 03:04:05 +0000",
3610 "T10": "1234-01-02T03:04:05Z",
3611 "T11": "1234-01-02T03:04:05.000000006Z",
3612 "T12": "3:04AM",
3613 "T13": "Jan 2 03:04:05",
3614 "T14": "Jan 2 03:04:05.000",
3615 "T15": "Jan 2 03:04:05.000000",
3616 "T16": "Jan 2 03:04:05.000000006",
3617 "T17": "1234-01-02",
3618 "T18": "\"weird\"1234"
3619 }`,
3620 }, {
3621 name: name("Time/Format/Invalid"),
3622 in: struct {
3623 T time.Time `json:",format:UndefinedConstant"`
3624 }{},
3625 want: `{"T"`,
3626 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`undefined format layout: UndefinedConstant`)},
3627 }, {
3628 name: name("Time/Format/YearOverflow"),
3629 in: struct {
3630 T1 time.Time
3631 T2 time.Time
3632 }{
3633 time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second),
3634 time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC),
3635 },
3636 want: `{"T1":"9999-12-31T23:59:59Z","T2"`,
3637 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`year outside of range [0,9999]`)},
3638 }, {
3639 name: name("Time/Format/YearUnderflow"),
3640 in: struct {
3641 T1 time.Time
3642 T2 time.Time
3643 }{
3644 time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC),
3645 time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second),
3646 },
3647 want: `{"T1":"0000-01-01T00:00:00Z","T2"`,
3648 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`year outside of range [0,9999]`)},
3649 }, {
3650 name: name("Time/Format/YearUnderflow"),
3651 in: struct{ T time.Time }{time.Date(-998, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second)},
3652 want: `{"T"`,
3653 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`year outside of range [0,9999]`)},
3654 }, {
3655 name: name("Time/Format/ZoneExact"),
3656 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 23*60*60+59*60))},
3657 want: `{"T":"2020-01-01T00:00:00+23:59"}`,
3658 }, {
3659 name: name("Time/Format/ZoneHourOverflow"),
3660 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 24*60*60))},
3661 want: `{"T"`,
3662 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`timezone hour outside of range [0,23]`)},
3663 }, {
3664 name: name("Time/Format/ZoneHourOverflow"),
3665 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 123*60*60))},
3666 want: `{"T"`,
3667 wantErr: &SemanticError{action: "marshal", GoType: timeTimeType, Err: errors.New(`timezone hour outside of range [0,23]`)},
3668 }, {
3669 name: name("Time/IgnoreInvalidFormat"),
3670 mopts: MarshalOptions{formatDepth: 1000, format: "invalid"},
3671 in: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
3672 want: `"2000-01-01T00:00:00Z"`,
3673 }}
3674
3675 for _, tt := range tests {
3676 t.Run(tt.name.name, func(t *testing.T) {
•3677 if tt.name.name == "Structs/OmitEmpty/NonEmpty" || tt.name.name == "Structs/OmitZero/NonZero" {
3678 t.Skip("behavior changed in go1.22")
3679 }
3680 var got []byte
3681 var gotErr error
3682 if tt.useWriter {
3683 bb := new(struct{ bytes.Buffer }) // avoid optimizations with bytes.Buffer
3684 gotErr = tt.mopts.MarshalFull(tt.eopts, bb, tt.in)
3685 got = bb.Bytes()
3686 } else {
3687 got, gotErr = tt.mopts.Marshal(tt.eopts, tt.in)
3688 }
3689 if tt.canonicalize {
3690 (*RawValue)(&got).Canonicalize()
3691 }
3692 if string(got) != tt.want {
3693 t.Errorf("%s: Marshal output mismatch:\ngot %s\nwant %s", tt.name.where, got, tt.want)
3694 }
3695 if !reflect.DeepEqual(gotErr, tt.wantErr) {
3696 t.Errorf("%s: Marshal error mismatch:\ngot %v\nwant %v", tt.name.where, gotErr, tt.wantErr)
3697 }
3698 })
3699 }
3700 }
3701
3702 func TestUnmarshal(t *testing.T) {
3703 tests := []struct {
3704 name testName
3705 dopts DecodeOptions
3706 uopts UnmarshalOptions
3707 inBuf string
3708 inVal any
3709 want any
3710 wantErr error
3711 }{{
3712 name: name("Nil"),
3713 inBuf: `null`,
3714 wantErr: &SemanticError{action: "unmarshal", Err: errors.New("value must be passed as a non-nil pointer reference")},
3715 }, {
3716 name: name("NilPointer"),
3717 inBuf: `null`,
3718 inVal: (*string)(nil),
3719 want: (*string)(nil),
3720 wantErr: &SemanticError{action: "unmarshal", GoType: stringType, Err: errors.New("value must be passed as a non-nil pointer reference")},
3721 }, {
3722 name: name("NonPointer"),
3723 inBuf: `null`,
3724 inVal: "unchanged",
3725 want: "unchanged",
3726 wantErr: &SemanticError{action: "unmarshal", GoType: stringType, Err: errors.New("value must be passed as a non-nil pointer reference")},
3727 }, {
3728 name: name("Bools/TrailingJunk"),
3729 inBuf: `falsetrue`,
3730 inVal: addr(true),
3731 want: addr(false),
3732 wantErr: newInvalidCharacterError([]byte("t"), "after top-level value"),
3733 }, {
3734 name: name("Bools/Null"),
3735 inBuf: `null`,
3736 inVal: addr(true),
3737 want: addr(false),
3738 }, {
3739 name: name("Bools"),
3740 inBuf: `[null,false,true]`,
3741 inVal: new([]bool),
3742 want: addr([]bool{false, false, true}),
3743 }, {
3744 name: name("Bools/Named"),
3745 inBuf: `[null,false,true]`,
3746 inVal: new([]namedBool),
3747 want: addr([]namedBool{false, false, true}),
3748 }, {
3749 name: name("Bools/Invalid/StringifiedFalse"),
3750 uopts: UnmarshalOptions{StringifyNumbers: true},
3751 inBuf: `"false"`,
3752 inVal: addr(true),
3753 want: addr(true),
3754 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: boolType},
3755 }, {
3756 name: name("Bools/Invalid/StringifiedTrue"),
3757 uopts: UnmarshalOptions{StringifyNumbers: true},
3758 inBuf: `"true"`,
3759 inVal: addr(true),
3760 want: addr(true),
3761 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: boolType},
3762 }, {
3763 name: name("Bools/Invalid/Number"),
3764 inBuf: `0`,
3765 inVal: addr(true),
3766 want: addr(true),
3767 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: boolType},
3768 }, {
3769 name: name("Bools/Invalid/String"),
3770 inBuf: `""`,
3771 inVal: addr(true),
3772 want: addr(true),
3773 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: boolType},
3774 }, {
3775 name: name("Bools/Invalid/Object"),
3776 inBuf: `{}`,
3777 inVal: addr(true),
3778 want: addr(true),
3779 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: boolType},
3780 }, {
3781 name: name("Bools/Invalid/Array"),
3782 inBuf: `[]`,
3783 inVal: addr(true),
3784 want: addr(true),
3785 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: boolType},
3786 }, {
3787 name: name("Bools/IgnoreInvalidFormat"),
3788 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
3789 inBuf: `false`,
3790 inVal: addr(true),
3791 want: addr(false),
3792 }, {
3793 name: name("Strings/Null"),
3794 inBuf: `null`,
3795 inVal: addr("something"),
3796 want: addr(""),
3797 }, {
3798 name: name("Strings"),
3799 inBuf: `[null,"","hello","世界"]`,
3800 inVal: new([]string),
3801 want: addr([]string{"", "", "hello", "世界"}),
3802 }, {
3803 name: name("Strings/Escaped"),
3804 inBuf: `[null,"","\u0068\u0065\u006c\u006c\u006f","\u4e16\u754c"]`,
3805 inVal: new([]string),
3806 want: addr([]string{"", "", "hello", "世界"}),
3807 }, {
3808 name: name("Strings/Named"),
3809 inBuf: `[null,"","hello","世界"]`,
3810 inVal: new([]namedString),
3811 want: addr([]namedString{"", "", "hello", "世界"}),
3812 }, {
3813 name: name("Strings/Invalid/False"),
3814 inBuf: `false`,
3815 inVal: addr("nochange"),
3816 want: addr("nochange"),
3817 wantErr: &SemanticError{action: "unmarshal", JSONKind: 'f', GoType: stringType},
3818 }, {
3819 name: name("Strings/Invalid/True"),
3820 inBuf: `true`,
3821 inVal: addr("nochange"),
3822 want: addr("nochange"),
3823 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: stringType},
3824 }, {
3825 name: name("Strings/Invalid/Object"),
3826 inBuf: `{}`,
3827 inVal: addr("nochange"),
3828 want: addr("nochange"),
3829 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: stringType},
3830 }, {
3831 name: name("Strings/Invalid/Array"),
3832 inBuf: `[]`,
3833 inVal: addr("nochange"),
3834 want: addr("nochange"),
3835 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: stringType},
3836 }, {
3837 name: name("Strings/IgnoreInvalidFormat"),
3838 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
3839 inBuf: `"hello"`,
3840 inVal: addr("goodbye"),
3841 want: addr("hello"),
3842 }, {
3843 name: name("Bytes/Null"),
3844 inBuf: `null`,
3845 inVal: addr([]byte("something")),
3846 want: addr([]byte(nil)),
3847 }, {
3848 name: name("Bytes"),
3849 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
3850 inVal: new([][]byte),
3851 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
3852 }, {
3853 name: name("Bytes/Large"),
3854 inBuf: `"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgYW5kIGF0ZSB0aGUgaG9tZXdvcmsgdGhhdCBJIHNwZW50IHNvIG11Y2ggdGltZSBvbi4="`,
3855 inVal: new([]byte),
3856 want: addr([]byte("the quick brown fox jumped over the lazy dog and ate the homework that I spent so much time on.")),
3857 }, {
3858 name: name("Bytes/Reuse"),
3859 inBuf: `"AQID"`,
3860 inVal: addr([]byte("changed")),
3861 want: addr([]byte{1, 2, 3}),
3862 }, {
3863 name: name("Bytes/Escaped"),
3864 inBuf: `[null,"","\u0041\u0051\u003d\u003d","\u0041\u0051\u0049\u003d","\u0041\u0051\u0049\u0044"]`,
3865 inVal: new([][]byte),
3866 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
3867 }, {
3868 name: name("Bytes/Named"),
3869 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
3870 inVal: new([]namedBytes),
3871 want: addr([]namedBytes{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
3872 }, {
3873 name: name("Bytes/NotStringified"),
3874 uopts: UnmarshalOptions{StringifyNumbers: true},
3875 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
3876 inVal: new([][]byte),
3877 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
3878 }, {
3879 // NOTE: []namedByte is not assignable to []byte,
3880 // so the following should be treated as a slice of uints.
3881 name: name("Bytes/Invariant"),
3882 inBuf: `[null,[],[1],[1,2],[1,2,3]]`,
3883 inVal: new([][]namedByte),
3884 want: addr([][]namedByte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
3885 }, {
3886 // NOTE: This differs in behavior from v1,
3887 // but keeps the representation of slices and arrays more consistent.
3888 name: name("Bytes/ByteArray"),
3889 inBuf: `"aGVsbG8="`,
3890 inVal: new([5]byte),
3891 want: addr([5]byte{'h', 'e', 'l', 'l', 'o'}),
3892 }, {
3893 name: name("Bytes/ByteArray0/Valid"),
3894 inBuf: `""`,
3895 inVal: new([0]byte),
3896 want: addr([0]byte{}),
3897 }, {
3898 name: name("Bytes/ByteArray0/Invalid"),
3899 inBuf: `"A"`,
3900 inVal: new([0]byte),
3901 want: addr([0]byte{}),
3902 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array0ByteType, Err: func() error {
3903 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("A"))
3904 return err
3905 }()},
3906 }, {
3907 name: name("Bytes/ByteArray0/Overflow"),
3908 inBuf: `"AA=="`,
3909 inVal: new([0]byte),
3910 want: addr([0]byte{}),
3911 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array0ByteType, Err: errors.New("decoded base64 length of 1 mismatches array length of 0")},
3912 }, {
3913 name: name("Bytes/ByteArray1/Valid"),
3914 inBuf: `"AQ=="`,
3915 inVal: new([1]byte),
3916 want: addr([1]byte{1}),
3917 }, {
3918 name: name("Bytes/ByteArray1/Invalid"),
3919 inBuf: `"$$=="`,
3920 inVal: new([1]byte),
3921 want: addr([1]byte{}),
3922 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array1ByteType, Err: func() error {
3923 _, err := base64.StdEncoding.Decode(make([]byte, 1), []byte("$$=="))
3924 return err
3925 }()},
3926 }, {
3927 name: name("Bytes/ByteArray1/Underflow"),
3928 inBuf: `""`,
3929 inVal: new([1]byte),
3930 want: addr([1]byte{}),
3931 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array1ByteType, Err: errors.New("decoded base64 length of 0 mismatches array length of 1")},
3932 }, {
3933 name: name("Bytes/ByteArray1/Overflow"),
3934 inBuf: `"AQI="`,
3935 inVal: new([1]byte),
3936 want: addr([1]byte{}),
3937 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array1ByteType, Err: errors.New("decoded base64 length of 2 mismatches array length of 1")},
3938 }, {
3939 name: name("Bytes/ByteArray2/Valid"),
3940 inBuf: `"AQI="`,
3941 inVal: new([2]byte),
3942 want: addr([2]byte{1, 2}),
3943 }, {
3944 name: name("Bytes/ByteArray2/Invalid"),
3945 inBuf: `"$$$="`,
3946 inVal: new([2]byte),
3947 want: addr([2]byte{}),
3948 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array2ByteType, Err: func() error {
3949 _, err := base64.StdEncoding.Decode(make([]byte, 2), []byte("$$$="))
3950 return err
3951 }()},
3952 }, {
3953 name: name("Bytes/ByteArray2/Underflow"),
3954 inBuf: `"AQ=="`,
3955 inVal: new([2]byte),
3956 want: addr([2]byte{}),
3957 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array2ByteType, Err: errors.New("decoded base64 length of 1 mismatches array length of 2")},
3958 }, {
3959 name: name("Bytes/ByteArray2/Overflow"),
3960 inBuf: `"AQID"`,
3961 inVal: new([2]byte),
3962 want: addr([2]byte{}),
3963 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array2ByteType, Err: errors.New("decoded base64 length of 3 mismatches array length of 2")},
3964 }, {
3965 name: name("Bytes/ByteArray3/Valid"),
3966 inBuf: `"AQID"`,
3967 inVal: new([3]byte),
3968 want: addr([3]byte{1, 2, 3}),
3969 }, {
3970 name: name("Bytes/ByteArray3/Invalid"),
3971 inBuf: `"$$$$"`,
3972 inVal: new([3]byte),
3973 want: addr([3]byte{}),
3974 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array3ByteType, Err: func() error {
3975 _, err := base64.StdEncoding.Decode(make([]byte, 3), []byte("$$$$"))
3976 return err
3977 }()},
3978 }, {
3979 name: name("Bytes/ByteArray3/Underflow"),
3980 inBuf: `"AQI="`,
3981 inVal: new([3]byte),
3982 want: addr([3]byte{}),
3983 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array3ByteType, Err: errors.New("decoded base64 length of 2 mismatches array length of 3")},
3984 }, {
3985 name: name("Bytes/ByteArray3/Overflow"),
3986 inBuf: `"AQIDAQ=="`,
3987 inVal: new([3]byte),
3988 want: addr([3]byte{}),
3989 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array3ByteType, Err: errors.New("decoded base64 length of 4 mismatches array length of 3")},
3990 }, {
3991 name: name("Bytes/ByteArray4/Valid"),
3992 inBuf: `"AQIDBA=="`,
3993 inVal: new([4]byte),
3994 want: addr([4]byte{1, 2, 3, 4}),
3995 }, {
3996 name: name("Bytes/ByteArray4/Invalid"),
3997 inBuf: `"$$$$$$=="`,
3998 inVal: new([4]byte),
3999 want: addr([4]byte{}),
4000 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array4ByteType, Err: func() error {
4001 _, err := base64.StdEncoding.Decode(make([]byte, 4), []byte("$$$$$$=="))
4002 return err
4003 }()},
4004 }, {
4005 name: name("Bytes/ByteArray4/Underflow"),
4006 inBuf: `"AQID"`,
4007 inVal: new([4]byte),
4008 want: addr([4]byte{}),
4009 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array4ByteType, Err: errors.New("decoded base64 length of 3 mismatches array length of 4")},
4010 }, {
4011 name: name("Bytes/ByteArray4/Overflow"),
4012 inBuf: `"AQIDBAU="`,
4013 inVal: new([4]byte),
4014 want: addr([4]byte{}),
4015 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array4ByteType, Err: errors.New("decoded base64 length of 5 mismatches array length of 4")},
4016 }, {
4017 // NOTE: []namedByte is not assignable to []byte,
4018 // so the following should be treated as a array of uints.
4019 name: name("Bytes/NamedByteArray"),
4020 inBuf: `[104,101,108,108,111]`,
4021 inVal: new([5]namedByte),
4022 want: addr([5]namedByte{'h', 'e', 'l', 'l', 'o'}),
4023 }, {
4024 name: name("Bytes/Valid/Denormalized"),
4025 inBuf: `"AR=="`,
4026 inVal: new([]byte),
4027 want: addr([]byte{1}),
4028 }, {
4029 name: name("Bytes/Invalid/Unpadded1"),
4030 inBuf: `"AQ="`,
4031 inVal: addr([]byte("nochange")),
4032 want: addr([]byte("nochange")),
4033 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
4034 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("AQ="))
4035 return err
4036 }()},
4037 }, {
4038 name: name("Bytes/Invalid/Unpadded2"),
4039 inBuf: `"AQ"`,
4040 inVal: addr([]byte("nochange")),
4041 want: addr([]byte("nochange")),
4042 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
4043 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("AQ"))
4044 return err
4045 }()},
4046 }, {
4047 name: name("Bytes/Invalid/Character"),
4048 inBuf: `"@@@@"`,
4049 inVal: addr([]byte("nochange")),
4050 want: addr([]byte("nochange")),
4051 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
4052 _, err := base64.StdEncoding.Decode(make([]byte, 3), []byte("@@@@"))
4053 return err
4054 }()},
4055 }, {
4056 name: name("Bytes/Invalid/Bool"),
4057 inBuf: `true`,
4058 inVal: addr([]byte("nochange")),
4059 want: addr([]byte("nochange")),
4060 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: bytesType},
4061 }, {
4062 name: name("Bytes/Invalid/Number"),
4063 inBuf: `0`,
4064 inVal: addr([]byte("nochange")),
4065 want: addr([]byte("nochange")),
4066 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: bytesType},
4067 }, {
4068 name: name("Bytes/Invalid/Object"),
4069 inBuf: `{}`,
4070 inVal: addr([]byte("nochange")),
4071 want: addr([]byte("nochange")),
4072 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: bytesType},
4073 }, {
4074 name: name("Bytes/Invalid/Array"),
4075 inBuf: `[]`,
4076 inVal: addr([]byte("nochange")),
4077 want: addr([]byte("nochange")),
4078 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: bytesType},
4079 }, {
4080 name: name("Bytes/IgnoreInvalidFormat"),
4081 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
4082 inBuf: `"aGVsbG8="`,
4083 inVal: new([]byte),
4084 want: addr([]byte("hello")),
4085 }, {
4086 name: name("Ints/Null"),
4087 inBuf: `null`,
4088 inVal: addr(int(1)),
4089 want: addr(int(0)),
4090 }, {
4091 name: name("Ints/Int"),
4092 inBuf: `1`,
4093 inVal: addr(int(0)),
4094 want: addr(int(1)),
4095 }, {
4096 name: name("Ints/Int8/MinOverflow"),
4097 inBuf: `-129`,
4098 inVal: addr(int8(-1)),
4099 want: addr(int8(-1)),
4100 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int8Type, Err: fmt.Errorf(`cannot parse "-129" as signed integer: %w`, strconv.ErrRange)},
4101 }, {
4102 name: name("Ints/Int8/Min"),
4103 inBuf: `-128`,
4104 inVal: addr(int8(0)),
4105 want: addr(int8(-128)),
4106 }, {
4107 name: name("Ints/Int8/Max"),
4108 inBuf: `127`,
4109 inVal: addr(int8(0)),
4110 want: addr(int8(127)),
4111 }, {
4112 name: name("Ints/Int8/MaxOverflow"),
4113 inBuf: `128`,
4114 inVal: addr(int8(-1)),
4115 want: addr(int8(-1)),
4116 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int8Type, Err: fmt.Errorf(`cannot parse "128" as signed integer: %w`, strconv.ErrRange)},
4117 }, {
4118 name: name("Ints/Int16/MinOverflow"),
4119 inBuf: `-32769`,
4120 inVal: addr(int16(-1)),
4121 want: addr(int16(-1)),
4122 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int16Type, Err: fmt.Errorf(`cannot parse "-32769" as signed integer: %w`, strconv.ErrRange)},
4123 }, {
4124 name: name("Ints/Int16/Min"),
4125 inBuf: `-32768`,
4126 inVal: addr(int16(0)),
4127 want: addr(int16(-32768)),
4128 }, {
4129 name: name("Ints/Int16/Max"),
4130 inBuf: `32767`,
4131 inVal: addr(int16(0)),
4132 want: addr(int16(32767)),
4133 }, {
4134 name: name("Ints/Int16/MaxOverflow"),
4135 inBuf: `32768`,
4136 inVal: addr(int16(-1)),
4137 want: addr(int16(-1)),
4138 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int16Type, Err: fmt.Errorf(`cannot parse "32768" as signed integer: %w`, strconv.ErrRange)},
4139 }, {
4140 name: name("Ints/Int32/MinOverflow"),
4141 inBuf: `-2147483649`,
4142 inVal: addr(int32(-1)),
4143 want: addr(int32(-1)),
4144 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int32Type, Err: fmt.Errorf(`cannot parse "-2147483649" as signed integer: %w`, strconv.ErrRange)},
4145 }, {
4146 name: name("Ints/Int32/Min"),
4147 inBuf: `-2147483648`,
4148 inVal: addr(int32(0)),
4149 want: addr(int32(-2147483648)),
4150 }, {
4151 name: name("Ints/Int32/Max"),
4152 inBuf: `2147483647`,
4153 inVal: addr(int32(0)),
4154 want: addr(int32(2147483647)),
4155 }, {
4156 name: name("Ints/Int32/MaxOverflow"),
4157 inBuf: `2147483648`,
4158 inVal: addr(int32(-1)),
4159 want: addr(int32(-1)),
4160 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int32Type, Err: fmt.Errorf(`cannot parse "2147483648" as signed integer: %w`, strconv.ErrRange)},
4161 }, {
4162 name: name("Ints/Int64/MinOverflow"),
4163 inBuf: `-9223372036854775809`,
4164 inVal: addr(int64(-1)),
4165 want: addr(int64(-1)),
4166 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int64Type, Err: fmt.Errorf(`cannot parse "-9223372036854775809" as signed integer: %w`, strconv.ErrRange)},
4167 }, {
4168 name: name("Ints/Int64/Min"),
4169 inBuf: `-9223372036854775808`,
4170 inVal: addr(int64(0)),
4171 want: addr(int64(-9223372036854775808)),
4172 }, {
4173 name: name("Ints/Int64/Max"),
4174 inBuf: `9223372036854775807`,
4175 inVal: addr(int64(0)),
4176 want: addr(int64(9223372036854775807)),
4177 }, {
4178 name: name("Ints/Int64/MaxOverflow"),
4179 inBuf: `9223372036854775808`,
4180 inVal: addr(int64(-1)),
4181 want: addr(int64(-1)),
4182 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: int64Type, Err: fmt.Errorf(`cannot parse "9223372036854775808" as signed integer: %w`, strconv.ErrRange)},
4183 }, {
4184 name: name("Ints/Named"),
4185 inBuf: `-6464`,
4186 inVal: addr(namedInt64(0)),
4187 want: addr(namedInt64(-6464)),
4188 }, {
4189 name: name("Ints/Stringified"),
4190 uopts: UnmarshalOptions{StringifyNumbers: true},
4191 inBuf: `"-6464"`,
4192 inVal: new(int),
4193 want: addr(int(-6464)),
4194 }, {
4195 name: name("Ints/Escaped"),
4196 uopts: UnmarshalOptions{StringifyNumbers: true},
4197 inBuf: `"\u002d\u0036\u0034\u0036\u0034"`,
4198 inVal: new(int),
4199 want: addr(int(-6464)),
4200 }, {
4201 name: name("Ints/Valid/NegativeZero"),
4202 inBuf: `-0`,
4203 inVal: addr(int(1)),
4204 want: addr(int(0)),
4205 }, {
4206 name: name("Ints/Invalid/Fraction"),
4207 inBuf: `1.0`,
4208 inVal: addr(int(-1)),
4209 want: addr(int(-1)),
4210 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: intType, Err: fmt.Errorf(`cannot parse "1.0" as signed integer: %w`, strconv.ErrSyntax)},
4211 }, {
4212 name: name("Ints/Invalid/Exponent"),
4213 inBuf: `1e0`,
4214 inVal: addr(int(-1)),
4215 want: addr(int(-1)),
4216 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: intType, Err: fmt.Errorf(`cannot parse "1e0" as signed integer: %w`, strconv.ErrSyntax)},
4217 }, {
4218 name: name("Ints/Invalid/StringifiedFraction"),
4219 uopts: UnmarshalOptions{StringifyNumbers: true},
4220 inBuf: `"1.0"`,
4221 inVal: addr(int(-1)),
4222 want: addr(int(-1)),
4223 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: intType, Err: fmt.Errorf(`cannot parse "1.0" as signed integer: %w`, strconv.ErrSyntax)},
4224 }, {
4225 name: name("Ints/Invalid/StringifiedExponent"),
4226 uopts: UnmarshalOptions{StringifyNumbers: true},
4227 inBuf: `"1e0"`,
4228 inVal: addr(int(-1)),
4229 want: addr(int(-1)),
4230 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: intType, Err: fmt.Errorf(`cannot parse "1e0" as signed integer: %w`, strconv.ErrSyntax)},
4231 }, {
4232 name: name("Ints/Invalid/Overflow"),
4233 inBuf: `100000000000000000000000000000`,
4234 inVal: addr(int(-1)),
4235 want: addr(int(-1)),
4236 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: intType, Err: fmt.Errorf(`cannot parse "100000000000000000000000000000" as signed integer: %w`, strconv.ErrRange)},
4237 }, {
4238 name: name("Ints/Invalid/OverflowSyntax"),
4239 uopts: UnmarshalOptions{StringifyNumbers: true},
4240 inBuf: `"100000000000000000000000000000x"`,
4241 inVal: addr(int(-1)),
4242 want: addr(int(-1)),
4243 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: intType, Err: fmt.Errorf(`cannot parse "100000000000000000000000000000x" as signed integer: %w`, strconv.ErrSyntax)},
4244 }, {
4245 name: name("Ints/Invalid/Whitespace"),
4246 uopts: UnmarshalOptions{StringifyNumbers: true},
4247 inBuf: `"0 "`,
4248 inVal: addr(int(-1)),
4249 want: addr(int(-1)),
4250 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: intType, Err: fmt.Errorf(`cannot parse "0 " as signed integer: %w`, strconv.ErrSyntax)},
4251 }, {
4252 name: name("Ints/Invalid/Bool"),
4253 inBuf: `true`,
4254 inVal: addr(int(-1)),
4255 want: addr(int(-1)),
4256 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: intType},
4257 }, {
4258 name: name("Ints/Invalid/String"),
4259 inBuf: `"0"`,
4260 inVal: addr(int(-1)),
4261 want: addr(int(-1)),
4262 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: intType},
4263 }, {
4264 name: name("Ints/Invalid/Object"),
4265 inBuf: `{}`,
4266 inVal: addr(int(-1)),
4267 want: addr(int(-1)),
4268 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: intType},
4269 }, {
4270 name: name("Ints/Invalid/Array"),
4271 inBuf: `[]`,
4272 inVal: addr(int(-1)),
4273 want: addr(int(-1)),
4274 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: intType},
4275 }, {
4276 name: name("Ints/IgnoreInvalidFormat"),
4277 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
4278 inBuf: `1`,
4279 inVal: addr(int(0)),
4280 want: addr(int(1)),
4281 }, {
4282 name: name("Uints/Null"),
4283 inBuf: `null`,
4284 inVal: addr(uint(1)),
4285 want: addr(uint(0)),
4286 }, {
4287 name: name("Uints/Uint"),
4288 inBuf: `1`,
4289 inVal: addr(uint(0)),
4290 want: addr(uint(1)),
4291 }, {
4292 name: name("Uints/Uint8/Min"),
4293 inBuf: `0`,
4294 inVal: addr(uint8(1)),
4295 want: addr(uint8(0)),
4296 }, {
4297 name: name("Uints/Uint8/Max"),
4298 inBuf: `255`,
4299 inVal: addr(uint8(0)),
4300 want: addr(uint8(255)),
4301 }, {
4302 name: name("Uints/Uint8/MaxOverflow"),
4303 inBuf: `256`,
4304 inVal: addr(uint8(1)),
4305 want: addr(uint8(1)),
4306 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uint8Type, Err: fmt.Errorf(`cannot parse "256" as unsigned integer: %w`, strconv.ErrRange)},
4307 }, {
4308 name: name("Uints/Uint16/Min"),
4309 inBuf: `0`,
4310 inVal: addr(uint16(1)),
4311 want: addr(uint16(0)),
4312 }, {
4313 name: name("Uints/Uint16/Max"),
4314 inBuf: `65535`,
4315 inVal: addr(uint16(0)),
4316 want: addr(uint16(65535)),
4317 }, {
4318 name: name("Uints/Uint16/MaxOverflow"),
4319 inBuf: `65536`,
4320 inVal: addr(uint16(1)),
4321 want: addr(uint16(1)),
4322 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uint16Type, Err: fmt.Errorf(`cannot parse "65536" as unsigned integer: %w`, strconv.ErrRange)},
4323 }, {
4324 name: name("Uints/Uint32/Min"),
4325 inBuf: `0`,
4326 inVal: addr(uint32(1)),
4327 want: addr(uint32(0)),
4328 }, {
4329 name: name("Uints/Uint32/Max"),
4330 inBuf: `4294967295`,
4331 inVal: addr(uint32(0)),
4332 want: addr(uint32(4294967295)),
4333 }, {
4334 name: name("Uints/Uint32/MaxOverflow"),
4335 inBuf: `4294967296`,
4336 inVal: addr(uint32(1)),
4337 want: addr(uint32(1)),
4338 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uint32Type, Err: fmt.Errorf(`cannot parse "4294967296" as unsigned integer: %w`, strconv.ErrRange)},
4339 }, {
4340 name: name("Uints/Uint64/Min"),
4341 inBuf: `0`,
4342 inVal: addr(uint64(1)),
4343 want: addr(uint64(0)),
4344 }, {
4345 name: name("Uints/Uint64/Max"),
4346 inBuf: `18446744073709551615`,
4347 inVal: addr(uint64(0)),
4348 want: addr(uint64(18446744073709551615)),
4349 }, {
4350 name: name("Uints/Uint64/MaxOverflow"),
4351 inBuf: `18446744073709551616`,
4352 inVal: addr(uint64(1)),
4353 want: addr(uint64(1)),
4354 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uint64Type, Err: fmt.Errorf(`cannot parse "18446744073709551616" as unsigned integer: %w`, strconv.ErrRange)},
4355 }, {
4356 name: name("Uints/Named"),
4357 inBuf: `6464`,
4358 inVal: addr(namedUint64(0)),
4359 want: addr(namedUint64(6464)),
4360 }, {
4361 name: name("Uints/Stringified"),
4362 uopts: UnmarshalOptions{StringifyNumbers: true},
4363 inBuf: `"6464"`,
4364 inVal: new(uint),
4365 want: addr(uint(6464)),
4366 }, {
4367 name: name("Uints/Escaped"),
4368 uopts: UnmarshalOptions{StringifyNumbers: true},
4369 inBuf: `"\u0036\u0034\u0036\u0034"`,
4370 inVal: new(uint),
4371 want: addr(uint(6464)),
4372 }, {
4373 name: name("Uints/Invalid/NegativeOne"),
4374 inBuf: `-1`,
4375 inVal: addr(uint(1)),
4376 want: addr(uint(1)),
4377 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uintType, Err: fmt.Errorf(`cannot parse "-1" as unsigned integer: %w`, strconv.ErrSyntax)},
4378 }, {
4379 name: name("Uints/Invalid/NegativeZero"),
4380 inBuf: `-0`,
4381 inVal: addr(uint(1)),
4382 want: addr(uint(1)),
4383 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uintType, Err: fmt.Errorf(`cannot parse "-0" as unsigned integer: %w`, strconv.ErrSyntax)},
4384 }, {
4385 name: name("Uints/Invalid/Fraction"),
4386 inBuf: `1.0`,
4387 inVal: addr(uint(10)),
4388 want: addr(uint(10)),
4389 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uintType, Err: fmt.Errorf(`cannot parse "1.0" as unsigned integer: %w`, strconv.ErrSyntax)},
4390 }, {
4391 name: name("Uints/Invalid/Exponent"),
4392 inBuf: `1e0`,
4393 inVal: addr(uint(10)),
4394 want: addr(uint(10)),
4395 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uintType, Err: fmt.Errorf(`cannot parse "1e0" as unsigned integer: %w`, strconv.ErrSyntax)},
4396 }, {
4397 name: name("Uints/Invalid/StringifiedFraction"),
4398 uopts: UnmarshalOptions{StringifyNumbers: true},
4399 inBuf: `"1.0"`,
4400 inVal: addr(uint(10)),
4401 want: addr(uint(10)),
4402 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: uintType, Err: fmt.Errorf(`cannot parse "1.0" as unsigned integer: %w`, strconv.ErrSyntax)},
4403 }, {
4404 name: name("Uints/Invalid/StringifiedExponent"),
4405 uopts: UnmarshalOptions{StringifyNumbers: true},
4406 inBuf: `"1e0"`,
4407 inVal: addr(uint(10)),
4408 want: addr(uint(10)),
4409 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: uintType, Err: fmt.Errorf(`cannot parse "1e0" as unsigned integer: %w`, strconv.ErrSyntax)},
4410 }, {
4411 name: name("Uints/Invalid/Overflow"),
4412 inBuf: `100000000000000000000000000000`,
4413 inVal: addr(uint(1)),
4414 want: addr(uint(1)),
4415 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: uintType, Err: fmt.Errorf(`cannot parse "100000000000000000000000000000" as unsigned integer: %w`, strconv.ErrRange)},
4416 }, {
4417 name: name("Uints/Invalid/OverflowSyntax"),
4418 uopts: UnmarshalOptions{StringifyNumbers: true},
4419 inBuf: `"100000000000000000000000000000x"`,
4420 inVal: addr(uint(1)),
4421 want: addr(uint(1)),
4422 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: uintType, Err: fmt.Errorf(`cannot parse "100000000000000000000000000000x" as unsigned integer: %w`, strconv.ErrSyntax)},
4423 }, {
4424 name: name("Uints/Invalid/Whitespace"),
4425 uopts: UnmarshalOptions{StringifyNumbers: true},
4426 inBuf: `"0 "`,
4427 inVal: addr(uint(1)),
4428 want: addr(uint(1)),
4429 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: uintType, Err: fmt.Errorf(`cannot parse "0 " as unsigned integer: %w`, strconv.ErrSyntax)},
4430 }, {
4431 name: name("Uints/Invalid/Bool"),
4432 inBuf: `true`,
4433 inVal: addr(uint(1)),
4434 want: addr(uint(1)),
4435 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: uintType},
4436 }, {
4437 name: name("Uints/Invalid/String"),
4438 inBuf: `"0"`,
4439 inVal: addr(uint(1)),
4440 want: addr(uint(1)),
4441 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: uintType},
4442 }, {
4443 name: name("Uints/Invalid/Object"),
4444 inBuf: `{}`,
4445 inVal: addr(uint(1)),
4446 want: addr(uint(1)),
4447 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: uintType},
4448 }, {
4449 name: name("Uints/Invalid/Array"),
4450 inBuf: `[]`,
4451 inVal: addr(uint(1)),
4452 want: addr(uint(1)),
4453 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: uintType},
4454 }, {
4455 name: name("Uints/IgnoreInvalidFormat"),
4456 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
4457 inBuf: `1`,
4458 inVal: addr(uint(0)),
4459 want: addr(uint(1)),
4460 }, {
4461 name: name("Floats/Null"),
4462 inBuf: `null`,
4463 inVal: addr(float64(64.64)),
4464 want: addr(float64(0)),
4465 }, {
4466 name: name("Floats/Float32/Pi"),
4467 inBuf: `3.14159265358979323846264338327950288419716939937510582097494459`,
4468 inVal: addr(float32(32.32)),
4469 want: addr(float32(math.Pi)),
4470 }, {
4471 name: name("Floats/Float32/Underflow"),
4472 inBuf: `-1e1000`,
4473 inVal: addr(float32(32.32)),
4474 want: addr(float32(-math.MaxFloat32)),
4475 }, {
4476 name: name("Floats/Float32/Overflow"),
4477 inBuf: `-1e1000`,
4478 inVal: addr(float32(32.32)),
4479 want: addr(float32(-math.MaxFloat32)),
4480 }, {
4481 name: name("Floats/Float64/Pi"),
4482 inBuf: `3.14159265358979323846264338327950288419716939937510582097494459`,
4483 inVal: addr(float64(64.64)),
4484 want: addr(float64(math.Pi)),
4485 }, {
4486 name: name("Floats/Float64/Underflow"),
4487 inBuf: `-1e1000`,
4488 inVal: addr(float64(64.64)),
4489 want: addr(float64(-math.MaxFloat64)),
4490 }, {
4491 name: name("Floats/Float64/Overflow"),
4492 inBuf: `-1e1000`,
4493 inVal: addr(float64(64.64)),
4494 want: addr(float64(-math.MaxFloat64)),
4495 }, {
4496 name: name("Floats/Named"),
4497 inBuf: `64.64`,
4498 inVal: addr(namedFloat64(0)),
4499 want: addr(namedFloat64(64.64)),
4500 }, {
4501 name: name("Floats/Stringified"),
4502 uopts: UnmarshalOptions{StringifyNumbers: true},
4503 inBuf: `"64.64"`,
4504 inVal: new(float64),
4505 want: addr(float64(64.64)),
4506 }, {
4507 name: name("Floats/Escaped"),
4508 uopts: UnmarshalOptions{StringifyNumbers: true},
4509 inBuf: `"\u0036\u0034\u002e\u0036\u0034"`,
4510 inVal: new(float64),
4511 want: addr(float64(64.64)),
4512 }, {
4513 name: name("Floats/Invalid/NaN"),
4514 uopts: UnmarshalOptions{StringifyNumbers: true},
4515 inBuf: `"NaN"`,
4516 inVal: addr(float64(64.64)),
4517 want: addr(float64(64.64)),
4518 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type, Err: fmt.Errorf(`cannot parse "NaN" as JSON number: %w`, strconv.ErrSyntax)},
4519 }, {
4520 name: name("Floats/Invalid/Infinity"),
4521 uopts: UnmarshalOptions{StringifyNumbers: true},
4522 inBuf: `"Infinity"`,
4523 inVal: addr(float64(64.64)),
4524 want: addr(float64(64.64)),
4525 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type, Err: fmt.Errorf(`cannot parse "Infinity" as JSON number: %w`, strconv.ErrSyntax)},
4526 }, {
4527 name: name("Floats/Invalid/Whitespace"),
4528 uopts: UnmarshalOptions{StringifyNumbers: true},
4529 inBuf: `"1 "`,
4530 inVal: addr(float64(64.64)),
4531 want: addr(float64(64.64)),
4532 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type, Err: fmt.Errorf(`cannot parse "1 " as JSON number: %w`, strconv.ErrSyntax)},
4533 }, {
4534 name: name("Floats/Invalid/GoSyntax"),
4535 uopts: UnmarshalOptions{StringifyNumbers: true},
4536 inBuf: `"1p-2"`,
4537 inVal: addr(float64(64.64)),
4538 want: addr(float64(64.64)),
4539 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type, Err: fmt.Errorf(`cannot parse "1p-2" as JSON number: %w`, strconv.ErrSyntax)},
4540 }, {
4541 name: name("Floats/Invalid/Bool"),
4542 inBuf: `true`,
4543 inVal: addr(float64(64.64)),
4544 want: addr(float64(64.64)),
4545 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: float64Type},
4546 }, {
4547 name: name("Floats/Invalid/String"),
4548 inBuf: `"0"`,
4549 inVal: addr(float64(64.64)),
4550 want: addr(float64(64.64)),
4551 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type},
4552 }, {
4553 name: name("Floats/Invalid/Object"),
4554 inBuf: `{}`,
4555 inVal: addr(float64(64.64)),
4556 want: addr(float64(64.64)),
4557 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: float64Type},
4558 }, {
4559 name: name("Floats/Invalid/Array"),
4560 inBuf: `[]`,
4561 inVal: addr(float64(64.64)),
4562 want: addr(float64(64.64)),
4563 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: float64Type},
4564 }, {
4565 name: name("Floats/IgnoreInvalidFormat"),
4566 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
4567 inBuf: `1`,
4568 inVal: addr(float64(0)),
4569 want: addr(float64(1)),
4570 }, {
4571 name: name("Maps/Null"),
4572 inBuf: `null`,
4573 inVal: addr(map[string]string{"key": "value"}),
4574 want: new(map[string]string),
4575 }, {
4576 name: name("Maps/InvalidKey/Bool"),
4577 inBuf: `{"true":"false"}`,
4578 inVal: new(map[bool]bool),
4579 want: addr(make(map[bool]bool)),
4580 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: boolType},
4581 }, {
4582 name: name("Maps/InvalidKey/NamedBool"),
4583 inBuf: `{"true":"false"}`,
4584 inVal: new(map[namedBool]bool),
4585 want: addr(make(map[namedBool]bool)),
4586 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: namedBoolType},
4587 }, {
4588 name: name("Maps/InvalidKey/Array"),
4589 inBuf: `{"key":"value"}`,
4590 inVal: new(map[[1]string]string),
4591 want: addr(make(map[[1]string]string)),
4592 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array1StringType},
4593 }, {
4594 name: name("Maps/InvalidKey/Channel"),
4595 inBuf: `{"key":"value"}`,
4596 inVal: new(map[chan string]string),
4597 want: addr(make(map[chan string]string)),
4598 wantErr: &SemanticError{action: "unmarshal", GoType: chanStringType},
4599 }, {
4600 name: name("Maps/ValidKey/Int"),
4601 inBuf: `{"0":0,"-1":1,"2":2,"-3":3}`,
4602 inVal: new(map[int]int),
4603 want: addr(map[int]int{0: 0, -1: 1, 2: 2, -3: 3}),
4604 }, {
4605 name: name("Maps/ValidKey/NamedInt"),
4606 inBuf: `{"0":0,"-1":1,"2":2,"-3":3}`,
4607 inVal: new(map[namedInt64]int),
4608 want: addr(map[namedInt64]int{0: 0, -1: 1, 2: 2, -3: 3}),
4609 }, {
4610 name: name("Maps/ValidKey/Uint"),
4611 inBuf: `{"0":0,"1":1,"2":2,"3":3}`,
4612 inVal: new(map[uint]uint),
4613 want: addr(map[uint]uint{0: 0, 1: 1, 2: 2, 3: 3}),
4614 }, {
4615 name: name("Maps/ValidKey/NamedUint"),
4616 inBuf: `{"0":0,"1":1,"2":2,"3":3}`,
4617 inVal: new(map[namedUint64]uint),
4618 want: addr(map[namedUint64]uint{0: 0, 1: 1, 2: 2, 3: 3}),
4619 }, {
4620 name: name("Maps/ValidKey/Float"),
4621 inBuf: `{"1.234":1.234,"12.34":12.34,"123.4":123.4}`,
4622 inVal: new(map[float64]float64),
4623 want: addr(map[float64]float64{1.234: 1.234, 12.34: 12.34, 123.4: 123.4}),
4624 }, {
4625 name: name("Maps/DuplicateName/Int"),
4626 inBuf: `{"0":1,"-0":-1}`,
4627 inVal: new(map[int]int),
4628 want: addr(map[int]int{0: 1}),
4629 wantErr: (&SyntacticError{str: `duplicate name "-0" in object`}).withOffset(int64(len(`{"0":1,`))),
4630 }, {
4631 name: name("Maps/DuplicateName/Int/AllowDuplicateNames"),
4632 dopts: DecodeOptions{AllowDuplicateNames: true},
4633 inBuf: `{"0":1,"-0":-1}`,
4634 inVal: new(map[int]int),
4635 want: addr(map[int]int{0: -1}), // latter takes precedence
4636 }, {
4637 name: name("Maps/DuplicateName/Int/OverwriteExisting"),
4638 inBuf: `{"-0":-1}`,
4639 inVal: addr(map[int]int{0: 1}),
4640 want: addr(map[int]int{0: -1}),
4641 }, {
4642 name: name("Maps/DuplicateName/Float"),
4643 inBuf: `{"1.0":"1.0","1":"1","1e0":"1e0"}`,
4644 inVal: new(map[float64]string),
4645 want: addr(map[float64]string{1: "1.0"}),
4646 wantErr: (&SyntacticError{str: `duplicate name "1" in object`}).withOffset(int64(len(`{"1.0":"1.0",`))),
4647 }, {
4648 name: name("Maps/DuplicateName/Float/AllowDuplicateNames"),
4649 dopts: DecodeOptions{AllowDuplicateNames: true},
4650 inBuf: `{"1.0":"1.0","1":"1","1e0":"1e0"}`,
4651 inVal: new(map[float64]string),
4652 want: addr(map[float64]string{1: "1e0"}), // latter takes precedence
4653 }, {
4654 name: name("Maps/DuplicateName/Float/OverwriteExisting"),
4655 inBuf: `{"1.0":"1.0"}`,
4656 inVal: addr(map[float64]string{1: "1"}),
4657 want: addr(map[float64]string{1: "1.0"}),
4658 }, {
4659 name: name("Maps/DuplicateName/NoCaseString"),
4660 inBuf: `{"hello":"hello","HELLO":"HELLO"}`,
4661 inVal: new(map[nocaseString]string),
4662 want: addr(map[nocaseString]string{"hello": "hello"}),
4663 wantErr: (&SyntacticError{str: `duplicate name "HELLO" in object`}).withOffset(int64(len(`{"hello":"hello",`))),
4664 }, {
4665 name: name("Maps/DuplicateName/NoCaseString/AllowDuplicateNames"),
4666 dopts: DecodeOptions{AllowDuplicateNames: true},
4667 inBuf: `{"hello":"hello","HELLO":"HELLO"}`,
4668 inVal: new(map[nocaseString]string),
4669 want: addr(map[nocaseString]string{"hello": "HELLO"}), // latter takes precedence
4670 }, {
4671 name: name("Maps/DuplicateName/NoCaseString/OverwriteExisting"),
4672 dopts: DecodeOptions{AllowDuplicateNames: true},
4673 inBuf: `{"HELLO":"HELLO"}`,
4674 inVal: addr(map[nocaseString]string{"hello": "hello"}),
4675 want: addr(map[nocaseString]string{"hello": "HELLO"}),
4676 }, {
4677 name: name("Maps/ValidKey/Interface"),
4678 inBuf: `{"false":"false","true":"true","string":"string","0":"0","[]":"[]","{}":"{}"}`,
4679 inVal: new(map[any]string),
4680 want: addr(map[any]string{
4681 "false": "false",
4682 "true": "true",
4683 "string": "string",
4684 "0": "0",
4685 "[]": "[]",
4686 "{}": "{}",
4687 }),
4688 }, {
4689 name: name("Maps/InvalidValue/Channel"),
4690 inBuf: `{"key":"value"}`,
4691 inVal: new(map[string]chan string),
4692 want: addr(map[string]chan string{
4693 "key": nil,
4694 }),
4695 wantErr: &SemanticError{action: "unmarshal", GoType: chanStringType},
4696 }, {
4697 name: name("Maps/RecursiveMap"),
4698 inBuf: `{"buzz":{},"fizz":{"bar":{},"foo":{}}}`,
4699 inVal: new(recursiveMap),
4700 want: addr(recursiveMap{
4701 "fizz": {
4702 "foo": {},
4703 "bar": {},
4704 },
4705 "buzz": {},
4706 }),
4707 }, {
4708 // NOTE: The semantics differs from v1,
4709 // where existing map entries were not merged into.
4710 // See https://go.dev/issue/31924.
4711 name: name("Maps/Merge"),
4712 dopts: DecodeOptions{AllowDuplicateNames: true},
4713 inBuf: `{"k1":{"k2":"v2"},"k2":{"k1":"v1"},"k2":{"k2":"v2"}}`,
4714 inVal: addr(map[string]map[string]string{
4715 "k1": {"k1": "v1"},
4716 }),
4717 want: addr(map[string]map[string]string{
4718 "k1": {"k1": "v1", "k2": "v2"},
4719 "k2": {"k1": "v1", "k2": "v2"},
4720 }),
4721 }, {
4722 name: name("Maps/Invalid/Bool"),
4723 inBuf: `true`,
4724 inVal: addr(map[string]string{"key": "value"}),
4725 want: addr(map[string]string{"key": "value"}),
4726 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: mapStringStringType},
4727 }, {
4728 name: name("Maps/Invalid/String"),
4729 inBuf: `""`,
4730 inVal: addr(map[string]string{"key": "value"}),
4731 want: addr(map[string]string{"key": "value"}),
4732 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: mapStringStringType},
4733 }, {
4734 name: name("Maps/Invalid/Number"),
4735 inBuf: `0`,
4736 inVal: addr(map[string]string{"key": "value"}),
4737 want: addr(map[string]string{"key": "value"}),
4738 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: mapStringStringType},
4739 }, {
4740 name: name("Maps/Invalid/Array"),
4741 inBuf: `[]`,
4742 inVal: addr(map[string]string{"key": "value"}),
4743 want: addr(map[string]string{"key": "value"}),
4744 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: mapStringStringType},
4745 }, {
4746 name: name("Maps/IgnoreInvalidFormat"),
4747 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
4748 inBuf: `{"hello":"goodbye"}`,
4749 inVal: addr(map[string]string{}),
4750 want: addr(map[string]string{"hello": "goodbye"}),
4751 }, {
4752 name: name("Structs/Null"),
4753 inBuf: `null`,
4754 inVal: addr(structAll{String: "something"}),
4755 want: addr(structAll{}),
4756 }, {
4757 name: name("Structs/Empty"),
4758 inBuf: `{}`,
4759 inVal: addr(structAll{
4760 String: "hello",
4761 Map: map[string]string{},
4762 Slice: []string{},
4763 }),
4764 want: addr(structAll{
4765 String: "hello",
4766 Map: map[string]string{},
4767 Slice: []string{},
4768 }),
4769 }, {
4770 name: name("Structs/Normal"),
4771 inBuf: `{
4772 "Bool": true,
4773 "String": "hello",
4774 "Bytes": "AQID",
4775 "Int": -64,
4776 "Uint": 64,
4777 "Float": 3.14159,
4778 "Map": {"key": "value"},
4779 "StructScalars": {
4780 "Bool": true,
4781 "String": "hello",
4782 "Bytes": "AQID",
4783 "Int": -64,
4784 "Uint": 64,
4785 "Float": 3.14159
4786 },
4787 "StructMaps": {
4788 "MapBool": {"": true},
4789 "MapString": {"": "hello"},
4790 "MapBytes": {"": "AQID"},
4791 "MapInt": {"": -64},
4792 "MapUint": {"": 64},
4793 "MapFloat": {"": 3.14159}
4794 },
4795 "StructSlices": {
4796 "SliceBool": [true],
4797 "SliceString": ["hello"],
4798 "SliceBytes": ["AQID"],
4799 "SliceInt": [-64],
4800 "SliceUint": [64],
4801 "SliceFloat": [3.14159]
4802 },
4803 "Slice": ["fizz","buzz"],
4804 "Array": ["goodbye"],
4805 "Pointer": {},
4806 "Interface": null
4807 }`,
4808 inVal: new(structAll),
4809 want: addr(structAll{
4810 Bool: true,
4811 String: "hello",
4812 Bytes: []byte{1, 2, 3},
4813 Int: -64,
4814 Uint: +64,
4815 Float: 3.14159,
4816 Map: map[string]string{"key": "value"},
4817 StructScalars: structScalars{
4818 Bool: true,
4819 String: "hello",
4820 Bytes: []byte{1, 2, 3},
4821 Int: -64,
4822 Uint: +64,
4823 Float: 3.14159,
4824 },
4825 StructMaps: structMaps{
4826 MapBool: map[string]bool{"": true},
4827 MapString: map[string]string{"": "hello"},
4828 MapBytes: map[string][]byte{"": {1, 2, 3}},
4829 MapInt: map[string]int64{"": -64},
4830 MapUint: map[string]uint64{"": +64},
4831 MapFloat: map[string]float64{"": 3.14159},
4832 },
4833 StructSlices: structSlices{
4834 SliceBool: []bool{true},
4835 SliceString: []string{"hello"},
4836 SliceBytes: [][]byte{{1, 2, 3}},
4837 SliceInt: []int64{-64},
4838 SliceUint: []uint64{+64},
4839 SliceFloat: []float64{3.14159},
4840 },
4841 Slice: []string{"fizz", "buzz"},
4842 Array: [1]string{"goodbye"},
4843 Pointer: new(structAll),
4844 }),
4845 }, {
4846 name: name("Structs/Merge"),
4847 inBuf: `{
4848 "Bool": false,
4849 "String": "goodbye",
4850 "Int": -64,
4851 "Float": 3.14159,
4852 "Map": {"k2": "v2"},
4853 "StructScalars": {
4854 "Bool": true,
4855 "String": "hello",
4856 "Bytes": "AQID",
4857 "Int": -64
4858 },
4859 "StructMaps": {
4860 "MapBool": {"": true},
4861 "MapString": {"": "hello"},
4862 "MapBytes": {"": "AQID"},
4863 "MapInt": {"": -64},
4864 "MapUint": {"": 64},
4865 "MapFloat": {"": 3.14159}
4866 },
4867 "StructSlices": {
4868 "SliceString": ["hello"],
4869 "SliceBytes": ["AQID"],
4870 "SliceInt": [-64],
4871 "SliceUint": [64]
4872 },
4873 "Slice": ["fizz","buzz"],
4874 "Array": ["goodbye"],
4875 "Pointer": {},
4876 "Interface": {"k2":"v2"}
4877 }`,
4878 inVal: addr(structAll{
4879 Bool: true,
4880 String: "hello",
4881 Bytes: []byte{1, 2, 3},
4882 Uint: +64,
4883 Float: math.NaN(),
4884 Map: map[string]string{"k1": "v1"},
4885 StructScalars: structScalars{
4886 String: "hello",
4887 Bytes: make([]byte, 2, 4),
4888 Uint: +64,
4889 Float: 3.14159,
4890 },
4891 StructMaps: structMaps{
4892 MapBool: map[string]bool{"": false},
4893 MapBytes: map[string][]byte{"": {}},
4894 MapInt: map[string]int64{"": 123},
4895 MapFloat: map[string]float64{"": math.Inf(+1)},
4896 },
4897 StructSlices: structSlices{
4898 SliceBool: []bool{true},
4899 SliceBytes: [][]byte{nil, nil},
4900 SliceInt: []int64{-123},
4901 SliceUint: []uint64{+123},
4902 SliceFloat: []float64{3.14159},
4903 },
4904 Slice: []string{"buzz", "fizz", "gizz"},
4905 Array: [1]string{"hello"},
4906 Pointer: new(structAll),
4907 Interface: map[string]string{"k1": "v1"},
4908 }),
4909 want: addr(structAll{
4910 Bool: false,
4911 String: "goodbye",
4912 Bytes: []byte{1, 2, 3},
4913 Int: -64,
4914 Uint: +64,
4915 Float: 3.14159,
4916 Map: map[string]string{"k1": "v1", "k2": "v2"},
4917 StructScalars: structScalars{
4918 Bool: true,
4919 String: "hello",
4920 Bytes: []byte{1, 2, 3},
4921 Int: -64,
4922 Uint: +64,
4923 Float: 3.14159,
4924 },
4925 StructMaps: structMaps{
4926 MapBool: map[string]bool{"": true},
4927 MapString: map[string]string{"": "hello"},
4928 MapBytes: map[string][]byte{"": {1, 2, 3}},
4929 MapInt: map[string]int64{"": -64},
4930 MapUint: map[string]uint64{"": +64},
4931 MapFloat: map[string]float64{"": 3.14159},
4932 },
4933 StructSlices: structSlices{
4934 SliceBool: []bool{true},
4935 SliceString: []string{"hello"},
4936 SliceBytes: [][]byte{{1, 2, 3}},
4937 SliceInt: []int64{-64},
4938 SliceUint: []uint64{+64},
4939 SliceFloat: []float64{3.14159},
4940 },
4941 Slice: []string{"fizz", "buzz"},
4942 Array: [1]string{"goodbye"},
4943 Pointer: new(structAll),
4944 Interface: map[string]string{"k1": "v1", "k2": "v2"},
4945 }),
4946 }, {
4947 name: name("Structs/Stringified/Normal"),
4948 inBuf: `{
4949 "Bool": true,
4950 "String": "hello",
4951 "Bytes": "AQID",
4952 "Int": -64,
4953 "Uint": 64,
4954 "Float": 3.14159,
4955 "Map": {"key": "value"},
4956 "StructScalars": {
4957 "Bool": true,
4958 "String": "hello",
4959 "Bytes": "AQID",
4960 "Int": -64,
4961 "Uint": 64,
4962 "Float": 3.14159
4963 },
4964 "StructMaps": {
4965 "MapBool": {"": true},
4966 "MapString": {"": "hello"},
4967 "MapBytes": {"": "AQID"},
4968 "MapInt": {"": -64},
4969 "MapUint": {"": 64},
4970 "MapFloat": {"": 3.14159}
4971 },
4972 "StructSlices": {
4973 "SliceBool": [true],
4974 "SliceString": ["hello"],
4975 "SliceBytes": ["AQID"],
4976 "SliceInt": [-64],
4977 "SliceUint": [64],
4978 "SliceFloat": [3.14159]
4979 },
4980 "Slice": ["fizz","buzz"],
4981 "Array": ["goodbye"],
4982 "Pointer": {},
4983 "Interface": null
4984 }`,
4985 inVal: new(structStringifiedAll),
4986 want: addr(structStringifiedAll{
4987 Bool: true,
4988 String: "hello",
4989 Bytes: []byte{1, 2, 3},
4990 Int: -64, // may be stringified
4991 Uint: +64, // may be stringified
4992 Float: 3.14159, // may be stringified
4993 Map: map[string]string{"key": "value"},
4994 StructScalars: structScalars{
4995 Bool: true,
4996 String: "hello",
4997 Bytes: []byte{1, 2, 3},
4998 Int: -64, // may be stringified
4999 Uint: +64, // may be stringified
5000 Float: 3.14159, // may be stringified
5001 },
5002 StructMaps: structMaps{
5003 MapBool: map[string]bool{"": true},
5004 MapString: map[string]string{"": "hello"},
5005 MapBytes: map[string][]byte{"": {1, 2, 3}},
5006 MapInt: map[string]int64{"": -64}, // may be stringified
5007 MapUint: map[string]uint64{"": +64}, // may be stringified
5008 MapFloat: map[string]float64{"": 3.14159}, // may be stringified
5009 },
5010 StructSlices: structSlices{
5011 SliceBool: []bool{true},
5012 SliceString: []string{"hello"},
5013 SliceBytes: [][]byte{{1, 2, 3}},
5014 SliceInt: []int64{-64}, // may be stringified
5015 SliceUint: []uint64{+64}, // may be stringified
5016 SliceFloat: []float64{3.14159}, // may be stringified
5017 },
5018 Slice: []string{"fizz", "buzz"},
5019 Array: [1]string{"goodbye"},
5020 Pointer: new(structStringifiedAll), // may be stringified
5021 }),
5022 }, {
5023 name: name("Structs/Stringified/String"),
5024 inBuf: `{
5025 "Bool": true,
5026 "String": "hello",
5027 "Bytes": "AQID",
5028 "Int": "-64",
5029 "Uint": "64",
5030 "Float": "3.14159",
5031 "Map": {"key": "value"},
5032 "StructScalars": {
5033 "Bool": true,
5034 "String": "hello",
5035 "Bytes": "AQID",
5036 "Int": "-64",
5037 "Uint": "64",
5038 "Float": "3.14159"
5039 },
5040 "StructMaps": {
5041 "MapBool": {"": true},
5042 "MapString": {"": "hello"},
5043 "MapBytes": {"": "AQID"},
5044 "MapInt": {"": "-64"},
5045 "MapUint": {"": "64"},
5046 "MapFloat": {"": "3.14159"}
5047 },
5048 "StructSlices": {
5049 "SliceBool": [true],
5050 "SliceString": ["hello"],
5051 "SliceBytes": ["AQID"],
5052 "SliceInt": ["-64"],
5053 "SliceUint": ["64"],
5054 "SliceFloat": ["3.14159"]
5055 },
5056 "Slice": ["fizz","buzz"],
5057 "Array": ["goodbye"],
5058 "Pointer": {},
5059 "Interface": null
5060 }`,
5061 inVal: new(structStringifiedAll),
5062 want: addr(structStringifiedAll{
5063 Bool: true,
5064 String: "hello",
5065 Bytes: []byte{1, 2, 3},
5066 Int: -64, // may be stringified
5067 Uint: +64, // may be stringified
5068 Float: 3.14159, // may be stringified
5069 Map: map[string]string{"key": "value"},
5070 StructScalars: structScalars{
5071 Bool: true,
5072 String: "hello",
5073 Bytes: []byte{1, 2, 3},
5074 Int: -64, // may be stringified
5075 Uint: +64, // may be stringified
5076 Float: 3.14159, // may be stringified
5077 },
5078 StructMaps: structMaps{
5079 MapBool: map[string]bool{"": true},
5080 MapString: map[string]string{"": "hello"},
5081 MapBytes: map[string][]byte{"": {1, 2, 3}},
5082 MapInt: map[string]int64{"": -64}, // may be stringified
5083 MapUint: map[string]uint64{"": +64}, // may be stringified
5084 MapFloat: map[string]float64{"": 3.14159}, // may be stringified
5085 },
5086 StructSlices: structSlices{
5087 SliceBool: []bool{true},
5088 SliceString: []string{"hello"},
5089 SliceBytes: [][]byte{{1, 2, 3}},
5090 SliceInt: []int64{-64}, // may be stringified
5091 SliceUint: []uint64{+64}, // may be stringified
5092 SliceFloat: []float64{3.14159}, // may be stringified
5093 },
5094 Slice: []string{"fizz", "buzz"},
5095 Array: [1]string{"goodbye"},
5096 Pointer: new(structStringifiedAll), // may be stringified
5097 }),
5098 }, {
5099 name: name("Structs/Format/Bytes"),
5100 inBuf: `{
5101 "Base16": "0123456789abcdef",
5102 "Base32": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
5103 "Base32Hex": "0123456789ABCDEFGHIJKLMNOPQRSTUV",
5104 "Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
5105 "Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
5106 "Array": [1, 2, 3, 4]
5107 }`,
5108 inVal: new(structFormatBytes),
5109 want: addr(structFormatBytes{
5110 Base16: []byte("\x01\x23\x45\x67\x89\xab\xcd\xef"),
5111 Base32: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
5112 Base32Hex: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
5113 Base64: []byte("\x00\x10\x83\x10Q\x87 \x92\x8b0ӏA\x14\x93QU\x97a\x96\x9bqן\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2ۯ\xc3\x1c\xb3\xd3]\xb7㞻\xf3߿"),
5114 Base64URL: []byte("\x00\x10\x83\x10Q\x87 \x92\x8b0ӏA\x14\x93QU\x97a\x96\x9bqן\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2ۯ\xc3\x1c\xb3\xd3]\xb7㞻\xf3߿"),
5115 Array: []byte{1, 2, 3, 4},
5116 }),
5117 }, {
5118 name: name("Structs/Format/Bytes/Array"),
5119 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *byte) error {
5120 if string(b) == "true" {
5121 *v = 1
5122 } else {
5123 *v = 0
5124 }
5125 return nil
5126 })},
5127 inBuf: `{"Array":[false,true,false,true,false,true]}`,
5128 inVal: new(struct {
5129 Array []byte `json:",format:array"`
5130 }),
5131 want: addr(struct {
5132 Array []byte `json:",format:array"`
5133 }{
5134 Array: []byte{0, 1, 0, 1, 0, 1},
5135 }),
5136 }, {
5137 name: name("Structs/Format/Bytes/Invalid/Base16/WrongKind"),
5138 inBuf: `{"Base16": [1,2,3,4]}`,
5139 inVal: new(structFormatBytes),
5140 wantErr: &SemanticError{action: "unmarshal", JSONKind: '[', GoType: bytesType},
5141 }, {
5142 name: name("Structs/Format/Bytes/Invalid/Base16/AllPadding"),
5143 inBuf: `{"Base16": "===="}`,
5144 inVal: new(structFormatBytes),
5145 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5146 _, err := hex.Decode(make([]byte, 2), []byte("====="))
5147 return err
5148 }()},
5149 }, {
5150 name: name("Structs/Format/Bytes/Invalid/Base16/EvenPadding"),
5151 inBuf: `{"Base16": "0123456789abcdef="}`,
5152 inVal: new(structFormatBytes),
5153 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5154 _, err := hex.Decode(make([]byte, 8), []byte("0123456789abcdef="))
5155 return err
5156 }()},
5157 }, {
5158 name: name("Structs/Format/Bytes/Invalid/Base16/OddPadding"),
5159 inBuf: `{"Base16": "0123456789abcdef0="}`,
5160 inVal: new(structFormatBytes),
5161 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5162 _, err := hex.Decode(make([]byte, 9), []byte("0123456789abcdef0="))
5163 return err
5164 }()},
5165 }, {
5166 name: name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/LineFeed"),
5167 inBuf: `{"Base16": "aa\naa"}`,
5168 inVal: new(structFormatBytes),
5169 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5170 _, err := hex.Decode(make([]byte, 9), []byte("aa\naa"))
5171 return err
5172 }()},
5173 }, {
5174 name: name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/CarriageReturn"),
5175 inBuf: `{"Base16": "aa\raa"}`,
5176 inVal: new(structFormatBytes),
5177 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5178 _, err := hex.Decode(make([]byte, 9), []byte("aa\raa"))
5179 return err
5180 }()},
5181 }, {
5182 name: name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/Space"),
5183 inBuf: `{"Base16": "aa aa"}`,
5184 inVal: new(structFormatBytes),
5185 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5186 _, err := hex.Decode(make([]byte, 9), []byte("aa aa"))
5187 return err
5188 }()},
5189 }, {
5190 name: name("Structs/Format/Bytes/Invalid/Base32/Padding"),
5191 inBuf: `[
5192 {"Base32": "NA======"},
5193 {"Base32": "NBSQ===="},
5194 {"Base32": "NBSWY==="},
5195 {"Base32": "NBSWY3A="},
5196 {"Base32": "NBSWY3DP"}
5197 ]`,
5198 inVal: new([]structFormatBytes),
5199 want: addr([]structFormatBytes{
5200 {Base32: []byte("h")},
5201 {Base32: []byte("he")},
5202 {Base32: []byte("hel")},
5203 {Base32: []byte("hell")},
5204 {Base32: []byte("hello")},
5205 }),
5206 }, {
5207 name: name("Structs/Format/Bytes/Invalid/Base32/Invalid/NoPadding"),
5208 inBuf: `[
5209 {"Base32": "NA"},
5210 {"Base32": "NBSQ"},
5211 {"Base32": "NBSWY"},
5212 {"Base32": "NBSWY3A"},
5213 {"Base32": "NBSWY3DP"}
5214 ]`,
5215 inVal: new([]structFormatBytes),
5216 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5217 _, err := base32.StdEncoding.Decode(make([]byte, 1), []byte("NA"))
5218 return err
5219 }()},
5220 }, {
5221 name: name("Structs/Format/Bytes/Invalid/Base32/WrongAlphabet"),
5222 inBuf: `{"Base32": "0123456789ABCDEFGHIJKLMNOPQRSTUV"}`,
5223 inVal: new(structFormatBytes),
5224 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5225 _, err := base32.StdEncoding.Decode(make([]byte, 20), []byte("0123456789ABCDEFGHIJKLMNOPQRSTUV"))
5226 return err
5227 }()},
5228 }, {
5229 name: name("Structs/Format/Bytes/Invalid/Base32Hex/WrongAlphabet"),
5230 inBuf: `{"Base32Hex": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"}`,
5231 inVal: new(structFormatBytes),
5232 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5233 _, err := base32.HexEncoding.Decode(make([]byte, 20), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"))
5234 return err
5235 }()},
5236 }, {
5237 name: name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/LineFeed"),
5238 inBuf: `{"Base32": "AAAA\nAAAA"}`,
5239 inVal: new(structFormatBytes),
5240 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: errors.New("illegal data at input byte 4")},
5241 }, {
5242 name: name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/CarriageReturn"),
5243 inBuf: `{"Base32": "AAAA\rAAAA"}`,
5244 inVal: new(structFormatBytes),
5245 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: errors.New("illegal data at input byte 4")},
5246 }, {
5247 name: name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/Space"),
5248 inBuf: `{"Base32": "AAAA AAAA"}`,
5249 inVal: new(structFormatBytes),
5250 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: base32.CorruptInputError(4)},
5251 }, {
5252 name: name("Structs/Format/Bytes/Invalid/Base64/WrongAlphabet"),
5253 inBuf: `{"Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}`,
5254 inVal: new(structFormatBytes),
5255 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5256 _, err := base64.StdEncoding.Decode(make([]byte, 48), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"))
5257 return err
5258 }()},
5259 }, {
5260 name: name("Structs/Format/Bytes/Invalid/Base64URL/WrongAlphabet"),
5261 inBuf: `{"Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}`,
5262 inVal: new(structFormatBytes),
5263 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: func() error {
5264 _, err := base64.URLEncoding.Decode(make([]byte, 48), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"))
5265 return err
5266 }()},
5267 }, {
5268 name: name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/LineFeed"),
5269 inBuf: `{"Base64": "aa=\n="}`,
5270 inVal: new(structFormatBytes),
5271 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: errors.New("illegal data at input byte 3")},
5272 }, {
5273 name: name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/CarriageReturn"),
5274 inBuf: `{"Base64": "aa=\r="}`,
5275 inVal: new(structFormatBytes),
5276 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: errors.New("illegal data at input byte 3")},
5277 }, {
5278 name: name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/Space"),
5279 inBuf: `{"Base64": "aa= ="}`,
5280 inVal: new(structFormatBytes),
5281 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: bytesType, Err: base64.CorruptInputError(2)},
5282 }, {
5283 name: name("Structs/Format/Floats"),
5284 inBuf: `[
5285 {"NonFinite": 3.141592653589793, "PointerNonFinite": 3.141592653589793},
5286 {"NonFinite": "-Infinity", "PointerNonFinite": "-Infinity"},
5287 {"NonFinite": "Infinity", "PointerNonFinite": "Infinity"}
5288 ]`,
5289 inVal: new([]structFormatFloats),
5290 want: addr([]structFormatFloats{
5291 {NonFinite: math.Pi, PointerNonFinite: addr(math.Pi)},
5292 {NonFinite: math.Inf(-1), PointerNonFinite: addr(math.Inf(-1))},
5293 {NonFinite: math.Inf(+1), PointerNonFinite: addr(math.Inf(+1))},
5294 }),
5295 }, {
5296 name: name("Structs/Format/Floats/NaN"),
5297 inBuf: `{"NonFinite": "NaN"}`,
5298 inVal: new(structFormatFloats),
5299 // Avoid checking want since reflect.DeepEqual fails for NaNs.
5300 }, {
5301 name: name("Structs/Format/Floats/Invalid/NaN"),
5302 inBuf: `{"NonFinite": "nan"}`,
5303 inVal: new(structFormatFloats),
5304 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type},
5305 }, {
5306 name: name("Structs/Format/Floats/Invalid/PositiveInfinity"),
5307 inBuf: `{"NonFinite": "+Infinity"}`,
5308 inVal: new(structFormatFloats),
5309 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type},
5310 }, {
5311 name: name("Structs/Format/Floats/Invalid/NegativeInfinitySpace"),
5312 inBuf: `{"NonFinite": "-Infinity "}`,
5313 inVal: new(structFormatFloats),
5314 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: float64Type},
5315 }, {
5316 name: name("Structs/Format/Maps"),
5317 inBuf: `[
5318 {"EmitNull": null, "PointerEmitNull": null},
5319 {"EmitNull": {}, "PointerEmitNull": {}},
5320 {"EmitNull": {"k": "v"}, "PointerEmitNull": {"k": "v"}}
5321 ]`,
5322 inVal: new([]structFormatMaps),
5323 want: addr([]structFormatMaps{
5324 {EmitNull: nil, PointerEmitNull: nil},
5325 {EmitNull: map[string]string{}, PointerEmitNull: addr(map[string]string{})},
5326 {EmitNull: map[string]string{"k": "v"}, PointerEmitNull: addr(map[string]string{"k": "v"})},
5327 }),
5328 }, {
5329 name: name("Structs/Format/Slices"),
5330 inBuf: `[
5331 {"EmitNull": null, "PointerEmitNull": null},
5332 {"EmitNull": [], "PointerEmitNull": []},
5333 {"EmitNull": ["v"], "PointerEmitNull": ["v"]}
5334 ]`,
5335 inVal: new([]structFormatSlices),
5336 want: addr([]structFormatSlices{
5337 {EmitNull: nil, PointerEmitNull: nil},
5338 {EmitNull: []string{}, PointerEmitNull: addr([]string{})},
5339 {EmitNull: []string{"v"}, PointerEmitNull: addr([]string{"v"})},
5340 }),
5341 }, {
5342 name: name("Structs/Format/Invalid/Bool"),
5343 inBuf: `{"Bool":true}`,
5344 inVal: new(structFormatInvalid),
5345 wantErr: &SemanticError{action: "unmarshal", GoType: boolType, Err: errors.New(`invalid format flag: "invalid"`)},
5346 }, {
5347 name: name("Structs/Format/Invalid/String"),
5348 inBuf: `{"String": "string"}`,
5349 inVal: new(structFormatInvalid),
5350 wantErr: &SemanticError{action: "unmarshal", GoType: stringType, Err: errors.New(`invalid format flag: "invalid"`)},
5351 }, {
5352 name: name("Structs/Format/Invalid/Bytes"),
5353 inBuf: `{"Bytes": "bytes"}`,
5354 inVal: new(structFormatInvalid),
5355 wantErr: &SemanticError{action: "unmarshal", GoType: bytesType, Err: errors.New(`invalid format flag: "invalid"`)},
5356 }, {
5357 name: name("Structs/Format/Invalid/Int"),
5358 inBuf: `{"Int": 1}`,
5359 inVal: new(structFormatInvalid),
5360 wantErr: &SemanticError{action: "unmarshal", GoType: int64Type, Err: errors.New(`invalid format flag: "invalid"`)},
5361 }, {
5362 name: name("Structs/Format/Invalid/Uint"),
5363 inBuf: `{"Uint": 1}`,
5364 inVal: new(structFormatInvalid),
5365 wantErr: &SemanticError{action: "unmarshal", GoType: uint64Type, Err: errors.New(`invalid format flag: "invalid"`)},
5366 }, {
5367 name: name("Structs/Format/Invalid/Float"),
5368 inBuf: `{"Float": 1}`,
5369 inVal: new(structFormatInvalid),
5370 wantErr: &SemanticError{action: "unmarshal", GoType: float64Type, Err: errors.New(`invalid format flag: "invalid"`)},
5371 }, {
5372 name: name("Structs/Format/Invalid/Map"),
5373 inBuf: `{"Map":{}}`,
5374 inVal: new(structFormatInvalid),
5375 wantErr: &SemanticError{action: "unmarshal", GoType: mapStringStringType, Err: errors.New(`invalid format flag: "invalid"`)},
5376 }, {
5377 name: name("Structs/Format/Invalid/Struct"),
5378 inBuf: `{"Struct": {}}`,
5379 inVal: new(structFormatInvalid),
5380 wantErr: &SemanticError{action: "unmarshal", GoType: structAllType, Err: errors.New(`invalid format flag: "invalid"`)},
5381 }, {
5382 name: name("Structs/Format/Invalid/Slice"),
5383 inBuf: `{"Slice": {}}`,
5384 inVal: new(structFormatInvalid),
5385 wantErr: &SemanticError{action: "unmarshal", GoType: sliceStringType, Err: errors.New(`invalid format flag: "invalid"`)},
5386 }, {
5387 name: name("Structs/Format/Invalid/Array"),
5388 inBuf: `{"Array": []}`,
5389 inVal: new(structFormatInvalid),
5390 wantErr: &SemanticError{action: "unmarshal", GoType: array1StringType, Err: errors.New(`invalid format flag: "invalid"`)},
5391 }, {
5392 name: name("Structs/Format/Invalid/Interface"),
5393 inBuf: `{"Interface": "anything"}`,
5394 inVal: new(structFormatInvalid),
5395 wantErr: &SemanticError{action: "unmarshal", GoType: anyType, Err: errors.New(`invalid format flag: "invalid"`)},
5396 }, {
5397 name: name("Structs/Inline/Zero"),
5398 inBuf: `{"D":""}`,
5399 inVal: new(structInlined),
5400 want: new(structInlined),
5401 }, {
5402 name: name("Structs/Inline/Alloc"),
5403 inBuf: `{"E":"","F":"","G":"","A":"","B":"","D":""}`,
5404 inVal: new(structInlined),
5405 want: addr(structInlined{
5406 X: structInlinedL1{
5407 X: &structInlinedL2{},
5408 StructEmbed1: StructEmbed1{},
5409 },
5410 StructEmbed2: &StructEmbed2{},
5411 }),
5412 }, {
5413 name: name("Structs/Inline/NonZero"),
5414 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
5415 inVal: new(structInlined),
5416 want: addr(structInlined{
5417 X: structInlinedL1{
5418 X: &structInlinedL2{A: "A1", B: "B1" /* C: "C1" */},
5419 StructEmbed1: StructEmbed1{ /* C: "C2" */ D: "D2" /* E: "E2" */},
5420 },
5421 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
5422 }),
5423 }, {
5424 name: name("Structs/Inline/Merge"),
5425 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
5426 inVal: addr(structInlined{
5427 X: structInlinedL1{
5428 X: &structInlinedL2{B: "##", C: "C1"},
5429 StructEmbed1: StructEmbed1{C: "C2", E: "E2"},
5430 },
5431 StructEmbed2: &StructEmbed2{E: "##", G: "G3"},
5432 }),
5433 want: addr(structInlined{
5434 X: structInlinedL1{
5435 X: &structInlinedL2{A: "A1", B: "B1", C: "C1"},
5436 StructEmbed1: StructEmbed1{C: "C2", D: "D2", E: "E2"},
5437 },
5438 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
5439 }),
5440 }, {
5441 name: name("Structs/InlinedFallback/RawValue/Noop"),
5442 inBuf: `{"A":1,"B":2}`,
5443 inVal: new(structInlineRawValue),
5444 want: addr(structInlineRawValue{A: 1, X: RawValue(nil), B: 2}),
5445 }, {
5446 name: name("Structs/InlinedFallback/RawValue/MergeN1/Nil"),
5447 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5448 inVal: new(structInlineRawValue),
5449 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":"buzz"}`), B: 2}),
5450 }, {
5451 name: name("Structs/InlinedFallback/RawValue/MergeN1/Empty"),
5452 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5453 inVal: addr(structInlineRawValue{X: RawValue{}}),
5454 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":"buzz"}`), B: 2}),
5455 }, {
5456 name: name("Structs/InlinedFallback/RawValue/MergeN1/Whitespace"),
5457 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5458 inVal: addr(structInlineRawValue{X: RawValue("\n\r\t ")}),
5459 want: addr(structInlineRawValue{A: 1, X: RawValue("")}),
5460 wantErr: &SemanticError{action: "unmarshal", GoType: rawValueType, Err: errors.New("inlined raw value must be a JSON object")},
5461 }, {
5462 name: name("Structs/InlinedFallback/RawValue/MergeN1/Null"),
5463 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5464 inVal: addr(structInlineRawValue{X: RawValue("null")}),
5465 want: addr(structInlineRawValue{A: 1, X: RawValue("null")}),
5466 wantErr: &SemanticError{action: "unmarshal", GoType: rawValueType, Err: errors.New("inlined raw value must be a JSON object")},
5467 }, {
5468 name: name("Structs/InlinedFallback/RawValue/MergeN1/ObjectN0"),
5469 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5470 inVal: addr(structInlineRawValue{X: RawValue(` { } `)}),
5471 want: addr(structInlineRawValue{A: 1, X: RawValue(` {"fizz":"buzz"}`), B: 2}),
5472 }, {
5473 name: name("Structs/InlinedFallback/RawValue/MergeN2/ObjectN1"),
5474 inBuf: `{"A":1,"fizz":"buzz","B":2,"foo": [ 1 , 2 , 3 ]}`,
5475 inVal: addr(structInlineRawValue{X: RawValue(` { "fizz" : "buzz" } `)}),
5476 want: addr(structInlineRawValue{A: 1, X: RawValue(` { "fizz" : "buzz","fizz":"buzz","foo":[ 1 , 2 , 3 ]}`), B: 2}),
5477 }, {
5478 name: name("Structs/InlinedFallback/RawValue/Merge/ObjectEnd"),
5479 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5480 inVal: addr(structInlineRawValue{X: RawValue(` } `)}),
5481 // NOTE: This produces invalid output,
5482 // but the value being merged into is already invalid.
5483 want: addr(structInlineRawValue{A: 1, X: RawValue(`,"fizz":"buzz"}`), B: 2}),
5484 }, {
5485 name: name("Structs/InlinedFallback/RawValue/MergeInvalidValue"),
5486 inBuf: `{"A":1,"fizz":nil,"B":2}`,
5487 inVal: new(structInlineRawValue),
5488 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":`)}),
5489 wantErr: newInvalidCharacterError([]byte("i"), "within literal null (expecting 'u')").withOffset(int64(len(`{"A":1,"fizz":n`))),
5490 }, {
5491 name: name("Structs/InlinedFallback/RawValue/CaseSensitive"),
5492 inBuf: `{"A":1,"fizz":"buzz","B":2,"a":3}`,
5493 inVal: new(structInlineRawValue),
5494 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":"buzz","a":3}`), B: 2}),
5495 }, {
5496 name: name("Structs/InlinedFallback/RawValue/RejectDuplicateNames"),
5497 dopts: DecodeOptions{AllowDuplicateNames: false},
5498 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
5499 inVal: new(structInlineRawValue),
5500 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":"buzz"}`), B: 2}),
5501 wantErr: (&SyntacticError{str: `duplicate name "fizz" in object`}).withOffset(int64(len(`{"A":1,"fizz":"buzz","B":2,`))),
5502 }, {
5503 name: name("Structs/InlinedFallback/RawValue/AllowDuplicateNames"),
5504 dopts: DecodeOptions{AllowDuplicateNames: true},
5505 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
5506 inVal: new(structInlineRawValue),
5507 want: addr(structInlineRawValue{A: 1, X: RawValue(`{"fizz":"buzz","fizz":"buzz"}`), B: 2}),
5508 }, {
5509 name: name("Structs/InlinedFallback/RawValue/Nested/Noop"),
5510 inBuf: `{}`,
5511 inVal: new(structInlinePointerInlineRawValue),
5512 want: new(structInlinePointerInlineRawValue),
5513 }, {
5514 name: name("Structs/InlinedFallback/RawValue/Nested/Alloc"),
5515 inBuf: `{"A":1,"fizz":"buzz"}`,
5516 inVal: new(structInlinePointerInlineRawValue),
5517 want: addr(structInlinePointerInlineRawValue{
5518 X: &struct {
5519 A int
5520 X RawValue `json:",inline"`
5521 }{A: 1, X: RawValue(`{"fizz":"buzz"}`)},
5522 }),
5523 }, {
5524 name: name("Structs/InlinedFallback/RawValue/Nested/Merge"),
5525 inBuf: `{"fizz":"buzz"}`,
5526 inVal: addr(structInlinePointerInlineRawValue{
5527 X: &struct {
5528 A int
5529 X RawValue `json:",inline"`
5530 }{A: 1},
5531 }),
5532 want: addr(structInlinePointerInlineRawValue{
5533 X: &struct {
5534 A int
5535 X RawValue `json:",inline"`
5536 }{A: 1, X: RawValue(`{"fizz":"buzz"}`)},
5537 }),
5538 }, {
5539 name: name("Structs/InlinedFallback/PointerRawValue/Noop"),
5540 inBuf: `{"A":1,"B":2}`,
5541 inVal: new(structInlinePointerRawValue),
5542 want: addr(structInlinePointerRawValue{A: 1, X: nil, B: 2}),
5543 }, {
5544 name: name("Structs/InlinedFallback/PointerRawValue/Alloc"),
5545 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5546 inVal: new(structInlinePointerRawValue),
5547 want: addr(structInlinePointerRawValue{A: 1, X: addr(RawValue(`{"fizz":"buzz"}`)), B: 2}),
5548 }, {
5549 name: name("Structs/InlinedFallback/PointerRawValue/Merge"),
5550 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5551 inVal: addr(structInlinePointerRawValue{X: addr(RawValue(`{"fizz":"buzz"}`))}),
5552 want: addr(structInlinePointerRawValue{A: 1, X: addr(RawValue(`{"fizz":"buzz","fizz":"buzz"}`)), B: 2}),
5553 }, {
5554 name: name("Structs/InlinedFallback/PointerRawValue/Nested/Nil"),
5555 inBuf: `{"fizz":"buzz"}`,
5556 inVal: new(structInlineInlinePointerRawValue),
5557 want: addr(structInlineInlinePointerRawValue{
5558 X: struct {
5559 X *RawValue `json:",inline"`
5560 }{X: addr(RawValue(`{"fizz":"buzz"}`))},
5561 }),
5562 }, {
5563 name: name("Structs/InlinedFallback/MapStringAny/Noop"),
5564 inBuf: `{"A":1,"B":2}`,
5565 inVal: new(structInlineMapStringAny),
5566 want: addr(structInlineMapStringAny{A: 1, X: nil, B: 2}),
5567 }, {
5568 name: name("Structs/InlinedFallback/MapStringAny/MergeN1/Nil"),
5569 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5570 inVal: new(structInlineMapStringAny),
5571 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
5572 }, {
5573 name: name("Structs/InlinedFallback/MapStringAny/MergeN1/Empty"),
5574 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5575 inVal: addr(structInlineMapStringAny{X: jsonObject{}}),
5576 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
5577 }, {
5578 name: name("Structs/InlinedFallback/MapStringAny/MergeN1/ObjectN1"),
5579 inBuf: `{"A":1,"fizz":{"charlie":"DELTA","echo":"foxtrot"},"B":2}`,
5580 inVal: addr(structInlineMapStringAny{X: jsonObject{"fizz": jsonObject{
5581 "alpha": "bravo",
5582 "charlie": "delta",
5583 }}}),
5584 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": jsonObject{
5585 "alpha": "bravo",
5586 "charlie": "DELTA",
5587 "echo": "foxtrot",
5588 }}, B: 2}),
5589 }, {
5590 name: name("Structs/InlinedFallback/MapStringAny/MergeN2/ObjectN1"),
5591 inBuf: `{"A":1,"fizz":"buzz","B":2,"foo": [ 1 , 2 , 3 ]}`,
5592 inVal: addr(structInlineMapStringAny{X: jsonObject{"fizz": "wuzz"}}),
5593 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz", "foo": jsonArray{1.0, 2.0, 3.0}}, B: 2}),
5594 }, {
5595 name: name("Structs/InlinedFallback/MapStringAny/MergeInvalidValue"),
5596 inBuf: `{"A":1,"fizz":nil,"B":2}`,
5597 inVal: new(structInlineMapStringAny),
5598 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": nil}}),
5599 wantErr: newInvalidCharacterError([]byte("i"), "within literal null (expecting 'u')").withOffset(int64(len(`{"A":1,"fizz":n`))),
5600 }, {
5601 name: name("Structs/InlinedFallback/MapStringAny/MergeInvalidValue/Existing"),
5602 inBuf: `{"A":1,"fizz":nil,"B":2}`,
5603 inVal: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": true}}),
5604 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": true}}),
5605 wantErr: newInvalidCharacterError([]byte("i"), "within literal null (expecting 'u')").withOffset(int64(len(`{"A":1,"fizz":n`))),
5606 }, {
5607 name: name("Structs/InlinedFallback/MapStringAny/CaseSensitive"),
5608 inBuf: `{"A":1,"fizz":"buzz","B":2,"a":3}`,
5609 inVal: new(structInlineMapStringAny),
5610 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz", "a": 3.0}, B: 2}),
5611 }, {
5612 name: name("Structs/InlinedFallback/MapStringAny/RejectDuplicateNames"),
5613 dopts: DecodeOptions{AllowDuplicateNames: false},
5614 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
5615 inVal: new(structInlineMapStringAny),
5616 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
5617 wantErr: (&SyntacticError{str: `duplicate name "fizz" in object`}).withOffset(int64(len(`{"A":1,"fizz":"buzz","B":2,`))),
5618 }, {
5619 name: name("Structs/InlinedFallback/MapStringAny/AllowDuplicateNames"),
5620 dopts: DecodeOptions{AllowDuplicateNames: true},
5621 inBuf: `{"A":1,"fizz":{"one":1,"two":-2},"B":2,"fizz":{"two":2,"three":3}}`,
5622 inVal: new(structInlineMapStringAny),
5623 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": jsonObject{"one": 1.0, "two": 2.0, "three": 3.0}}, B: 2}),
5624 }, {
5625 name: name("Structs/InlinedFallback/MapStringAny/Nested/Noop"),
5626 inBuf: `{}`,
5627 inVal: new(structInlinePointerInlineMapStringAny),
5628 want: new(structInlinePointerInlineMapStringAny),
5629 }, {
5630 name: name("Structs/InlinedFallback/MapStringAny/Nested/Alloc"),
5631 inBuf: `{"A":1,"fizz":"buzz"}`,
5632 inVal: new(structInlinePointerInlineMapStringAny),
5633 want: addr(structInlinePointerInlineMapStringAny{
5634 X: &struct {
5635 A int
5636 X jsonObject `json:",inline"`
5637 }{A: 1, X: jsonObject{"fizz": "buzz"}},
5638 }),
5639 }, {
5640 name: name("Structs/InlinedFallback/MapStringAny/Nested/Merge"),
5641 inBuf: `{"fizz":"buzz"}`,
5642 inVal: addr(structInlinePointerInlineMapStringAny{
5643 X: &struct {
5644 A int
5645 X jsonObject `json:",inline"`
5646 }{A: 1},
5647 }),
5648 want: addr(structInlinePointerInlineMapStringAny{
5649 X: &struct {
5650 A int
5651 X jsonObject `json:",inline"`
5652 }{A: 1, X: jsonObject{"fizz": "buzz"}},
5653 }),
5654 }, {
5655 name: name("Structs/InlinedFallback/MapStringInt/UnmarshalFuncV1"),
5656 uopts: UnmarshalOptions{
5657 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *any) error {
5658 var err error
5659 *v, err = strconv.ParseFloat(string(bytes.Trim(b, `"`)), 64)
5660 return err
5661 }),
5662 },
5663 inBuf: `{"D":"1.1","E":"2.2","F":"3.3"}`,
5664 inVal: new(structInlineMapStringAny),
5665 want: addr(structInlineMapStringAny{X: jsonObject{"D": 1.1, "E": 2.2, "F": 3.3}}),
5666 }, {
5667 name: name("Structs/InlinedFallback/PointerMapStringAny/Noop"),
5668 inBuf: `{"A":1,"B":2}`,
5669 inVal: new(structInlinePointerMapStringAny),
5670 want: addr(structInlinePointerMapStringAny{A: 1, X: nil, B: 2}),
5671 }, {
5672 name: name("Structs/InlinedFallback/PointerMapStringAny/Alloc"),
5673 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5674 inVal: new(structInlinePointerMapStringAny),
5675 want: addr(structInlinePointerMapStringAny{A: 1, X: addr(jsonObject{"fizz": "buzz"}), B: 2}),
5676 }, {
5677 name: name("Structs/InlinedFallback/PointerMapStringAny/Merge"),
5678 inBuf: `{"A":1,"fizz":"wuzz","B":2}`,
5679 inVal: addr(structInlinePointerMapStringAny{X: addr(jsonObject{"fizz": "buzz"})}),
5680 want: addr(structInlinePointerMapStringAny{A: 1, X: addr(jsonObject{"fizz": "wuzz"}), B: 2}),
5681 }, {
5682 name: name("Structs/InlinedFallback/PointerMapStringAny/Nested/Nil"),
5683 inBuf: `{"fizz":"buzz"}`,
5684 inVal: new(structInlineInlinePointerMapStringAny),
5685 want: addr(structInlineInlinePointerMapStringAny{
5686 X: struct {
5687 X *jsonObject `json:",inline"`
5688 }{X: addr(jsonObject{"fizz": "buzz"})},
5689 }),
5690 }, {
5691 name: name("Structs/InlinedFallback/MapStringInt"),
5692 inBuf: `{"zero": 0, "one": 1, "two": 2}`,
5693 inVal: new(structInlineMapStringInt),
5694 want: addr(structInlineMapStringInt{
5695 X: map[string]int{"zero": 0, "one": 1, "two": 2},
5696 }),
5697 }, {
5698 name: name("Structs/InlinedFallback/MapStringInt/Null"),
5699 inBuf: `{"zero": 0, "one": null, "two": 2}`,
5700 inVal: new(structInlineMapStringInt),
5701 want: addr(structInlineMapStringInt{
5702 X: map[string]int{"zero": 0, "one": 0, "two": 2},
5703 }),
5704 }, {
5705 name: name("Structs/InlinedFallback/MapStringInt/Invalid"),
5706 inBuf: `{"zero": 0, "one": {}, "two": 2}`,
5707 inVal: new(structInlineMapStringInt),
5708 want: addr(structInlineMapStringInt{
5709 X: map[string]int{"zero": 0, "one": 0},
5710 }),
5711 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: intType},
5712 }, {
5713 name: name("Structs/InlinedFallback/MapStringInt/StringifiedNumbers"),
5714 uopts: UnmarshalOptions{StringifyNumbers: true},
5715 inBuf: `{"zero": 0, "one": "1", "two": 2}`,
5716 inVal: new(structInlineMapStringInt),
5717 want: addr(structInlineMapStringInt{
5718 X: map[string]int{"zero": 0, "one": 1, "two": 2},
5719 }),
5720 }, {
5721 name: name("Structs/InlinedFallback/MapStringInt/UnmarshalFuncV1"),
5722 uopts: UnmarshalOptions{
5723 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *int) error {
5724 i, err := strconv.ParseInt(string(bytes.Trim(b, `"`)), 10, 64)
5725 if err != nil {
5726 return err
5727 }
5728 *v = int(i)
5729 return nil
5730 }),
5731 },
5732 inBuf: `{"zero": "0", "one": "1", "two": "2"}`,
5733 inVal: new(structInlineMapStringInt),
5734 want: addr(structInlineMapStringInt{
5735 X: map[string]int{"zero": 0, "one": 1, "two": 2},
5736 }),
5737 }, {
5738 name: name("Structs/InlinedFallback/RejectUnknownMembers"),
5739 uopts: UnmarshalOptions{RejectUnknownMembers: true},
5740 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5741 inVal: new(structInlineRawValue),
5742 // NOTE: DiscardUnknownMembers has no effect since this is "inline".
5743 want: addr(structInlineRawValue{
5744 A: 1,
5745 X: RawValue(`{"fizz":"buzz"}`),
5746 B: 2,
5747 }),
5748 }, {
5749 name: name("Structs/UnknownFallback/RejectUnknownMembers"),
5750 uopts: UnmarshalOptions{RejectUnknownMembers: true},
5751 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5752 inVal: new(structUnknownRawValue),
5753 want: addr(structUnknownRawValue{A: 1}),
5754 wantErr: &SemanticError{action: "unmarshal", GoType: structUnknownRawValueType, Err: errors.New(`unknown name "fizz"`)},
5755 }, {
5756 name: name("Structs/UnknownFallback"),
5757 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
5758 inVal: new(structUnknownRawValue),
5759 want: addr(structUnknownRawValue{
5760 A: 1,
5761 X: RawValue(`{"fizz":"buzz"}`),
5762 B: 2,
5763 }),
5764 }, {
5765 name: name("Structs/UnknownIgnored"),
5766 uopts: UnmarshalOptions{RejectUnknownMembers: false},
5767 inBuf: `{"unknown":"fizzbuzz"}`,
5768 inVal: new(structAll),
5769 want: new(structAll),
5770 }, {
5771 name: name("Structs/RejectUnknownMembers"),
5772 uopts: UnmarshalOptions{RejectUnknownMembers: true},
5773 inBuf: `{"unknown":"fizzbuzz"}`,
5774 inVal: new(structAll),
5775 want: new(structAll),
5776 wantErr: &SemanticError{action: "unmarshal", GoType: structAllType, Err: errors.New(`unknown name "unknown"`)},
5777 }, {
5778 name: name("Structs/UnexportedIgnored"),
5779 inBuf: `{"ignored":"unused"}`,
5780 inVal: new(structUnexportedIgnored),
5781 want: new(structUnexportedIgnored),
5782 }, {
5783 name: name("Structs/IgnoredUnexportedEmbedded"),
5784 inBuf: `{"namedString":"unused"}`,
5785 inVal: new(structIgnoredUnexportedEmbedded),
5786 want: new(structIgnoredUnexportedEmbedded),
5787 }, {
5788 name: name("Structs/WeirdNames"),
5789 inBuf: `{"":"empty",",":"comma","\"":"quote"}`,
5790 inVal: new(structWeirdNames),
5791 want: addr(structWeirdNames{Empty: "empty", Comma: "comma", Quote: "quote"}),
5792 }, {
5793 name: name("Structs/NoCase/Exact"),
5794 inBuf: `{"AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
5795 inVal: new(structNoCase),
5796 want: addr(structNoCase{AaA: "AaA", AAa: "AAa", AAA: "AAA"}),
5797 }, {
5798 name: name("Structs/NoCase/Merge/AllowDuplicateNames"),
5799 dopts: DecodeOptions{AllowDuplicateNames: true},
5800 inBuf: `{"AaA":"AaA","aaa":"aaa","aAa":"aAa"}`,
5801 inVal: new(structNoCase),
5802 want: addr(structNoCase{AaA: "aAa"}),
5803 }, {
5804 name: name("Structs/NoCase/Merge/RejectDuplicateNames"),
5805 dopts: DecodeOptions{AllowDuplicateNames: false},
5806 inBuf: `{"AaA":"AaA","aaa":"aaa"}`,
5807 inVal: new(structNoCase),
5808 want: addr(structNoCase{AaA: "AaA"}),
5809 wantErr: (&SyntacticError{str: `duplicate name "aaa" in object`}).withOffset(int64(len(`{"AaA":"AaA",`))),
5810 }, {
5811 name: name("Structs/CaseSensitive"),
5812 inBuf: `{"BOOL": true, "STRING": "hello", "BYTES": "AQID", "INT": -64, "UINT": 64, "FLOAT": 3.14159}`,
5813 inVal: new(structScalars),
5814 want: addr(structScalars{}),
5815 }, {
5816 name: name("Structs/DuplicateName/NoCase/ExactDifferent"),
5817 inBuf: `{"AAA":"AAA","AaA":"AaA","AAa":"AAa","Aaa":"Aaa"}`,
5818 inVal: addr(structNoCaseInlineRawValue{}),
5819 want: addr(structNoCaseInlineRawValue{AAA: "AAA", AaA: "AaA", AAa: "AAa", Aaa: "Aaa"}),
5820 }, {
5821 name: name("Structs/DuplicateName/NoCase/ExactConflict"),
5822 inBuf: `{"AAA":"AAA","AAA":"AAA"}`,
5823 inVal: addr(structNoCaseInlineRawValue{}),
5824 want: addr(structNoCaseInlineRawValue{AAA: "AAA"}),
5825 wantErr: (&SyntacticError{str: `duplicate name "AAA" in object`}).withOffset(int64(len(`{"AAA":"AAA",`))),
5826 }, {
5827 name: name("Structs/DuplicateName/NoCase/OverwriteExact"),
5828 inBuf: `{"AAA":"after"}`,
5829 inVal: addr(structNoCaseInlineRawValue{AAA: "before"}),
5830 want: addr(structNoCaseInlineRawValue{AAA: "after"}),
5831 }, {
5832 name: name("Structs/DuplicateName/NoCase/NoCaseConflict"),
5833 inBuf: `{"aaa":"aaa","aaA":"aaA"}`,
5834 inVal: addr(structNoCaseInlineRawValue{}),
5835 want: addr(structNoCaseInlineRawValue{AaA: "aaa"}),
5836 wantErr: (&SyntacticError{str: `duplicate name "aaA" in object`}).withOffset(int64(len(`{"aaa":"aaa",`))),
5837 }, {
5838 name: name("Structs/DuplicateName/NoCase/OverwriteNoCase"),
5839 inBuf: `{"aaa":"aaa","aaA":"aaA"}`,
5840 inVal: addr(structNoCaseInlineRawValue{}),
5841 want: addr(structNoCaseInlineRawValue{AaA: "aaa"}),
5842 wantErr: (&SyntacticError{str: `duplicate name "aaA" in object`}).withOffset(int64(len(`{"aaa":"aaa",`))),
5843 }, {
5844 name: name("Structs/DuplicateName/Inline/Unknown"),
5845 inBuf: `{"unknown":""}`,
5846 inVal: addr(structNoCaseInlineRawValue{}),
5847 want: addr(structNoCaseInlineRawValue{X: RawValue(`{"unknown":""}`)}),
5848 }, {
5849 name: name("Structs/DuplicateName/Inline/UnknownMerge"),
5850 inBuf: `{"unknown":""}`,
5851 inVal: addr(structNoCaseInlineRawValue{X: RawValue(`{"unknown":""}`)}),
5852 want: addr(structNoCaseInlineRawValue{X: RawValue(`{"unknown":"","unknown":""}`)}),
5853 }, {
5854 name: name("Structs/DuplicateName/Inline/NoCaseOkay"),
5855 inBuf: `{"b":"","B":""}`,
5856 inVal: addr(structNoCaseInlineRawValue{}),
5857 want: addr(structNoCaseInlineRawValue{X: RawValue(`{"b":"","B":""}`)}),
5858 }, {
5859 name: name("Structs/DuplicateName/Inline/ExactConflict"),
5860 inBuf: `{"b":"","b":""}`,
5861 inVal: addr(structNoCaseInlineRawValue{}),
5862 want: addr(structNoCaseInlineRawValue{X: RawValue(`{"b":""}`)}),
5863 wantErr: (&SyntacticError{str: `duplicate name "b" in object`}).withOffset(int64(len(`{"b":"",`))),
5864 }, {
5865 name: name("Structs/Invalid/ErrUnexpectedEOF"),
5866 inBuf: ``,
5867 inVal: addr(structAll{}),
5868 want: addr(structAll{}),
5869 wantErr: io.ErrUnexpectedEOF,
5870 }, {
5871 name: name("Structs/Invalid/NestedErrUnexpectedEOF"),
5872 inBuf: `{"Pointer":`,
5873 inVal: addr(structAll{}),
5874 want: addr(structAll{Pointer: new(structAll)}),
5875 wantErr: io.ErrUnexpectedEOF,
5876 }, {
5877 name: name("Structs/Invalid/Conflicting"),
5878 inBuf: `{}`,
5879 inVal: addr(structConflicting{}),
5880 want: addr(structConflicting{}),
5881 wantErr: &SemanticError{action: "unmarshal", GoType: structConflictingType, Err: errors.New("Go struct fields A and B conflict over JSON object name \"conflict\"")},
5882 }, {
5883 name: name("Structs/Invalid/NoneExported"),
5884 inBuf: `{}`,
5885 inVal: addr(structNoneExported{}),
5886 want: addr(structNoneExported{}),
5887 wantErr: &SemanticError{action: "unmarshal", GoType: structNoneExportedType, Err: errors.New("Go struct has no exported fields")},
5888 }, {
5889 name: name("Structs/Invalid/MalformedTag"),
5890 inBuf: `{}`,
5891 inVal: addr(structMalformedTag{}),
5892 want: addr(structMalformedTag{}),
5893 wantErr: &SemanticError{action: "unmarshal", GoType: structMalformedTagType, Err: errors.New("Go struct field Malformed has malformed `json` tag: invalid character '\"' at start of option (expecting Unicode letter or single quote)")},
5894 }, {
5895 name: name("Structs/Invalid/UnexportedTag"),
5896 inBuf: `{}`,
5897 inVal: addr(structUnexportedTag{}),
5898 want: addr(structUnexportedTag{}),
5899 wantErr: &SemanticError{action: "unmarshal", GoType: structUnexportedTagType, Err: errors.New("unexported Go struct field unexported cannot have non-ignored `json:\"name\"` tag")},
5900 }, {
5901 name: name("Structs/Invalid/UnexportedEmbedded"),
5902 inBuf: `{}`,
5903 inVal: addr(structUnexportedEmbedded{}),
5904 want: addr(structUnexportedEmbedded{}),
5905 wantErr: &SemanticError{action: "unmarshal", GoType: structUnexportedEmbeddedType, Err: errors.New("embedded Go struct field namedString of an unexported type must be explicitly ignored with a `json:\"-\"` tag")},
5906 }, {
5907 name: name("Structs/Unknown"),
5908 inBuf: `{
5909 "object0": {},
5910 "object1": {"key1": "value"},
5911 "object2": {"key1": "value", "key2": "value"},
5912 "objects": {"":{"":{"":{}}}},
5913 "array0": [],
5914 "array1": ["value1"],
5915 "array2": ["value1", "value2"],
5916 "array": [[[]]],
5917 "scalars": [null, false, true, "string", 12.345]
5918 }`,
5919 inVal: addr(struct{}{}),
5920 want: addr(struct{}{}),
5921 }, {
5922 name: name("Structs/IgnoreInvalidFormat"),
5923 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
5924 inBuf: `{"Field":"Value"}`,
5925 inVal: addr(struct{ Field string }{}),
5926 want: addr(struct{ Field string }{"Value"}),
5927 }, {
5928 name: name("Slices/Null"),
5929 inBuf: `null`,
5930 inVal: addr([]string{"something"}),
5931 want: addr([]string(nil)),
5932 }, {
5933 name: name("Slices/Bool"),
5934 inBuf: `[true,false]`,
5935 inVal: new([]bool),
5936 want: addr([]bool{true, false}),
5937 }, {
5938 name: name("Slices/String"),
5939 inBuf: `["hello","goodbye"]`,
5940 inVal: new([]string),
5941 want: addr([]string{"hello", "goodbye"}),
5942 }, {
5943 name: name("Slices/Bytes"),
5944 inBuf: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
5945 inVal: new([][]byte),
5946 want: addr([][]byte{[]byte("hello"), []byte("goodbye")}),
5947 }, {
5948 name: name("Slices/Int"),
5949 inBuf: `[-2,-1,0,1,2]`,
5950 inVal: new([]int),
5951 want: addr([]int{-2, -1, 0, 1, 2}),
5952 }, {
5953 name: name("Slices/Uint"),
5954 inBuf: `[0,1,2,3,4]`,
5955 inVal: new([]uint),
5956 want: addr([]uint{0, 1, 2, 3, 4}),
5957 }, {
5958 name: name("Slices/Float"),
5959 inBuf: `[3.14159,12.34]`,
5960 inVal: new([]float64),
5961 want: addr([]float64{3.14159, 12.34}),
5962 }, {
5963 // NOTE: The semantics differs from v1, where the slice length is reset
5964 // and new elements are appended to the end.
5965 // See https://go.dev/issue/21092.
5966 name: name("Slices/Merge"),
5967 inBuf: `[{"k3":"v3"},{"k4":"v4"}]`,
5968 inVal: addr([]map[string]string{{"k1": "v1"}, {"k2": "v2"}}[:1]),
5969 want: addr([]map[string]string{{"k3": "v3"}, {"k4": "v4"}}),
5970 }, {
5971 name: name("Slices/Invalid/Channel"),
5972 inBuf: `["hello"]`,
5973 inVal: new([]chan string),
5974 want: addr([]chan string{nil}),
5975 wantErr: &SemanticError{action: "unmarshal", GoType: chanStringType},
5976 }, {
5977 name: name("Slices/RecursiveSlice"),
5978 inBuf: `[[],[],[[]],[[],[]]]`,
5979 inVal: new(recursiveSlice),
5980 want: addr(recursiveSlice{
5981 {},
5982 {},
5983 {{}},
5984 {{}, {}},
5985 }),
5986 }, {
5987 name: name("Slices/Invalid/Bool"),
5988 inBuf: `true`,
5989 inVal: addr([]string{"nochange"}),
5990 want: addr([]string{"nochange"}),
5991 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: sliceStringType},
5992 }, {
5993 name: name("Slices/Invalid/String"),
5994 inBuf: `""`,
5995 inVal: addr([]string{"nochange"}),
5996 want: addr([]string{"nochange"}),
5997 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: sliceStringType},
5998 }, {
5999 name: name("Slices/Invalid/Number"),
6000 inBuf: `0`,
6001 inVal: addr([]string{"nochange"}),
6002 want: addr([]string{"nochange"}),
6003 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: sliceStringType},
6004 }, {
6005 name: name("Slices/Invalid/Object"),
6006 inBuf: `{}`,
6007 inVal: addr([]string{"nochange"}),
6008 want: addr([]string{"nochange"}),
6009 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: sliceStringType},
6010 }, {
6011 name: name("Slices/IgnoreInvalidFormat"),
6012 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
6013 inBuf: `[false,true]`,
6014 inVal: addr([]bool{true, false}),
6015 want: addr([]bool{false, true}),
6016 }, {
6017 name: name("Arrays/Null"),
6018 inBuf: `null`,
6019 inVal: addr([1]string{"something"}),
6020 want: addr([1]string{}),
6021 }, {
6022 name: name("Arrays/Bool"),
6023 inBuf: `[true,false]`,
6024 inVal: new([2]bool),
6025 want: addr([2]bool{true, false}),
6026 }, {
6027 name: name("Arrays/String"),
6028 inBuf: `["hello","goodbye"]`,
6029 inVal: new([2]string),
6030 want: addr([2]string{"hello", "goodbye"}),
6031 }, {
6032 name: name("Arrays/Bytes"),
6033 inBuf: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
6034 inVal: new([2][]byte),
6035 want: addr([2][]byte{[]byte("hello"), []byte("goodbye")}),
6036 }, {
6037 name: name("Arrays/Int"),
6038 inBuf: `[-2,-1,0,1,2]`,
6039 inVal: new([5]int),
6040 want: addr([5]int{-2, -1, 0, 1, 2}),
6041 }, {
6042 name: name("Arrays/Uint"),
6043 inBuf: `[0,1,2,3,4]`,
6044 inVal: new([5]uint),
6045 want: addr([5]uint{0, 1, 2, 3, 4}),
6046 }, {
6047 name: name("Arrays/Float"),
6048 inBuf: `[3.14159,12.34]`,
6049 inVal: new([2]float64),
6050 want: addr([2]float64{3.14159, 12.34}),
6051 }, {
6052 // NOTE: The semantics differs from v1, where elements are not merged.
6053 // This is to maintain consistent merge semantics with slices.
6054 name: name("Arrays/Merge"),
6055 inBuf: `[{"k3":"v3"},{"k4":"v4"}]`,
6056 inVal: addr([2]map[string]string{{"k1": "v1"}, {"k2": "v2"}}),
6057 want: addr([2]map[string]string{{"k3": "v3"}, {"k4": "v4"}}),
6058 }, {
6059 name: name("Arrays/Invalid/Channel"),
6060 inBuf: `["hello"]`,
6061 inVal: new([1]chan string),
6062 want: new([1]chan string),
6063 wantErr: &SemanticError{action: "unmarshal", GoType: chanStringType},
6064 }, {
6065 name: name("Arrays/Invalid/Underflow"),
6066 inBuf: `[]`,
6067 inVal: new([1]string),
6068 want: addr([1]string{}),
6069 wantErr: &SemanticError{action: "unmarshal", GoType: array1StringType, Err: errors.New("too few array elements")},
6070 }, {
6071 name: name("Arrays/Invalid/Overflow"),
6072 inBuf: `["1","2"]`,
6073 inVal: new([1]string),
6074 want: addr([1]string{"1"}),
6075 wantErr: &SemanticError{action: "unmarshal", GoType: array1StringType, Err: errors.New("too many array elements")},
6076 }, {
6077 name: name("Arrays/Invalid/Bool"),
6078 inBuf: `true`,
6079 inVal: addr([1]string{"nochange"}),
6080 want: addr([1]string{"nochange"}),
6081 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: array1StringType},
6082 }, {
6083 name: name("Arrays/Invalid/String"),
6084 inBuf: `""`,
6085 inVal: addr([1]string{"nochange"}),
6086 want: addr([1]string{"nochange"}),
6087 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: array1StringType},
6088 }, {
6089 name: name("Arrays/Invalid/Number"),
6090 inBuf: `0`,
6091 inVal: addr([1]string{"nochange"}),
6092 want: addr([1]string{"nochange"}),
6093 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: array1StringType},
6094 }, {
6095 name: name("Arrays/Invalid/Object"),
6096 inBuf: `{}`,
6097 inVal: addr([1]string{"nochange"}),
6098 want: addr([1]string{"nochange"}),
6099 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: array1StringType},
6100 }, {
6101 name: name("Arrays/IgnoreInvalidFormat"),
6102 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
6103 inBuf: `[false,true]`,
6104 inVal: addr([2]bool{true, false}),
6105 want: addr([2]bool{false, true}),
6106 }, {
6107 name: name("Pointers/NullL0"),
6108 inBuf: `null`,
6109 inVal: new(*string),
6110 want: addr((*string)(nil)),
6111 }, {
6112 name: name("Pointers/NullL1"),
6113 inBuf: `null`,
6114 inVal: addr(new(*string)),
6115 want: addr((**string)(nil)),
6116 }, {
6117 name: name("Pointers/Bool"),
6118 inBuf: `true`,
6119 inVal: addr(new(bool)),
6120 want: addr(addr(true)),
6121 }, {
6122 name: name("Pointers/String"),
6123 inBuf: `"hello"`,
6124 inVal: addr(new(string)),
6125 want: addr(addr("hello")),
6126 }, {
6127 name: name("Pointers/Bytes"),
6128 inBuf: `"aGVsbG8="`,
6129 inVal: addr(new([]byte)),
6130 want: addr(addr([]byte("hello"))),
6131 }, {
6132 name: name("Pointers/Int"),
6133 inBuf: `-123`,
6134 inVal: addr(new(int)),
6135 want: addr(addr(int(-123))),
6136 }, {
6137 name: name("Pointers/Uint"),
6138 inBuf: `123`,
6139 inVal: addr(new(int)),
6140 want: addr(addr(int(123))),
6141 }, {
6142 name: name("Pointers/Float"),
6143 inBuf: `123.456`,
6144 inVal: addr(new(float64)),
6145 want: addr(addr(float64(123.456))),
6146 }, {
6147 name: name("Pointers/Allocate"),
6148 inBuf: `"hello"`,
6149 inVal: addr((*string)(nil)),
6150 want: addr(addr("hello")),
6151 }, {
6152 name: name("Points/IgnoreInvalidFormat"),
6153 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
6154 inBuf: `true`,
6155 inVal: addr(new(bool)),
6156 want: addr(addr(true)),
6157 }, {
6158 name: name("Interfaces/Empty/Null"),
6159 inBuf: `null`,
6160 inVal: new(any),
6161 want: new(any),
6162 }, {
6163 name: name("Interfaces/NonEmpty/Null"),
6164 inBuf: `null`,
6165 inVal: new(io.Reader),
6166 want: new(io.Reader),
6167 }, {
6168 name: name("Interfaces/NonEmpty/Invalid"),
6169 inBuf: `"hello"`,
6170 inVal: new(io.Reader),
6171 want: new(io.Reader),
6172 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: ioReaderType, Err: errors.New("cannot derive concrete type for non-empty interface")},
6173 }, {
6174 name: name("Interfaces/Empty/False"),
6175 inBuf: `false`,
6176 inVal: new(any),
6177 want: func() any {
6178 var vi any = false
6179 return &vi
6180 }(),
6181 }, {
6182 name: name("Interfaces/Empty/True"),
6183 inBuf: `true`,
6184 inVal: new(any),
6185 want: func() any {
6186 var vi any = true
6187 return &vi
6188 }(),
6189 }, {
6190 name: name("Interfaces/Empty/String"),
6191 inBuf: `"string"`,
6192 inVal: new(any),
6193 want: func() any {
6194 var vi any = "string"
6195 return &vi
6196 }(),
6197 }, {
6198 name: name("Interfaces/Empty/Number"),
6199 inBuf: `3.14159`,
6200 inVal: new(any),
6201 want: func() any {
6202 var vi any = 3.14159
6203 return &vi
6204 }(),
6205 }, {
6206 name: name("Interfaces/Empty/Object"),
6207 inBuf: `{"k":"v"}`,
6208 inVal: new(any),
6209 want: func() any {
6210 var vi any = map[string]any{"k": "v"}
6211 return &vi
6212 }(),
6213 }, {
6214 name: name("Interfaces/Empty/Array"),
6215 inBuf: `["v"]`,
6216 inVal: new(any),
6217 want: func() any {
6218 var vi any = []any{"v"}
6219 return &vi
6220 }(),
6221 }, {
6222 name: name("Interfaces/NamedAny/String"),
6223 inBuf: `"string"`,
6224 inVal: new(namedAny),
6225 want: func() namedAny {
6226 var vi namedAny = "string"
6227 return &vi
6228 }(),
6229 }, {
6230 name: name("Interfaces/Invalid"),
6231 inBuf: `]`,
6232 inVal: new(any),
6233 want: new(any),
6234 wantErr: newInvalidCharacterError([]byte("]"), "at start of value"),
6235 }, {
6236 // NOTE: The semantics differs from v1,
6237 // where existing map entries were not merged into.
6238 // See https://go.dev/issue/26946.
6239 // See https://go.dev/issue/33993.
6240 name: name("Interfaces/Merge/Map"),
6241 inBuf: `{"k2":"v2"}`,
6242 inVal: func() any {
6243 var vi any = map[string]string{"k1": "v1"}
6244 return &vi
6245 }(),
6246 want: func() any {
6247 var vi any = map[string]string{"k1": "v1", "k2": "v2"}
6248 return &vi
6249 }(),
6250 }, {
6251 name: name("Interfaces/Merge/Struct"),
6252 inBuf: `{"Array":["goodbye"]}`,
6253 inVal: func() any {
6254 var vi any = structAll{String: "hello"}
6255 return &vi
6256 }(),
6257 want: func() any {
6258 var vi any = structAll{String: "hello", Array: [1]string{"goodbye"}}
6259 return &vi
6260 }(),
6261 }, {
6262 name: name("Interfaces/Merge/NamedInt"),
6263 inBuf: `64`,
6264 inVal: func() any {
6265 var vi any = namedInt64(-64)
6266 return &vi
6267 }(),
6268 want: func() any {
6269 var vi any = namedInt64(+64)
6270 return &vi
6271 }(),
6272 }, {
6273 name: name("Interfaces/IgnoreInvalidFormat"),
6274 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
6275 inBuf: `true`,
6276 inVal: new(any),
6277 want: func() any {
6278 var vi any = true
6279 return &vi
6280 }(),
6281 }, {
6282 name: name("Interfaces/Any"),
6283 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6284 inVal: new(struct{ X any }),
6285 want: addr(struct{ X any }{[]any{nil, false, true, "", 0.0, map[string]any{}, []any{}}}),
6286 }, {
6287 name: name("Interfaces/Any/Named"),
6288 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6289 inVal: new(struct{ X namedAny }),
6290 want: addr(struct{ X namedAny }{[]any{nil, false, true, "", 0.0, map[string]any{}, []any{}}}),
6291 }, {
6292 name: name("Interfaces/Any/Stringified"),
6293 uopts: UnmarshalOptions{StringifyNumbers: true},
6294 inBuf: `{"X":"0"}`,
6295 inVal: new(struct{ X any }),
6296 want: addr(struct{ X any }{"0"}),
6297 }, {
6298 name: name("Interfaces/Any/UnmarshalFunc/Any"),
6299 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *any) error {
6300 *v = "called"
6301 return nil
6302 })},
6303 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6304 inVal: new(struct{ X any }),
6305 want: addr(struct{ X any }{"called"}),
6306 }, {
6307 name: name("Interfaces/Any/UnmarshalFunc/Bool"),
6308 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *bool) error {
6309 *v = string(b) != "true"
6310 return nil
6311 })},
6312 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6313 inVal: new(struct{ X any }),
6314 want: addr(struct{ X any }{[]any{nil, true, false, "", 0.0, map[string]any{}, []any{}}}),
6315 }, {
6316 name: name("Interfaces/Any/UnmarshalFunc/String"),
6317 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *string) error {
6318 *v = "called"
6319 return nil
6320 })},
6321 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6322 inVal: new(struct{ X any }),
6323 want: addr(struct{ X any }{[]any{nil, false, true, "called", 0.0, map[string]any{}, []any{}}}),
6324 }, {
6325 name: name("Interfaces/Any/UnmarshalFunc/Float64"),
6326 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *float64) error {
6327 *v = 3.14159
6328 return nil
6329 })},
6330 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6331 inVal: new(struct{ X any }),
6332 want: addr(struct{ X any }{[]any{nil, false, true, "", 3.14159, map[string]any{}, []any{}}}),
6333 }, {
6334 name: name("Interfaces/Any/UnmarshalFunc/MapStringAny"),
6335 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *map[string]any) error {
6336 *v = map[string]any{"called": nil}
6337 return nil
6338 })},
6339 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6340 inVal: new(struct{ X any }),
6341 want: addr(struct{ X any }{[]any{nil, false, true, "", 0.0, map[string]any{"called": nil}, []any{}}}),
6342 }, {
6343 name: name("Interfaces/Any/UnmarshalFunc/SliceAny"),
6344 uopts: UnmarshalOptions{Unmarshalers: UnmarshalFuncV1(func(b []byte, v *[]any) error {
6345 *v = []any{"called"}
6346 return nil
6347 })},
6348 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
6349 inVal: new(struct{ X any }),
6350 want: addr(struct{ X any }{[]any{"called"}}),
6351 }, {
6352 name: name("Interfaces/Any/Maps/NonEmpty"),
6353 inBuf: `{"X":{"fizz":"buzz"}}`,
6354 inVal: new(struct{ X any }),
6355 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
6356 }, {
6357 name: name("Interfaces/Any/Maps/RejectDuplicateNames"),
6358 inBuf: `{"X":{"fizz":"buzz","fizz":true}}`,
6359 inVal: new(struct{ X any }),
6360 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
6361 wantErr: (&SyntacticError{str: `duplicate name "fizz" in object`}).withOffset(int64(len(`{"X":{"fizz":"buzz",`))),
6362 }, {
6363 name: name("Interfaces/Any/Maps/AllowDuplicateNames"),
6364 dopts: DecodeOptions{AllowDuplicateNames: true},
6365 inBuf: `{"X":{"fizz":"buzz","fizz":true}}`,
6366 inVal: new(struct{ X any }),
6367 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
6368 wantErr: &SemanticError{action: "unmarshal", JSONKind: 't', GoType: stringType},
6369 }, {
6370 name: name("Interfaces/Any/Slices/NonEmpty"),
6371 inBuf: `{"X":["fizz","buzz"]}`,
6372 inVal: new(struct{ X any }),
6373 want: addr(struct{ X any }{[]any{"fizz", "buzz"}}),
6374 }, {
6375 name: name("Methods/NilPointer/Null"),
6376 inBuf: `{"X":null}`,
6377 inVal: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}),
6378 want: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}), // method should not be called
6379 }, {
6380 name: name("Methods/NilPointer/Value"),
6381 inBuf: `{"X":"value"}`,
6382 inVal: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}),
6383 want: addr(struct{ X *allMethods }{X: &allMethods{method: "UnmarshalNextJSON", value: []byte(`"value"`)}}),
6384 }, {
6385 name: name("Methods/NilInterface/Null"),
6386 inBuf: `{"X":null}`,
6387 inVal: addr(struct{ X MarshalerV2 }{X: (*allMethods)(nil)}),
6388 want: addr(struct{ X MarshalerV2 }{X: nil}), // interface value itself is nil'd out
6389 }, {
6390 name: name("Methods/NilInterface/Value"),
6391 inBuf: `{"X":"value"}`,
6392 inVal: addr(struct{ X MarshalerV2 }{X: (*allMethods)(nil)}),
6393 want: addr(struct{ X MarshalerV2 }{X: &allMethods{method: "UnmarshalNextJSON", value: []byte(`"value"`)}}),
6394 }, {
6395 name: name("Methods/AllMethods"),
6396 inBuf: `{"X":"hello"}`,
6397 inVal: new(struct{ X *allMethods }),
6398 want: addr(struct{ X *allMethods }{X: &allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)}}),
6399 }, {
6400 name: name("Methods/AllMethodsExceptJSONv2"),
6401 inBuf: `{"X":"hello"}`,
6402 inVal: new(struct{ X *allMethodsExceptJSONv2 }),
6403 want: addr(struct{ X *allMethodsExceptJSONv2 }{X: &allMethodsExceptJSONv2{allMethods: allMethods{method: "UnmarshalJSON", value: []byte(`"hello"`)}}}),
6404 }, {
6405 name: name("Methods/AllMethodsExceptJSONv1"),
6406 inBuf: `{"X":"hello"}`,
6407 inVal: new(struct{ X *allMethodsExceptJSONv1 }),
6408 want: addr(struct{ X *allMethodsExceptJSONv1 }{X: &allMethodsExceptJSONv1{allMethods: allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)}}}),
6409 }, {
6410 name: name("Methods/AllMethodsExceptText"),
6411 inBuf: `{"X":"hello"}`,
6412 inVal: new(struct{ X *allMethodsExceptText }),
6413 want: addr(struct{ X *allMethodsExceptText }{X: &allMethodsExceptText{allMethods: allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)}}}),
6414 }, {
6415 name: name("Methods/OnlyMethodJSONv2"),
6416 inBuf: `{"X":"hello"}`,
6417 inVal: new(struct{ X *onlyMethodJSONv2 }),
6418 want: addr(struct{ X *onlyMethodJSONv2 }{X: &onlyMethodJSONv2{allMethods: allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)}}}),
6419 }, {
6420 name: name("Methods/OnlyMethodJSONv1"),
6421 inBuf: `{"X":"hello"}`,
6422 inVal: new(struct{ X *onlyMethodJSONv1 }),
6423 want: addr(struct{ X *onlyMethodJSONv1 }{X: &onlyMethodJSONv1{allMethods: allMethods{method: "UnmarshalJSON", value: []byte(`"hello"`)}}}),
6424 }, {
6425 name: name("Methods/OnlyMethodText"),
6426 inBuf: `{"X":"hello"}`,
6427 inVal: new(struct{ X *onlyMethodText }),
6428 want: addr(struct{ X *onlyMethodText }{X: &onlyMethodText{allMethods: allMethods{method: "UnmarshalText", value: []byte(`hello`)}}}),
6429 }, {
6430 name: name("Methods/IP"),
6431 inBuf: `"192.168.0.100"`,
6432 inVal: new(net.IP),
6433 want: addr(net.IPv4(192, 168, 0, 100)),
6434 }, {
6435 // NOTE: Fixes https://go.dev/issue/46516.
6436 name: name("Methods/Anonymous"),
6437 inBuf: `{"X":"hello"}`,
6438 inVal: new(struct{ X struct{ allMethods } }),
6439 want: addr(struct{ X struct{ allMethods } }{X: struct{ allMethods }{allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)}}}),
6440 }, {
6441 // NOTE: Fixes https://go.dev/issue/22967.
6442 name: name("Methods/Addressable"),
6443 inBuf: `{"V":"hello","M":{"K":"hello"},"I":"hello"}`,
6444 inVal: addr(struct {
6445 V allMethods
6446 M map[string]allMethods
6447 I any
6448 }{
6449 I: allMethods{}, // need to initialize with concrete value
6450 }),
6451 want: addr(struct {
6452 V allMethods
6453 M map[string]allMethods
6454 I any
6455 }{
6456 V: allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)},
6457 M: map[string]allMethods{"K": {method: "UnmarshalNextJSON", value: []byte(`"hello"`)}},
6458 I: allMethods{method: "UnmarshalNextJSON", value: []byte(`"hello"`)},
6459 }),
6460 }, {
6461 // NOTE: Fixes https://go.dev/issue/29732.
6462 name: name("Methods/MapKey/JSONv2"),
6463 inBuf: `{"k1":"v1b","k2":"v2"}`,
6464 inVal: addr(map[structMethodJSONv2]string{{"k1"}: "v1a", {"k3"}: "v3"}),
6465 want: addr(map[structMethodJSONv2]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
6466 }, {
6467 // NOTE: Fixes https://go.dev/issue/29732.
6468 name: name("Methods/MapKey/JSONv1"),
6469 inBuf: `{"k1":"v1b","k2":"v2"}`,
6470 inVal: addr(map[structMethodJSONv1]string{{"k1"}: "v1a", {"k3"}: "v3"}),
6471 want: addr(map[structMethodJSONv1]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
6472 }, {
6473 name: name("Methods/MapKey/Text"),
6474 inBuf: `{"k1":"v1b","k2":"v2"}`,
6475 inVal: addr(map[structMethodText]string{{"k1"}: "v1a", {"k3"}: "v3"}),
6476 want: addr(map[structMethodText]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
6477 }, {
6478 name: name("Methods/Invalid/JSONv2/Error"),
6479 inBuf: `{}`,
6480 inVal: addr(unmarshalJSONv2Func(func(UnmarshalOptions, *Decoder) error {
6481 return errors.New("some error")
6482 })),
6483 wantErr: &SemanticError{action: "unmarshal", GoType: unmarshalJSONv2FuncType, Err: errors.New("some error")},
6484 }, {
6485 name: name("Methods/Invalid/JSONv2/TooFew"),
6486 inVal: addr(unmarshalJSONv2Func(func(UnmarshalOptions, *Decoder) error {
6487 return nil // do nothing
6488 })),
6489 wantErr: &SemanticError{action: "unmarshal", GoType: unmarshalJSONv2FuncType, Err: errors.New("must read exactly one JSON value")},
6490 }, {
6491 name: name("Methods/Invalid/JSONv2/TooMany"),
6492 inBuf: `{}{}`,
6493 inVal: addr(unmarshalJSONv2Func(func(uo UnmarshalOptions, dec *Decoder) error {
6494 dec.ReadValue()
6495 dec.ReadValue()
6496 return nil
6497 })),
6498 wantErr: &SemanticError{action: "unmarshal", GoType: unmarshalJSONv2FuncType, Err: errors.New("must read exactly one JSON value")},
6499 }, {
6500 name: name("Methods/Invalid/JSONv2/SkipFunc"),
6501 inBuf: `{}`,
6502 inVal: addr(unmarshalJSONv2Func(func(UnmarshalOptions, *Decoder) error {
6503 return SkipFunc
6504 })),
6505 wantErr: &SemanticError{action: "unmarshal", GoType: unmarshalJSONv2FuncType, Err: errors.New("unmarshal method cannot be skipped")},
6506 }, {
6507 name: name("Methods/Invalid/JSONv1/Error"),
6508 inBuf: `{}`,
6509 inVal: addr(unmarshalJSONv1Func(func([]byte) error {
6510 return errors.New("some error")
6511 })),
6512 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: unmarshalJSONv1FuncType, Err: errors.New("some error")},
6513 }, {
6514 name: name("Methods/Invalid/JSONv1/SkipFunc"),
6515 inBuf: `{}`,
6516 inVal: addr(unmarshalJSONv1Func(func([]byte) error {
6517 return SkipFunc
6518 })),
6519 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: unmarshalJSONv1FuncType, Err: errors.New("unmarshal method cannot be skipped")},
6520 }, {
6521 name: name("Methods/Invalid/Text/Error"),
6522 inBuf: `"value"`,
6523 inVal: addr(unmarshalTextFunc(func([]byte) error {
6524 return errors.New("some error")
6525 })),
6526 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: unmarshalTextFuncType, Err: errors.New("some error")},
6527 }, {
6528 name: name("Methods/Invalid/Text/Syntax"),
6529 inBuf: `{}`,
6530 inVal: addr(unmarshalTextFunc(func([]byte) error {
6531 panic("should not be called")
6532 })),
6533 wantErr: &SemanticError{action: "unmarshal", JSONKind: '{', GoType: unmarshalTextFuncType, Err: errors.New("JSON value must be string type")},
6534 }, {
6535 name: name("Methods/Invalid/Text/SkipFunc"),
6536 inBuf: `"value"`,
6537 inVal: addr(unmarshalTextFunc(func([]byte) error {
6538 return SkipFunc
6539 })),
6540 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: unmarshalTextFuncType, Err: errors.New("unmarshal method cannot be skipped")},
6541 }, {
6542 name: name("Functions/String/V1"),
6543 uopts: UnmarshalOptions{
6544 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *string) error {
6545 if string(b) != `""` {
6546 return fmt.Errorf("got %s, want %s", b, `""`)
6547 }
6548 *v = "called"
6549 return nil
6550 }),
6551 },
6552 inBuf: `""`,
6553 inVal: addr(""),
6554 want: addr("called"),
6555 }, {
6556 name: name("Functions/NamedString/V1/NoMatch"),
6557 uopts: UnmarshalOptions{
6558 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *namedString) error {
6559 panic("should not be called")
6560 }),
6561 },
6562 inBuf: `""`,
6563 inVal: addr(""),
6564 want: addr(""),
6565 }, {
6566 name: name("Functions/NamedString/V1/Match"),
6567 uopts: UnmarshalOptions{
6568 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *namedString) error {
6569 if string(b) != `""` {
6570 return fmt.Errorf("got %s, want %s", b, `""`)
6571 }
6572 *v = "called"
6573 return nil
6574 }),
6575 },
6576 inBuf: `""`,
6577 inVal: addr(namedString("")),
6578 want: addr(namedString("called")),
6579 }, {
6580 name: name("Functions/String/V2"),
6581 uopts: UnmarshalOptions{
6582 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6583 switch b, err := dec.ReadValue(); {
6584 case err != nil:
6585 return err
6586 case string(b) != `""`:
6587 return fmt.Errorf("got %s, want %s", b, `""`)
6588 }
6589 *v = "called"
6590 return nil
6591 }),
6592 },
6593 inBuf: `""`,
6594 inVal: addr(""),
6595 want: addr("called"),
6596 }, {
6597 name: name("Functions/NamedString/V2/NoMatch"),
6598 uopts: UnmarshalOptions{
6599 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *namedString) error {
6600 panic("should not be called")
6601 }),
6602 },
6603 inBuf: `""`,
6604 inVal: addr(""),
6605 want: addr(""),
6606 }, {
6607 name: name("Functions/NamedString/V2/Match"),
6608 uopts: UnmarshalOptions{
6609 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *namedString) error {
6610 switch t, err := dec.ReadToken(); {
6611 case err != nil:
6612 return err
6613 case t.String() != ``:
6614 return fmt.Errorf("got %q, want %q", t, ``)
6615 }
6616 *v = "called"
6617 return nil
6618 }),
6619 },
6620 inBuf: `""`,
6621 inVal: addr(namedString("")),
6622 want: addr(namedString("called")),
6623 }, {
6624 name: name("Functions/String/Empty1/NoMatch"),
6625 uopts: UnmarshalOptions{
6626 Unmarshalers: new(Unmarshalers),
6627 },
6628 inBuf: `""`,
6629 inVal: addr(""),
6630 want: addr(""),
6631 }, {
6632 name: name("Functions/String/Empty2/NoMatch"),
6633 uopts: UnmarshalOptions{
6634 Unmarshalers: NewUnmarshalers(),
6635 },
6636 inBuf: `""`,
6637 inVal: addr(""),
6638 want: addr(""),
6639 }, {
6640 name: name("Functions/String/V1/DirectError"),
6641 uopts: UnmarshalOptions{
6642 Unmarshalers: UnmarshalFuncV1(func([]byte, *string) error {
6643 return errors.New("some error")
6644 }),
6645 },
6646 inBuf: `""`,
6647 inVal: addr(""),
6648 want: addr(""),
6649 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: reflect.PointerTo(stringType), Err: errors.New("some error")},
6650 }, {
6651 name: name("Functions/String/V1/SkipError"),
6652 uopts: UnmarshalOptions{
6653 Unmarshalers: UnmarshalFuncV1(func([]byte, *string) error {
6654 return SkipFunc
6655 }),
6656 },
6657 inBuf: `""`,
6658 inVal: addr(""),
6659 want: addr(""),
6660 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: reflect.PointerTo(stringType), Err: errors.New("unmarshal function of type func([]byte, T) error cannot be skipped")},
6661 }, {
6662 name: name("Functions/String/V2/DirectError"),
6663 uopts: UnmarshalOptions{
6664 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6665 return errors.New("some error")
6666 }),
6667 },
6668 inBuf: `""`,
6669 inVal: addr(""),
6670 want: addr(""),
6671 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: errors.New("some error")},
6672 }, {
6673 name: name("Functions/String/V2/TooFew"),
6674 uopts: UnmarshalOptions{
6675 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6676 return nil
6677 }),
6678 },
6679 inBuf: `""`,
6680 inVal: addr(""),
6681 want: addr(""),
6682 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: errors.New("must read exactly one JSON value")},
6683 }, {
6684 name: name("Functions/String/V2/TooMany"),
6685 uopts: UnmarshalOptions{
6686 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6687 if _, err := dec.ReadValue(); err != nil {
6688 return err
6689 }
6690 if _, err := dec.ReadValue(); err != nil {
6691 return err
6692 }
6693 return nil
6694 }),
6695 },
6696 inBuf: `["",""]`,
6697 inVal: addr([]string{}),
6698 want: addr([]string{""}),
6699 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: errors.New("must read exactly one JSON value")},
6700 }, {
6701 name: name("Functions/String/V2/Skipped"),
6702 uopts: UnmarshalOptions{
6703 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6704 return SkipFunc
6705 }),
6706 },
6707 inBuf: `""`,
6708 inVal: addr(""),
6709 want: addr(""),
6710 }, {
6711 name: name("Functions/String/V2/ProcessBeforeSkip"),
6712 uopts: UnmarshalOptions{
6713 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6714 if _, err := dec.ReadValue(); err != nil {
6715 return err
6716 }
6717 return SkipFunc
6718 }),
6719 },
6720 inBuf: `""`,
6721 inVal: addr(""),
6722 want: addr(""),
6723 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: errors.New("must not read any JSON tokens when skipping")},
6724 }, {
6725 name: name("Functions/String/V2/WrappedSkipError"),
6726 uopts: UnmarshalOptions{
6727 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6728 return fmt.Errorf("wrap: %w", SkipFunc)
6729 }),
6730 },
6731 inBuf: `""`,
6732 inVal: addr(""),
6733 want: addr(""),
6734 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: fmt.Errorf("wrap: %w", SkipFunc)},
6735 }, {
6736 name: name("Functions/Map/Key/NoCaseString/V1"),
6737 uopts: UnmarshalOptions{
6738 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *nocaseString) error {
6739 if string(b) != `"hello"` {
6740 return fmt.Errorf("got %s, want %s", b, `"hello"`)
6741 }
6742 *v = "called"
6743 return nil
6744 }),
6745 },
6746 inBuf: `{"hello":"world"}`,
6747 inVal: addr(map[nocaseString]string{}),
6748 want: addr(map[nocaseString]string{"called": "world"}),
6749 }, {
6750 name: name("Functions/Map/Key/TextMarshaler/V1"),
6751 uopts: UnmarshalOptions{
6752 Unmarshalers: UnmarshalFuncV1(func(b []byte, v encoding.TextMarshaler) error {
6753 if string(b) != `"hello"` {
6754 return fmt.Errorf("got %s, want %s", b, `"hello"`)
6755 }
6756 *v.(*nocaseString) = "called"
6757 return nil
6758 }),
6759 },
6760 inBuf: `{"hello":"world"}`,
6761 inVal: addr(map[nocaseString]string{}),
6762 want: addr(map[nocaseString]string{"called": "world"}),
6763 }, {
6764 name: name("Functions/Map/Key/NoCaseString/V2"),
6765 uopts: UnmarshalOptions{
6766 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *nocaseString) error {
6767 switch t, err := dec.ReadToken(); {
6768 case err != nil:
6769 return err
6770 case t.String() != "hello":
6771 return fmt.Errorf("got %q, want %q", t, "hello")
6772 }
6773 *v = "called"
6774 return nil
6775 }),
6776 },
6777 inBuf: `{"hello":"world"}`,
6778 inVal: addr(map[nocaseString]string{}),
6779 want: addr(map[nocaseString]string{"called": "world"}),
6780 }, {
6781 name: name("Functions/Map/Key/TextMarshaler/V2"),
6782 uopts: UnmarshalOptions{
6783 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v encoding.TextMarshaler) error {
6784 switch b, err := dec.ReadValue(); {
6785 case err != nil:
6786 return err
6787 case string(b) != `"hello"`:
6788 return fmt.Errorf("got %s, want %s", b, `"hello"`)
6789 }
6790 *v.(*nocaseString) = "called"
6791 return nil
6792 }),
6793 },
6794 inBuf: `{"hello":"world"}`,
6795 inVal: addr(map[nocaseString]string{}),
6796 want: addr(map[nocaseString]string{"called": "world"}),
6797 }, {
6798 name: name("Functions/Map/Key/String/V1/DuplicateName"),
6799 uopts: UnmarshalOptions{
6800 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6801 if _, err := dec.ReadValue(); err != nil {
6802 return err
6803 }
6804 *v = fmt.Sprintf("%d-%d", len(dec.tokens.stack), dec.tokens.last.length())
6805 return nil
6806 }),
6807 },
6808 inBuf: `{"name":"value","name":"value"}`,
6809 inVal: addr(map[string]string{}),
6810 want: addr(map[string]string{"1-1": "1-2"}),
6811 wantErr: &SemanticError{action: "unmarshal", GoType: reflect.PointerTo(stringType), Err: (&SyntacticError{str: `duplicate name "name" in object`}).withOffset(int64(len(`{"name":"value",`)))},
6812 }, {
6813 name: name("Functions/Map/Value/NoCaseString/V1"),
6814 uopts: UnmarshalOptions{
6815 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *nocaseString) error {
6816 if string(b) != `"world"` {
6817 return fmt.Errorf("got %s, want %s", b, `"world"`)
6818 }
6819 *v = "called"
6820 return nil
6821 }),
6822 },
6823 inBuf: `{"hello":"world"}`,
6824 inVal: addr(map[string]nocaseString{}),
6825 want: addr(map[string]nocaseString{"hello": "called"}),
6826 }, {
6827 name: name("Functions/Map/Value/TextMarshaler/V1"),
6828 uopts: UnmarshalOptions{
6829 Unmarshalers: UnmarshalFuncV1(func(b []byte, v encoding.TextMarshaler) error {
6830 if string(b) != `"world"` {
6831 return fmt.Errorf("got %s, want %s", b, `"world"`)
6832 }
6833 *v.(*nocaseString) = "called"
6834 return nil
6835 }),
6836 },
6837 inBuf: `{"hello":"world"}`,
6838 inVal: addr(map[string]nocaseString{}),
6839 want: addr(map[string]nocaseString{"hello": "called"}),
6840 }, {
6841 name: name("Functions/Map/Value/NoCaseString/V2"),
6842 uopts: UnmarshalOptions{
6843 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *nocaseString) error {
6844 switch t, err := dec.ReadToken(); {
6845 case err != nil:
6846 return err
6847 case t.String() != "world":
6848 return fmt.Errorf("got %q, want %q", t, "world")
6849 }
6850 *v = "called"
6851 return nil
6852 }),
6853 },
6854 inBuf: `{"hello":"world"}`,
6855 inVal: addr(map[string]nocaseString{}),
6856 want: addr(map[string]nocaseString{"hello": "called"}),
6857 }, {
6858 name: name("Functions/Map/Value/TextMarshaler/V2"),
6859 uopts: UnmarshalOptions{
6860 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v encoding.TextMarshaler) error {
6861 switch b, err := dec.ReadValue(); {
6862 case err != nil:
6863 return err
6864 case string(b) != `"world"`:
6865 return fmt.Errorf("got %s, want %s", b, `"world"`)
6866 }
6867 *v.(*nocaseString) = "called"
6868 return nil
6869 }),
6870 },
6871 inBuf: `{"hello":"world"}`,
6872 inVal: addr(map[string]nocaseString{}),
6873 want: addr(map[string]nocaseString{"hello": "called"}),
6874 }, {
6875 name: name("Funtions/Struct/Fields"),
6876 uopts: UnmarshalOptions{
6877 Unmarshalers: NewUnmarshalers(
6878 UnmarshalFuncV1(func(b []byte, v *bool) error {
6879 if string(b) != `"called1"` {
6880 return fmt.Errorf("got %s, want %s", b, `"called1"`)
6881 }
6882 *v = true
6883 return nil
6884 }),
6885 UnmarshalFuncV1(func(b []byte, v *string) error {
6886 if string(b) != `"called2"` {
6887 return fmt.Errorf("got %s, want %s", b, `"called2"`)
6888 }
6889 *v = "called2"
6890 return nil
6891 }),
6892 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *[]byte) error {
6893 switch t, err := dec.ReadToken(); {
6894 case err != nil:
6895 return err
6896 case t.String() != "called3":
6897 return fmt.Errorf("got %q, want %q", t, "called3")
6898 }
6899 *v = []byte("called3")
6900 return nil
6901 }),
6902 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *int64) error {
6903 switch b, err := dec.ReadValue(); {
6904 case err != nil:
6905 return err
6906 case string(b) != `"called4"`:
6907 return fmt.Errorf("got %s, want %s", b, `"called4"`)
6908 }
6909 *v = 123
6910 return nil
6911 }),
6912 ),
6913 },
6914 inBuf: `{"Bool":"called1","String":"called2","Bytes":"called3","Int":"called4","Uint":456,"Float":789}`,
6915 inVal: addr(structScalars{}),
6916 want: addr(structScalars{Bool: true, String: "called2", Bytes: []byte("called3"), Int: 123, Uint: 456, Float: 789}),
6917 }, {
6918 name: name("Functions/Struct/Inlined"),
6919 uopts: UnmarshalOptions{
6920 Unmarshalers: NewUnmarshalers(
6921 UnmarshalFuncV1(func([]byte, *structInlinedL1) error {
6922 panic("should not be called")
6923 }),
6924 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *StructEmbed2) error {
6925 panic("should not be called")
6926 }),
6927 ),
6928 },
6929 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
6930 inVal: new(structInlined),
6931 want: addr(structInlined{
6932 X: structInlinedL1{
6933 X: &structInlinedL2{A: "A1", B: "B1" /* C: "C1" */},
6934 StructEmbed1: StructEmbed1{ /* C: "C2" */ D: "D2" /* E: "E2" */},
6935 },
6936 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
6937 }),
6938 }, {
6939 name: name("Functions/Slice/Elem"),
6940 uopts: UnmarshalOptions{
6941 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *string) error {
6942 *v = strings.Trim(strings.ToUpper(string(b)), `"`)
6943 return nil
6944 }),
6945 },
6946 inBuf: `["hello","World"]`,
6947 inVal: addr([]string{}),
6948 want: addr([]string{"HELLO", "WORLD"}),
6949 }, {
6950 name: name("Functions/Array/Elem"),
6951 uopts: UnmarshalOptions{
6952 Unmarshalers: UnmarshalFuncV1(func(b []byte, v *string) error {
6953 *v = strings.Trim(strings.ToUpper(string(b)), `"`)
6954 return nil
6955 }),
6956 },
6957 inBuf: `["hello","World"]`,
6958 inVal: addr([2]string{}),
6959 want: addr([2]string{"HELLO", "WORLD"}),
6960 }, {
6961 name: name("Functions/Pointer/Nil"),
6962 uopts: UnmarshalOptions{
6963 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6964 t, err := dec.ReadToken()
6965 *v = strings.ToUpper(t.String())
6966 return err
6967 }),
6968 },
6969 inBuf: `{"X":"hello"}`,
6970 inVal: addr(struct{ X *string }{nil}),
6971 want: addr(struct{ X *string }{addr("HELLO")}),
6972 }, {
6973 name: name("Functions/Pointer/NonNil"),
6974 uopts: UnmarshalOptions{
6975 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
6976 t, err := dec.ReadToken()
6977 *v = strings.ToUpper(t.String())
6978 return err
6979 }),
6980 },
6981 inBuf: `{"X":"hello"}`,
6982 inVal: addr(struct{ X *string }{addr("")}),
6983 want: addr(struct{ X *string }{addr("HELLO")}),
6984 }, {
6985 name: name("Functions/Interface/Nil"),
6986 uopts: UnmarshalOptions{
6987 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v fmt.Stringer) error {
6988 panic("should not be called")
6989 }),
6990 },
6991 inBuf: `{"X":"hello"}`,
6992 inVal: addr(struct{ X fmt.Stringer }{nil}),
6993 want: addr(struct{ X fmt.Stringer }{nil}),
6994 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: fmtStringerType, Err: errors.New("cannot derive concrete type for non-empty interface")},
6995 }, {
6996 name: name("Functions/Interface/NetIP"),
6997 uopts: UnmarshalOptions{
6998 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *fmt.Stringer) error {
6999 *v = net.IP{}
7000 return SkipFunc
7001 }),
7002 },
7003 inBuf: `{"X":"1.1.1.1"}`,
7004 inVal: addr(struct{ X fmt.Stringer }{nil}),
7005 want: addr(struct{ X fmt.Stringer }{net.IPv4(1, 1, 1, 1)}),
7006 }, {
7007 name: name("Functions/Interface/NewPointerNetIP"),
7008 uopts: UnmarshalOptions{
7009 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *fmt.Stringer) error {
7010 *v = new(net.IP)
7011 return SkipFunc
7012 }),
7013 },
7014 inBuf: `{"X":"1.1.1.1"}`,
7015 inVal: addr(struct{ X fmt.Stringer }{nil}),
7016 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(1, 1, 1, 1))}),
7017 }, {
7018 name: name("Functions/Interface/NilPointerNetIP"),
7019 uopts: UnmarshalOptions{
7020 Unmarshalers: UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *fmt.Stringer) error {
7021 *v = (*net.IP)(nil)
7022 return SkipFunc
7023 }),
7024 },
7025 inBuf: `{"X":"1.1.1.1"}`,
7026 inVal: addr(struct{ X fmt.Stringer }{nil}),
7027 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(1, 1, 1, 1))}),
7028 }, {
7029 name: name("Functions/Interface/NilPointerNetIP/Override"),
7030 uopts: UnmarshalOptions{
7031 Unmarshalers: NewUnmarshalers(
7032 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *fmt.Stringer) error {
7033 *v = (*net.IP)(nil)
7034 return SkipFunc
7035 }),
7036 UnmarshalFuncV1(func(b []byte, v *net.IP) error {
7037 b = bytes.ReplaceAll(b, []byte(`1`), []byte(`8`))
7038 return v.UnmarshalText(bytes.Trim(b, `"`))
7039 }),
7040 ),
7041 },
7042 inBuf: `{"X":"1.1.1.1"}`,
7043 inVal: addr(struct{ X fmt.Stringer }{nil}),
7044 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(8, 8, 8, 8))}),
7045 }, {
7046 name: name("Functions/Interface/Any"),
7047 inBuf: `[null,{},{},{},{},{},{},{},{},{},{},{},{},"LAST"]`,
7048 inVal: addr([...]any{
7049 nil, // nil
7050 valueStringer{}, // T
7051 (*valueStringer)(nil), // *T
7052 addr(valueStringer{}), // *T
7053 (**valueStringer)(nil), // **T
7054 addr((*valueStringer)(nil)), // **T
7055 addr(addr(valueStringer{})), // **T
7056 pointerStringer{}, // T
7057 (*pointerStringer)(nil), // *T
7058 addr(pointerStringer{}), // *T
7059 (**pointerStringer)(nil), // **T
7060 addr((*pointerStringer)(nil)), // **T
7061 addr(addr(pointerStringer{})), // **T
7062 "LAST",
7063 }),
7064 uopts: UnmarshalOptions{
7065 Unmarshalers: func() *Unmarshalers {
7066 type P [2]int
7067 type PV struct {
7068 P P
7069 V any
7070 }
7071
7072 var lastChecks []func() error
7073 checkLast := func() error {
7074 for _, fn := range lastChecks {
7075 if err := fn(); err != nil {
7076 return err
7077 }
7078 }
7079 return SkipFunc
7080 }
7081 makeValueChecker := func(name string, want []PV) func(d *Decoder, v any) error {
7082 checkNext := func(d *Decoder, v any) error {
7083 p := P{len(d.tokens.stack), d.tokens.last.length()}
7084 rv := reflect.ValueOf(v)
7085 pv := PV{p, v}
7086 switch {
7087 case len(want) == 0:
7088 return fmt.Errorf("%s: %v: got more values than expected", name, p)
7089 case !rv.IsValid() || rv.Kind() != reflect.Pointer || rv.IsNil():
7090 return fmt.Errorf("%s: %v: got %#v, want non-nil pointer type", name, p, v)
7091 case !reflect.DeepEqual(pv, want[0]):
7092 return fmt.Errorf("%s:\n\tgot %#v\n\twant %#v", name, pv, want[0])
7093 default:
7094 want = want[1:]
7095 return SkipFunc
7096 }
7097 }
7098 lastChecks = append(lastChecks, func() error {
7099 if len(want) > 0 {
7100 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
7101 }
7102 return nil
7103 })
7104 return checkNext
7105 }
7106 makePositionChecker := func(name string, want []P) func(d *Decoder, v any) error {
7107 checkNext := func(d *Decoder, v any) error {
7108 p := P{len(d.tokens.stack), d.tokens.last.length()}
7109 switch {
7110 case len(want) == 0:
7111 return fmt.Errorf("%s: %v: got more values than wanted", name, p)
7112 case p != want[0]:
7113 return fmt.Errorf("%s: got %v, want %v", name, p, want[0])
7114 default:
7115 want = want[1:]
7116 return SkipFunc
7117 }
7118 }
7119 lastChecks = append(lastChecks, func() error {
7120 if len(want) > 0 {
7121 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
7122 }
7123 return nil
7124 })
7125 return checkNext
7126 }
7127
7128 // In contrast to marshal, unmarshal automatically allocates for
7129 // nil pointers, which causes unmarshal to visit more values.
7130 wantAny := []PV{
7131 {P{1, 0}, addr(any(nil))},
7132 {P{1, 1}, addr(any(valueStringer{}))},
7133 {P{1, 1}, addr(valueStringer{})},
7134 {P{1, 2}, addr(any((*valueStringer)(nil)))},
7135 {P{1, 2}, addr((*valueStringer)(nil))},
7136 {P{1, 2}, addr(valueStringer{})},
7137 {P{1, 3}, addr(any(addr(valueStringer{})))},
7138 {P{1, 3}, addr(addr(valueStringer{}))},
7139 {P{1, 3}, addr(valueStringer{})},
7140 {P{1, 4}, addr(any((**valueStringer)(nil)))},
7141 {P{1, 4}, addr((**valueStringer)(nil))},
7142 {P{1, 4}, addr((*valueStringer)(nil))},
7143 {P{1, 4}, addr(valueStringer{})},
7144 {P{1, 5}, addr(any(addr((*valueStringer)(nil))))},
7145 {P{1, 5}, addr(addr((*valueStringer)(nil)))},
7146 {P{1, 5}, addr((*valueStringer)(nil))},
7147 {P{1, 5}, addr(valueStringer{})},
7148 {P{1, 6}, addr(any(addr(addr(valueStringer{}))))},
7149 {P{1, 6}, addr(addr(addr(valueStringer{})))},
7150 {P{1, 6}, addr(addr(valueStringer{}))},
7151 {P{1, 6}, addr(valueStringer{})},
7152 {P{1, 7}, addr(any(pointerStringer{}))},
7153 {P{1, 7}, addr(pointerStringer{})},
7154 {P{1, 8}, addr(any((*pointerStringer)(nil)))},
7155 {P{1, 8}, addr((*pointerStringer)(nil))},
7156 {P{1, 8}, addr(pointerStringer{})},
7157 {P{1, 9}, addr(any(addr(pointerStringer{})))},
7158 {P{1, 9}, addr(addr(pointerStringer{}))},
7159 {P{1, 9}, addr(pointerStringer{})},
7160 {P{1, 10}, addr(any((**pointerStringer)(nil)))},
7161 {P{1, 10}, addr((**pointerStringer)(nil))},
7162 {P{1, 10}, addr((*pointerStringer)(nil))},
7163 {P{1, 10}, addr(pointerStringer{})},
7164 {P{1, 11}, addr(any(addr((*pointerStringer)(nil))))},
7165 {P{1, 11}, addr(addr((*pointerStringer)(nil)))},
7166 {P{1, 11}, addr((*pointerStringer)(nil))},
7167 {P{1, 11}, addr(pointerStringer{})},
7168 {P{1, 12}, addr(any(addr(addr(pointerStringer{}))))},
7169 {P{1, 12}, addr(addr(addr(pointerStringer{})))},
7170 {P{1, 12}, addr(addr(pointerStringer{}))},
7171 {P{1, 12}, addr(pointerStringer{})},
7172 {P{1, 13}, addr(any("LAST"))},
7173 {P{1, 13}, addr("LAST")},
7174 }
7175 checkAny := makeValueChecker("any", wantAny)
7176 anyUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v any) error {
7177 return checkAny(dec, v)
7178 })
7179
7180 var wantPointerAny []PV
7181 for _, v := range wantAny {
7182 if _, ok := v.V.(*any); ok {
7183 wantPointerAny = append(wantPointerAny, v)
7184 }
7185 }
7186 checkPointerAny := makeValueChecker("*any", wantPointerAny)
7187 pointerAnyUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *any) error {
7188 return checkPointerAny(dec, v)
7189 })
7190
7191 checkNamedAny := makeValueChecker("namedAny", wantAny)
7192 namedAnyUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v namedAny) error {
7193 return checkNamedAny(dec, v)
7194 })
7195
7196 checkPointerNamedAny := makeValueChecker("*namedAny", nil)
7197 pointerNamedAnyUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *namedAny) error {
7198 return checkPointerNamedAny(dec, v)
7199 })
7200
7201 type stringer = fmt.Stringer
7202 var wantStringer []PV
7203 for _, v := range wantAny {
7204 if _, ok := v.V.(stringer); ok {
7205 wantStringer = append(wantStringer, v)
7206 }
7207 }
7208 checkStringer := makeValueChecker("stringer", wantStringer)
7209 stringerUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v stringer) error {
7210 return checkStringer(dec, v)
7211 })
7212
7213 checkPointerStringer := makeValueChecker("*stringer", nil)
7214 pointerStringerUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *stringer) error {
7215 return checkPointerStringer(dec, v)
7216 })
7217
7218 wantValueStringer := []P{{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}}
7219 checkPointerValueStringer := makePositionChecker("*valueStringer", wantValueStringer)
7220 pointerValueStringerUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *valueStringer) error {
7221 return checkPointerValueStringer(dec, v)
7222 })
7223
7224 wantPointerStringer := []P{{1, 7}, {1, 8}, {1, 9}, {1, 10}, {1, 11}, {1, 12}}
7225 checkPointerPointerStringer := makePositionChecker("*pointerStringer", wantPointerStringer)
7226 pointerPointerStringerUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *pointerStringer) error {
7227 return checkPointerPointerStringer(dec, v)
7228 })
7229
7230 lastUnmarshaler := UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
7231 return checkLast()
7232 })
7233
7234 return NewUnmarshalers(
7235 // This is just like unmarshaling into a Go array,
7236 // but avoids zeroing the element before calling unmarshal.
7237 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *[14]any) error {
7238 if _, err := dec.ReadToken(); err != nil {
7239 return err
7240 }
7241 for i := 0; i < len(*v); i++ {
7242 if err := uo.UnmarshalNext(dec, &(*v)[i]); err != nil {
7243 return err
7244 }
7245 }
7246 if _, err := dec.ReadToken(); err != nil {
7247 return err
7248 }
7249 return nil
7250 }),
7251
7252 anyUnmarshaler,
7253 pointerAnyUnmarshaler,
7254 namedAnyUnmarshaler,
7255 pointerNamedAnyUnmarshaler, // never called
7256 stringerUnmarshaler,
7257 pointerStringerUnmarshaler, // never called
7258 pointerValueStringerUnmarshaler,
7259 pointerPointerStringerUnmarshaler,
7260 lastUnmarshaler,
7261 )
7262 }(),
7263 },
7264 }, {
7265 name: name("Functions/Precedence/V1First"),
7266 uopts: UnmarshalOptions{
7267 Unmarshalers: NewUnmarshalers(
7268 UnmarshalFuncV1(func(b []byte, v *string) error {
7269 if string(b) != `"called"` {
7270 return fmt.Errorf("got %s, want %s", b, `"called"`)
7271 }
7272 *v = "called"
7273 return nil
7274 }),
7275 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
7276 panic("should not be called")
7277 }),
7278 ),
7279 },
7280 inBuf: `"called"`,
7281 inVal: addr(""),
7282 want: addr("called"),
7283 }, {
7284 name: name("Functions/Precedence/V2First"),
7285 uopts: UnmarshalOptions{
7286 Unmarshalers: NewUnmarshalers(
7287 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
7288 switch t, err := dec.ReadToken(); {
7289 case err != nil:
7290 return err
7291 case t.String() != "called":
7292 return fmt.Errorf("got %q, want %q", t, "called")
7293 }
7294 *v = "called"
7295 return nil
7296 }),
7297 UnmarshalFuncV1(func([]byte, *string) error {
7298 panic("should not be called")
7299 }),
7300 ),
7301 },
7302 inBuf: `"called"`,
7303 inVal: addr(""),
7304 want: addr("called"),
7305 }, {
7306 name: name("Functions/Precedence/V2Skipped"),
7307 uopts: UnmarshalOptions{
7308 Unmarshalers: NewUnmarshalers(
7309 UnmarshalFuncV2(func(uo UnmarshalOptions, dec *Decoder, v *string) error {
7310 return SkipFunc
7311 }),
7312 UnmarshalFuncV1(func(b []byte, v *string) error {
7313 if string(b) != `"called"` {
7314 return fmt.Errorf("got %s, want %s", b, `"called"`)
7315 }
7316 *v = "called"
7317 return nil
7318 }),
7319 ),
7320 },
7321 inBuf: `"called"`,
7322 inVal: addr(""),
7323 want: addr("called"),
7324 }, {
7325 name: name("Functions/Precedence/NestedFirst"),
7326 uopts: UnmarshalOptions{
7327 Unmarshalers: NewUnmarshalers(
7328 NewUnmarshalers(
7329 UnmarshalFuncV1(func(b []byte, v *string) error {
7330 if string(b) != `"called"` {
7331 return fmt.Errorf("got %s, want %s", b, `"called"`)
7332 }
7333 *v = "called"
7334 return nil
7335 }),
7336 ),
7337 UnmarshalFuncV1(func([]byte, *string) error {
7338 panic("should not be called")
7339 }),
7340 ),
7341 },
7342 inBuf: `"called"`,
7343 inVal: addr(""),
7344 want: addr("called"),
7345 }, {
7346 name: name("Functions/Precedence/NestedLast"),
7347 uopts: UnmarshalOptions{
7348 Unmarshalers: NewUnmarshalers(
7349 UnmarshalFuncV1(func(b []byte, v *string) error {
7350 if string(b) != `"called"` {
7351 return fmt.Errorf("got %s, want %s", b, `"called"`)
7352 }
7353 *v = "called"
7354 return nil
7355 }),
7356 NewUnmarshalers(
7357 UnmarshalFuncV1(func([]byte, *string) error {
7358 panic("should not be called")
7359 }),
7360 ),
7361 ),
7362 },
7363 inBuf: `"called"`,
7364 inVal: addr(""),
7365 want: addr("called"),
7366 }, {
7367 name: name("Duration/Null"),
7368 inBuf: `{"D1":null,"D2":null}`,
7369 inVal: addr(struct {
7370 D1 time.Duration
7371 D2 time.Duration `json:",format:nanos"`
7372 }{1, 1}),
7373 want: addr(struct {
7374 D1 time.Duration
7375 D2 time.Duration `json:",format:nanos"`
7376 }{0, 0}),
7377 }, {
7378 name: name("Duration/Zero"),
7379 inBuf: `{"D1":"0s","D2":0}`,
7380 inVal: addr(struct {
7381 D1 time.Duration
7382 D2 time.Duration `json:",format:nanos"`
7383 }{1, 1}),
7384 want: addr(struct {
7385 D1 time.Duration
7386 D2 time.Duration `json:",format:nanos"`
7387 }{0, 0}),
7388 }, {
7389 name: name("Duration/Positive"),
7390 inBuf: `{"D1":"34293h33m9.123456789s","D2":123456789123456789}`,
7391 inVal: new(struct {
7392 D1 time.Duration
7393 D2 time.Duration `json:",format:nanos"`
7394 }),
7395 want: addr(struct {
7396 D1 time.Duration
7397 D2 time.Duration `json:",format:nanos"`
7398 }{
7399 123456789123456789,
7400 123456789123456789,
7401 }),
7402 }, {
7403 name: name("Duration/Negative"),
7404 inBuf: `{"D1":"-34293h33m9.123456789s","D2":-123456789123456789}`,
7405 inVal: new(struct {
7406 D1 time.Duration
7407 D2 time.Duration `json:",format:nanos"`
7408 }),
7409 want: addr(struct {
7410 D1 time.Duration
7411 D2 time.Duration `json:",format:nanos"`
7412 }{
7413 -123456789123456789,
7414 -123456789123456789,
7415 }),
7416 }, {
7417 name: name("Duration/Nanos/String"),
7418 inBuf: `{"D":"12345"}`,
7419 inVal: addr(struct {
7420 D time.Duration `json:",string,format:nanos"`
7421 }{1}),
7422 want: addr(struct {
7423 D time.Duration `json:",string,format:nanos"`
7424 }{12345}),
7425 }, {
7426 name: name("Duration/Nanos/String/Invalid"),
7427 inBuf: `{"D":"+12345"}`,
7428 inVal: addr(struct {
7429 D time.Duration `json:",string,format:nanos"`
7430 }{1}),
7431 want: addr(struct {
7432 D time.Duration `json:",string,format:nanos"`
7433 }{1}),
7434 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeDurationType, Err: fmt.Errorf(`cannot parse "+12345" as signed integer: %w`, strconv.ErrSyntax)},
7435 }, {
7436 name: name("Duration/Nanos/Mismatch"),
7437 inBuf: `{"D":"34293h33m9.123456789s"}`,
7438 inVal: addr(struct {
7439 D time.Duration `json:",format:nanos"`
7440 }{1}),
7441 want: addr(struct {
7442 D time.Duration `json:",format:nanos"`
7443 }{1}),
7444 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeDurationType},
7445 }, {
7446 name: name("Duration/Nanos/Invalid"),
7447 inBuf: `{"D":1.324}`,
7448 inVal: addr(struct {
7449 D time.Duration `json:",format:nanos"`
7450 }{1}),
7451 want: addr(struct {
7452 D time.Duration `json:",format:nanos"`
7453 }{1}),
7454 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: timeDurationType, Err: fmt.Errorf(`cannot parse "1.324" as signed integer: %w`, strconv.ErrSyntax)},
7455 }, {
7456 name: name("Duration/String/Mismatch"),
7457 inBuf: `{"D":-123456789123456789}`,
7458 inVal: addr(struct {
7459 D time.Duration
7460 }{1}),
7461 want: addr(struct {
7462 D time.Duration
7463 }{1}),
7464 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: timeDurationType},
7465 }, {
7466 name: name("Duration/String/Invalid"),
7467 inBuf: `{"D":"5minkutes"}`,
7468 inVal: addr(struct {
7469 D time.Duration
7470 }{1}),
7471 want: addr(struct {
7472 D time.Duration
7473 }{1}),
7474 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeDurationType, Err: func() error {
7475 _, err := time.ParseDuration("5minkutes")
7476 return err
7477 }()},
7478 }, {
7479 name: name("Duration/Syntax/Invalid"),
7480 inBuf: `{"D":x}`,
7481 inVal: addr(struct {
7482 D time.Duration
7483 }{1}),
7484 want: addr(struct {
7485 D time.Duration
7486 }{1}),
7487 wantErr: newInvalidCharacterError([]byte("x"), "at start of value").withOffset(int64(len(`{"D":`))),
7488 }, {
7489 name: name("Duration/Format/Invalid"),
7490 inBuf: `{"D":"0s"}`,
7491 inVal: addr(struct {
7492 D time.Duration `json:",format:invalid"`
7493 }{1}),
7494 want: addr(struct {
7495 D time.Duration `json:",format:invalid"`
7496 }{1}),
7497 wantErr: &SemanticError{action: "unmarshal", GoType: timeDurationType, Err: errors.New(`invalid format flag: "invalid"`)},
7498 }, {
7499 name: name("Duration/IgnoreInvalidFormat"),
7500 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
7501 inBuf: `"1s"`,
7502 inVal: addr(time.Duration(0)),
7503 want: addr(time.Second),
7504 }, {
7505 name: name("Time/Zero"),
7506 inBuf: `{"T1":"0001-01-01T00:00:00Z","T2":"01 Jan 01 00:00 UTC","T3":"0001-01-01","T4":"0001-01-01T00:00:00Z","T5":"0001-01-01T00:00:00Z"}`,
7507 inVal: new(struct {
7508 T1 time.Time
7509 T2 time.Time `json:",format:RFC822"`
7510 T3 time.Time `json:",format:'2006-01-02'"`
7511 T4 time.Time `json:",omitzero"`
7512 T5 time.Time `json:",omitempty"`
7513 }),
7514 want: addr(struct {
7515 T1 time.Time
7516 T2 time.Time `json:",format:RFC822"`
7517 T3 time.Time `json:",format:'2006-01-02'"`
7518 T4 time.Time `json:",omitzero"`
7519 T5 time.Time `json:",omitempty"`
7520 }{
7521 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
7522 mustParseTime(time.RFC822, "01 Jan 01 00:00 UTC"),
7523 mustParseTime("2006-01-02", "0001-01-01"),
7524 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
7525 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
7526 }),
7527 }, {
7528 name: name("Time/Format"),
7529 inBuf: `{
7530 "T1": "1234-01-02T03:04:05.000000006Z",
7531 "T2": "Mon Jan 2 03:04:05 1234",
7532 "T3": "Mon Jan 2 03:04:05 UTC 1234",
7533 "T4": "Mon Jan 02 03:04:05 +0000 1234",
7534 "T5": "02 Jan 34 03:04 UTC",
7535 "T6": "02 Jan 34 03:04 +0000",
7536 "T7": "Monday, 02-Jan-34 03:04:05 UTC",
7537 "T8": "Mon, 02 Jan 1234 03:04:05 UTC",
7538 "T9": "Mon, 02 Jan 1234 03:04:05 +0000",
7539 "T10": "1234-01-02T03:04:05Z",
7540 "T11": "1234-01-02T03:04:05.000000006Z",
7541 "T12": "3:04AM",
7542 "T13": "Jan 2 03:04:05",
7543 "T14": "Jan 2 03:04:05.000",
7544 "T15": "Jan 2 03:04:05.000000",
7545 "T16": "Jan 2 03:04:05.000000006",
7546 "T17": "1234-01-02",
7547 "T18": "\"weird\"1234"
7548 }`,
7549 inVal: new(structTimeFormat),
7550 want: addr(structTimeFormat{
7551 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
7552 mustParseTime(time.ANSIC, "Mon Jan 2 03:04:05 1234"),
7553 mustParseTime(time.UnixDate, "Mon Jan 2 03:04:05 UTC 1234"),
7554 mustParseTime(time.RubyDate, "Mon Jan 02 03:04:05 +0000 1234"),
7555 mustParseTime(time.RFC822, "02 Jan 34 03:04 UTC"),
7556 mustParseTime(time.RFC822Z, "02 Jan 34 03:04 +0000"),
7557 mustParseTime(time.RFC850, "Monday, 02-Jan-34 03:04:05 UTC"),
7558 mustParseTime(time.RFC1123, "Mon, 02 Jan 1234 03:04:05 UTC"),
7559 mustParseTime(time.RFC1123Z, "Mon, 02 Jan 1234 03:04:05 +0000"),
7560 mustParseTime(time.RFC3339, "1234-01-02T03:04:05Z"),
7561 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
7562 mustParseTime(time.Kitchen, "3:04AM"),
7563 mustParseTime(time.Stamp, "Jan 2 03:04:05"),
7564 mustParseTime(time.StampMilli, "Jan 2 03:04:05.000"),
7565 mustParseTime(time.StampMicro, "Jan 2 03:04:05.000000"),
7566 mustParseTime(time.StampNano, "Jan 2 03:04:05.000000006"),
7567 mustParseTime("2006-01-02", "1234-01-02"),
7568 mustParseTime(`\"weird\"2006`, `\"weird\"1234`),
7569 }),
7570 }, {
7571 name: name("Time/Format/Null"),
7572 inBuf: `{"T1": null,"T2": null,"T3": null,"T4": null,"T5": null,"T6": null,"T7": null,"T8": null,"T9": null,"T10": null,"T11": null,"T12": null,"T13": null,"T14": null,"T15": null,"T16": null,"T17": null,"T18": null}`,
7573 inVal: addr(structTimeFormat{
7574 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
7575 mustParseTime(time.ANSIC, "Mon Jan 2 03:04:05 1234"),
7576 mustParseTime(time.UnixDate, "Mon Jan 2 03:04:05 UTC 1234"),
7577 mustParseTime(time.RubyDate, "Mon Jan 02 03:04:05 +0000 1234"),
7578 mustParseTime(time.RFC822, "02 Jan 34 03:04 UTC"),
7579 mustParseTime(time.RFC822Z, "02 Jan 34 03:04 +0000"),
7580 mustParseTime(time.RFC850, "Monday, 02-Jan-34 03:04:05 UTC"),
7581 mustParseTime(time.RFC1123, "Mon, 02 Jan 1234 03:04:05 UTC"),
7582 mustParseTime(time.RFC1123Z, "Mon, 02 Jan 1234 03:04:05 +0000"),
7583 mustParseTime(time.RFC3339, "1234-01-02T03:04:05Z"),
7584 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
7585 mustParseTime(time.Kitchen, "3:04AM"),
7586 mustParseTime(time.Stamp, "Jan 2 03:04:05"),
7587 mustParseTime(time.StampMilli, "Jan 2 03:04:05.000"),
7588 mustParseTime(time.StampMicro, "Jan 2 03:04:05.000000"),
7589 mustParseTime(time.StampNano, "Jan 2 03:04:05.000000006"),
7590 mustParseTime("2006-01-02", "1234-01-02"),
7591 mustParseTime(`\"weird\"2006`, `\"weird\"1234`),
7592 }),
7593 want: new(structTimeFormat),
7594 }, {
7595 name: name("Time/RFC3339/Mismatch"),
7596 inBuf: `{"T":1234}`,
7597 inVal: new(struct {
7598 T time.Time
7599 }),
7600 wantErr: &SemanticError{action: "unmarshal", JSONKind: '0', GoType: timeTimeType},
7601 }, {
7602 name: name("Time/RFC3339/ParseError"),
7603 inBuf: `{"T":"2021-09-29T12:44:52"}`,
7604 inVal: new(struct {
7605 T time.Time
7606 }),
7607 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeTimeType, Err: func() error {
7608 _, err := time.Parse(time.RFC3339, "2021-09-29T12:44:52")
7609 return err
7610 }()},
7611 }, {
7612 name: name("Time/Format/Invalid"),
7613 inBuf: `{"T":""}`,
7614 inVal: new(struct {
7615 T time.Time `json:",format:UndefinedConstant"`
7616 }),
7617 wantErr: &SemanticError{action: "unmarshal", GoType: timeTimeType, Err: errors.New(`undefined format layout: UndefinedConstant`)},
7618 }, {
7619 name: name("Time/Format/SingleDigitHour"),
7620 inBuf: `{"T":"2000-01-01T1:12:34Z"}`,
7621 inVal: new(struct{ T time.Time }),
7622 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeTimeType, Err: &time.ParseError{time.RFC3339, "2000-01-01T1:12:34Z", "15", "1", ""}},
7623 }, {
7624 name: name("Time/Format/SubsecondComma"),
7625 inBuf: `{"T":"2000-01-01T00:00:00,000Z"}`,
7626 inVal: new(struct{ T time.Time }),
7627 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeTimeType, Err: &time.ParseError{time.RFC3339, "2000-01-01T00:00:00,000Z", ".", ",", ""}},
7628 }, {
7629 name: name("Time/Format/TimezoneHourOverflow"),
7630 inBuf: `{"T":"2000-01-01T00:00:00+24:00"}`,
7631 inVal: new(struct{ T time.Time }),
7632 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeTimeType, Err: &time.ParseError{time.RFC3339, "2000-01-01T00:00:00+24:00", "Z07:00", "+24:00", ": timezone hour out of range"}},
7633 }, {
7634 name: name("Time/Format/TimezoneMinuteOverflow"),
7635 inBuf: `{"T":"2000-01-01T00:00:00+00:60"}`,
7636 inVal: new(struct{ T time.Time }),
7637 wantErr: &SemanticError{action: "unmarshal", JSONKind: '"', GoType: timeTimeType, Err: &time.ParseError{time.RFC3339, "2000-01-01T00:00:00+00:60", "Z07:00", "+00:60", ": timezone minute out of range"}},
7638 }, {
7639 name: name("Time/Syntax/Invalid"),
7640 inBuf: `{"T":x}`,
7641 inVal: new(struct {
7642 T time.Time
7643 }),
7644 wantErr: newInvalidCharacterError([]byte("x"), "at start of value").withOffset(int64(len(`{"D":`))),
7645 }, {
7646 name: name("Time/IgnoreInvalidFormat"),
7647 uopts: UnmarshalOptions{formatDepth: 1000, format: "invalid"},
7648 inBuf: `"2000-01-01T00:00:00Z"`,
7649 inVal: addr(time.Time{}),
7650 want: addr(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)),
7651 }}
7652
7653 for _, tt := range tests {
7654 t.Run(tt.name.name, func(t *testing.T) {
7655 got := tt.inVal
7656 gotErr := tt.uopts.Unmarshal(tt.dopts, []byte(tt.inBuf), got)
7657 if !reflect.DeepEqual(got, tt.want) && tt.want != nil {
7658 t.Errorf("%s: Unmarshal output mismatch:\ngot %v\nwant %v", tt.name.where, got, tt.want)
7659 }
7660 if !reflect.DeepEqual(gotErr, tt.wantErr) {
7661 t.Errorf("%s: Unmarshal error mismatch:\ngot %v\nwant %v", tt.name.where, gotErr, tt.wantErr)
7662 }
7663 })
7664 }
7665 }
7666
7667 func TestMarshalInvalidNamespace(t *testing.T) {
7668 tests := []struct {
7669 name testName
7670 val any
7671 }{
7672 {name("Map"), map[string]string{"X": "\xde\xad\xbe\xef"}},
7673 {name("Struct"), struct{ X string }{"\xde\xad\xbe\xef"}},
7674 }
7675 for _, tt := range tests {
7676 t.Run(tt.name.name, func(t *testing.T) {
7677 enc := NewEncoder(new(bytes.Buffer))
7678 if err := (MarshalOptions{}).MarshalNext(enc, tt.val); err == nil {
7679 t.Fatalf("%s: MarshalNext error is nil, want non-nil", tt.name.where)
7680 }
7681 for _, tok := range []Token{Null, String(""), Int(0), ObjectStart, ObjectEnd, ArrayStart, ArrayEnd} {
7682 if err := enc.WriteToken(tok); err == nil {
7683 t.Fatalf("%s: WriteToken error is nil, want non-nil", tt.name.where)
7684 }
7685 }
7686 for _, val := range []string{`null`, `""`, `0`, `{}`, `[]`} {
7687 if err := enc.WriteValue([]byte(val)); err == nil {
7688 t.Fatalf("%s: WriteToken error is nil, want non-nil", tt.name.where)
7689 }
7690 }
7691 })
7692 }
7693 }
7694
7695 func TestUnmarshalInvalidNamespace(t *testing.T) {
7696 tests := []struct {
7697 name testName
7698 val any
7699 }{
7700 {name("Map"), addr(map[string]int{})},
7701 {name("Struct"), addr(struct{ X int }{})},
7702 }
7703 for _, tt := range tests {
7704 t.Run(tt.name.name, func(t *testing.T) {
7705 dec := NewDecoder(strings.NewReader(`{"X":""}`))
7706 if err := (UnmarshalOptions{}).UnmarshalNext(dec, tt.val); err == nil {
7707 t.Fatalf("%s: UnmarshalNext error is nil, want non-nil", tt.name.where)
7708 }
7709 if _, err := dec.ReadToken(); err == nil {
7710 t.Fatalf("%s: ReadToken error is nil, want non-nil", tt.name.where)
7711 }
7712 if _, err := dec.ReadValue(); err == nil {
7713 t.Fatalf("%s: ReadValue error is nil, want non-nil", tt.name.where)
7714 }
7715 })
7716 }
7717 }
7718
7719 func TestUnmarshalReuse(t *testing.T) {
7720 t.Run("Bytes", func(t *testing.T) {
7721 in := make([]byte, 3)
7722 want := &in[0]
7723 if err := Unmarshal([]byte(`"AQID"`), &in); err != nil {
7724 t.Fatalf("Unmarshal error: %v", err)
7725 }
7726 got := &in[0]
7727 if got != want {
7728 t.Errorf("input buffer was not reused")
7729 }
7730 })
7731 t.Run("Slices", func(t *testing.T) {
7732 in := make([]int, 3)
7733 want := &in[0]
7734 if err := Unmarshal([]byte(`[0,1,2]`), &in); err != nil {
7735 t.Fatalf("Unmarshal error: %v", err)
7736 }
7737 got := &in[0]
7738 if got != want {
7739 t.Errorf("input slice was not reused")
7740 }
7741 })
7742 t.Run("Maps", func(t *testing.T) {
7743 in := make(map[string]string)
7744 want := reflect.ValueOf(in).Pointer()
7745 if err := Unmarshal([]byte(`{"key":"value"}`), &in); err != nil {
7746 t.Fatalf("Unmarshal error: %v", err)
7747 }
7748 got := reflect.ValueOf(in).Pointer()
7749 if got != want {
7750 t.Errorf("input map was not reused")
7751 }
7752 })
7753 t.Run("Pointers", func(t *testing.T) {
7754 in := addr(addr(addr("hello")))
7755 want := **in
7756 if err := Unmarshal([]byte(`"goodbye"`), &in); err != nil {
7757 t.Fatalf("Unmarshal error: %v", err)
7758 }
7759 got := **in
7760 if got != want {
7761 t.Errorf("input pointer was not reused")
7762 }
7763 })
7764 }