Debian Codegraph @

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

raw
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 "net/netip"
19 "reflect"
20 "strconv"
21 "strings"
22 "testing"
23 "time"
24
25 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal"
26 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
27 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts"
28 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsontest"
29 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
30 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
31 )
32
33 func newNonStringNameError(offset int64, pointer jsontext.Pointer) error {
34 return &jsontext.SyntacticError{ByteOffset: offset, JSONPointer: pointer, Err: jsontext.ErrNonStringName}
35 }
36
37 func newInvalidCharacterError(prefix, where string, offset int64, pointer jsontext.Pointer) error {
38 return &jsontext.SyntacticError{ByteOffset: offset, JSONPointer: pointer, Err: jsonwire.NewInvalidCharacterError(prefix, where)}
39 }
40
41 func newInvalidUTF8Error(offset int64, pointer jsontext.Pointer) error {
42 return &jsontext.SyntacticError{ByteOffset: offset, JSONPointer: pointer, Err: jsonwire.ErrInvalidUTF8}
43 }
44
45 func newParseTimeError(layout, value, layoutElem, valueElem, message string) error {
46 return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message}
47 }
48
49 func EM(err error) *SemanticError {
50 return &SemanticError{action: "marshal", Err: err}
51 }
52
53 func EU(err error) *SemanticError {
54 return &SemanticError{action: "unmarshal", Err: err}
55 }
56
57 func (e *SemanticError) withVal(val string) *SemanticError {
58 e.JSONValue = jsontext.Value(val)
59 return e
60 }
61
62 func (e *SemanticError) withPos(prefix string, pointer jsontext.Pointer) *SemanticError {
63 e.ByteOffset = int64(len(prefix))
64 e.JSONPointer = pointer
65 return e
66 }
67
68 func (e *SemanticError) withType(k jsontext.Kind, t reflect.Type) *SemanticError {
69 e.JSONKind = k
70 e.GoType = t
71 return e
72 }
73
74 var (
75 errInvalidFormatFlag = errors.New(`invalid format flag "invalid"`)
76 errSomeError = errors.New("some error")
77 errMustNotCall = errors.New("must not call")
78 )
79
80 func T[T any]() reflect.Type { return reflect.TypeFor[T]() }
81
82 type (
83 jsonObject = map[string]any
84 jsonArray = []any
85
86 namedAny any
87 namedBool bool
88 namedString string
89 NamedString string
90 namedBytes []byte
91 namedInt64 int64
92 namedUint64 uint64
93 namedFloat64 float64
94 namedByte byte
95 netipAddr = netip.Addr
96
97 recursiveMap map[string]recursiveMap
98 recursiveSlice []recursiveSlice
99 recursivePointer struct{ P *recursivePointer }
100
101 structEmpty struct{}
102 structConflicting struct {
103 A string `json:"conflict"`
104 B string `json:"conflict"`
105 }
106 structNoneExported struct {
107 unexported string
108 }
109 structUnexportedIgnored struct {
110 ignored string `json:"-"`
111 }
112 structMalformedTag struct {
113 Malformed string `json:"\""`
114 }
115 structUnexportedTag struct {
116 unexported string `json:"name"`
117 }
118 structExportedEmbedded struct {
119 NamedString
120 }
121 structExportedEmbeddedTag struct {
122 NamedString `json:"name"`
123 }
124 structUnexportedEmbedded struct {
125 namedString
126 }
127 structUnexportedEmbeddedTag struct {
128 namedString `json:"name"`
129 }
130 structUnexportedEmbeddedMethodTag struct {
131 // netipAddr cannot be marshaled since the MarshalText method
132 // cannot be called on an unexported field.
133 netipAddr `json:"name"`
134
135 // Bogus MarshalText and AppendText methods are declared on
136 // structUnexportedEmbeddedMethodTag to prevent it from
137 // implementing those method interfaces.
138 }
139 structUnexportedEmbeddedStruct struct {
140 structOmitZeroAll
141 FizzBuzz int
142 structNestedAddr
143 }
144 structUnexportedEmbeddedStructPointer struct {
145 *structOmitZeroAll
146 FizzBuzz int
147 *structNestedAddr
148 }
149 structNestedAddr struct {
150 Addr netip.Addr
151 }
152 structIgnoredUnexportedEmbedded struct {
153 namedString `json:"-"`
154 }
155 structWeirdNames struct {
156 Empty string `json:"''"`
157 Comma string `json:"','"`
158 Quote string `json:"'\"'"`
159 }
160 structNoCase struct {
161 Aaa string `json:",case:strict"`
162 AA_A string
163 AaA string `json:",case:ignore"`
164 AAa string `json:",case:ignore"`
165 AAA string
166 }
167 structScalars struct {
168 unexported bool
169 Ignored bool `json:"-"`
170
171 Bool bool
172 String string
173 Bytes []byte
174 Int int64
175 Uint uint64
176 Float float64
177 }
178 structSlices struct {
179 unexported bool
180 Ignored bool `json:"-"`
181
182 SliceBool []bool
183 SliceString []string
184 SliceBytes [][]byte
185 SliceInt []int64
186 SliceUint []uint64
187 SliceFloat []float64
188 }
189 structMaps struct {
190 unexported bool
191 Ignored bool `json:"-"`
192
193 MapBool map[string]bool
194 MapString map[string]string
195 MapBytes map[string][]byte
196 MapInt map[string]int64
197 MapUint map[string]uint64
198 MapFloat map[string]float64
199 }
200 structAll struct {
201 Bool bool
202 String string
203 Bytes []byte
204 Int int64
205 Uint uint64
206 Float float64
207 Map map[string]string
208 StructScalars structScalars
209 StructMaps structMaps
210 StructSlices structSlices
211 Slice []string
212 Array [1]string
213 Pointer *structAll
214 Interface any
215 }
216 structStringifiedAll struct {
217 Bool bool `json:",string"`
218 String string `json:",string"`
219 Bytes []byte `json:",string"`
220 Int int64 `json:",string"`
221 Uint uint64 `json:",string"`
222 Float float64 `json:",string"`
223 Map map[string]string `json:",string"`
224 StructScalars structScalars `json:",string"`
225 StructMaps structMaps `json:",string"`
226 StructSlices structSlices `json:",string"`
227 Slice []string `json:",string"`
228 Array [1]string `json:",string"`
229 Pointer *structStringifiedAll `json:",string"`
230 Interface any `json:",string"`
231 }
232 structOmitZeroAll struct {
233 Bool bool `json:",omitzero"`
234 String string `json:",omitzero"`
235 Bytes []byte `json:",omitzero"`
236 Int int64 `json:",omitzero"`
237 Uint uint64 `json:",omitzero"`
238 Float float64 `json:",omitzero"`
239 Map map[string]string `json:",omitzero"`
240 StructScalars structScalars `json:",omitzero"`
241 StructMaps structMaps `json:",omitzero"`
242 StructSlices structSlices `json:",omitzero"`
243 Slice []string `json:",omitzero"`
244 Array [1]string `json:",omitzero"`
245 Pointer *structOmitZeroAll `json:",omitzero"`
246 Interface any `json:",omitzero"`
247 }
248 structOmitZeroMethodAll struct {
249 ValueAlwaysZero valueAlwaysZero `json:",omitzero"`
250 ValueNeverZero valueNeverZero `json:",omitzero"`
251 PointerAlwaysZero pointerAlwaysZero `json:",omitzero"`
252 PointerNeverZero pointerNeverZero `json:",omitzero"`
253 PointerValueAlwaysZero *valueAlwaysZero `json:",omitzero"`
254 PointerValueNeverZero *valueNeverZero `json:",omitzero"`
255 PointerPointerAlwaysZero *pointerAlwaysZero `json:",omitzero"`
256 PointerPointerNeverZero *pointerNeverZero `json:",omitzero"`
257 PointerPointerValueAlwaysZero **valueAlwaysZero `json:",omitzero"`
258 PointerPointerValueNeverZero **valueNeverZero `json:",omitzero"`
259 PointerPointerPointerAlwaysZero **pointerAlwaysZero `json:",omitzero"`
260 PointerPointerPointerNeverZero **pointerNeverZero `json:",omitzero"`
261 }
262 structOmitZeroMethodInterfaceAll struct {
263 ValueAlwaysZero isZeroer `json:",omitzero"`
264 ValueNeverZero isZeroer `json:",omitzero"`
265 PointerValueAlwaysZero isZeroer `json:",omitzero"`
266 PointerValueNeverZero isZeroer `json:",omitzero"`
267 PointerPointerAlwaysZero isZeroer `json:",omitzero"`
268 PointerPointerNeverZero isZeroer `json:",omitzero"`
269 }
270 structOmitEmptyAll struct {
271 Bool bool `json:",omitempty"`
272 PointerBool *bool `json:",omitempty"`
273 String string `json:",omitempty"`
274 StringEmpty stringMarshalEmpty `json:",omitempty"`
275 StringNonEmpty stringMarshalNonEmpty `json:",omitempty"`
276 PointerString *string `json:",omitempty"`
277 PointerStringEmpty *stringMarshalEmpty `json:",omitempty"`
278 PointerStringNonEmpty *stringMarshalNonEmpty `json:",omitempty"`
279 Bytes []byte `json:",omitempty"`
280 BytesEmpty bytesMarshalEmpty `json:",omitempty"`
281 BytesNonEmpty bytesMarshalNonEmpty `json:",omitempty"`
282 PointerBytes *[]byte `json:",omitempty"`
283 PointerBytesEmpty *bytesMarshalEmpty `json:",omitempty"`
284 PointerBytesNonEmpty *bytesMarshalNonEmpty `json:",omitempty"`
285 Float float64 `json:",omitempty"`
286 PointerFloat *float64 `json:",omitempty"`
287 Map map[string]string `json:",omitempty"`
288 MapEmpty mapMarshalEmpty `json:",omitempty"`
289 MapNonEmpty mapMarshalNonEmpty `json:",omitempty"`
290 PointerMap *map[string]string `json:",omitempty"`
291 PointerMapEmpty *mapMarshalEmpty `json:",omitempty"`
292 PointerMapNonEmpty *mapMarshalNonEmpty `json:",omitempty"`
293 Slice []string `json:",omitempty"`
294 SliceEmpty sliceMarshalEmpty `json:",omitempty"`
295 SliceNonEmpty sliceMarshalNonEmpty `json:",omitempty"`
296 PointerSlice *[]string `json:",omitempty"`
297 PointerSliceEmpty *sliceMarshalEmpty `json:",omitempty"`
298 PointerSliceNonEmpty *sliceMarshalNonEmpty `json:",omitempty"`
299 Pointer *structOmitZeroEmptyAll `json:",omitempty"`
300 Interface any `json:",omitempty"`
301 }
302 structOmitZeroEmptyAll struct {
303 Bool bool `json:",omitzero,omitempty"`
304 String string `json:",omitzero,omitempty"`
305 Bytes []byte `json:",omitzero,omitempty"`
306 Int int64 `json:",omitzero,omitempty"`
307 Uint uint64 `json:",omitzero,omitempty"`
308 Float float64 `json:",omitzero,omitempty"`
309 Map map[string]string `json:",omitzero,omitempty"`
310 Slice []string `json:",omitzero,omitempty"`
311 Array [1]string `json:",omitzero,omitempty"`
312 Pointer *structOmitZeroEmptyAll `json:",omitzero,omitempty"`
313 Interface any `json:",omitzero,omitempty"`
314 }
315 structFormatBytes struct {
316 Base16 []byte `json:",format:base16"`
317 Base32 []byte `json:",format:base32"`
318 Base32Hex []byte `json:",format:base32hex"`
319 Base64 []byte `json:",format:base64"`
320 Base64URL []byte `json:",format:base64url"`
321 Array []byte `json:",format:array"`
322 }
323 structFormatArrayBytes struct {
324 Base16 [4]byte `json:",format:base16"`
325 Base32 [4]byte `json:",format:base32"`
326 Base32Hex [4]byte `json:",format:base32hex"`
327 Base64 [4]byte `json:",format:base64"`
328 Base64URL [4]byte `json:",format:base64url"`
329 Array [4]byte `json:",format:array"`
330 Default [4]byte
331 }
332 structFormatFloats struct {
333 NonFinite float64 `json:",format:nonfinite"`
334 PointerNonFinite *float64 `json:",format:nonfinite"`
335 }
336 structFormatMaps struct {
337 EmitNull map[string]string `json:",format:emitnull"`
338 PointerEmitNull *map[string]string `json:",format:emitnull"`
339 EmitEmpty map[string]string `json:",format:emitempty"`
340 PointerEmitEmpty *map[string]string `json:",format:emitempty"`
341 EmitDefault map[string]string
342 PointerEmitDefault *map[string]string
343 }
344 structFormatSlices struct {
345 EmitNull []string `json:",format:emitnull"`
346 PointerEmitNull *[]string `json:",format:emitnull"`
347 EmitEmpty []string `json:",format:emitempty"`
348 PointerEmitEmpty *[]string `json:",format:emitempty"`
349 EmitDefault []string
350 PointerEmitDefault *[]string
351 }
352 structFormatInvalid struct {
353 Bool bool `json:",omitzero,format:invalid"`
354 String string `json:",omitzero,format:invalid"`
355 Bytes []byte `json:",omitzero,format:invalid"`
356 Int int64 `json:",omitzero,format:invalid"`
357 Uint uint64 `json:",omitzero,format:invalid"`
358 Float float64 `json:",omitzero,format:invalid"`
359 Map map[string]string `json:",omitzero,format:invalid"`
360 Struct structAll `json:",omitzero,format:invalid"`
361 Slice []string `json:",omitzero,format:invalid"`
362 Array [1]string `json:",omitzero,format:invalid"`
363 Interface any `json:",omitzero,format:invalid"`
364 }
365 structDurationFormat struct {
366 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
367 D2 time.Duration `json:",format:units"`
368 D3 time.Duration `json:",format:sec"`
369 D4 time.Duration `json:",string,format:sec"`
370 D5 time.Duration `json:",format:milli"`
371 D6 time.Duration `json:",string,format:milli"`
372 D7 time.Duration `json:",format:micro"`
373 D8 time.Duration `json:",string,format:micro"`
374 D9 time.Duration `json:",format:nano"`
375 D10 time.Duration `json:",string,format:nano"`
376 D11 time.Duration `json:",format:iso8601"`
377 }
378 structTimeFormat struct {
379 T1 time.Time
380 T2 time.Time `json:",format:ANSIC"`
381 T3 time.Time `json:",format:UnixDate"`
382 T4 time.Time `json:",format:RubyDate"`
383 T5 time.Time `json:",format:RFC822"`
384 T6 time.Time `json:",format:RFC822Z"`
385 T7 time.Time `json:",format:RFC850"`
386 T8 time.Time `json:",format:RFC1123"`
387 T9 time.Time `json:",format:RFC1123Z"`
388 T10 time.Time `json:",format:RFC3339"`
389 T11 time.Time `json:",format:RFC3339Nano"`
390 T12 time.Time `json:",format:Kitchen"`
391 T13 time.Time `json:",format:Stamp"`
392 T14 time.Time `json:",format:StampMilli"`
393 T15 time.Time `json:",format:StampMicro"`
394 T16 time.Time `json:",format:StampNano"`
395 T17 time.Time `json:",format:DateTime"`
396 T18 time.Time `json:",format:DateOnly"`
397 T19 time.Time `json:",format:TimeOnly"`
398 T20 time.Time `json:",format:'2006-01-02'"`
399 T21 time.Time `json:",format:'\"weird\"2006'"`
400 T22 time.Time `json:",format:unix"`
401 T23 time.Time `json:",string,format:unix"`
402 T24 time.Time `json:",format:unixmilli"`
403 T25 time.Time `json:",string,format:unixmilli"`
404 T26 time.Time `json:",format:unixmicro"`
405 T27 time.Time `json:",string,format:unixmicro"`
406 T28 time.Time `json:",format:unixnano"`
407 T29 time.Time `json:",string,format:unixnano"`
408 }
409 structInlined struct {
410 X structInlinedL1 `json:",inline"`
411 *StructEmbed2 // implicit inline
412 }
413 structInlinedL1 struct {
414 X *structInlinedL2 `json:",inline"`
415 StructEmbed1 `json:",inline"`
416 }
417 structInlinedL2 struct{ A, B, C string }
418 StructEmbed1 struct{ C, D, E string }
419 StructEmbed2 struct{ E, F, G string }
420 structUnknownTextValue struct {
421 A int `json:",omitzero"`
422 X jsontext.Value `json:",unknown"`
423 B int `json:",omitzero"`
424 }
425 structInlineTextValue struct {
426 A int `json:",omitzero"`
427 X jsontext.Value `json:",inline"`
428 B int `json:",omitzero"`
429 }
430 structInlinePointerTextValue struct {
431 A int `json:",omitzero"`
432 X *jsontext.Value `json:",inline"`
433 B int `json:",omitzero"`
434 }
435 structInlinePointerInlineTextValue struct {
436 X *struct {
437 A int
438 X jsontext.Value `json:",inline"`
439 } `json:",inline"`
440 }
441 structInlineInlinePointerTextValue struct {
442 X struct {
443 X *jsontext.Value `json:",inline"`
444 } `json:",inline"`
445 }
446 structInlineMapStringAny struct {
447 A int `json:",omitzero"`
448 X jsonObject `json:",inline"`
449 B int `json:",omitzero"`
450 }
451 structInlinePointerMapStringAny struct {
452 A int `json:",omitzero"`
453 X *jsonObject `json:",inline"`
454 B int `json:",omitzero"`
455 }
456 structInlinePointerInlineMapStringAny struct {
457 X *struct {
458 A int
459 X jsonObject `json:",inline"`
460 } `json:",inline"`
461 }
462 structInlineInlinePointerMapStringAny struct {
463 X struct {
464 X *jsonObject `json:",inline"`
465 } `json:",inline"`
466 }
467 structInlineMapStringInt struct {
468 X map[string]int `json:",inline"`
469 }
470 structInlineMapNamedStringInt struct {
471 X map[namedString]int `json:",inline"`
472 }
473 structInlineMapNamedStringAny struct {
474 A int `json:",omitzero"`
475 X map[namedString]any `json:",inline"`
476 B int `json:",omitzero"`
477 }
478 structNoCaseInlineTextValue struct {
479 AAA string `json:",omitempty,case:strict"`
480 AA_b string `json:",omitempty"`
481 AaA string `json:",omitempty,case:ignore"`
482 AAa string `json:",omitempty,case:ignore"`
483 Aaa string `json:",omitempty"`
484 X jsontext.Value `json:",inline"`
485 }
486 structNoCaseInlineMapStringAny struct {
487 AAA string `json:",omitempty"`
488 AaA string `json:",omitempty,case:ignore"`
489 AAa string `json:",omitempty,case:ignore"`
490 Aaa string `json:",omitempty"`
491 X jsonObject `json:",inline"`
492 }
493
494 allMethods struct {
495 method string // the method that was called
496 value []byte // the raw value to provide or store
497 }
498 allMethodsExceptJSONv2 struct {
499 allMethods
500 MarshalJSONTo struct{} // cancel out MarshalJSONTo method with collision
501 UnmarshalJSONFrom struct{} // cancel out UnmarshalJSONFrom method with collision
502 }
503 allMethodsExceptJSONv1 struct {
504 allMethods
505 MarshalJSON struct{} // cancel out MarshalJSON method with collision
506 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
507 }
508 allMethodsExceptText struct {
509 allMethods
510 MarshalText struct{} // cancel out MarshalText method with collision
511 UnmarshalText struct{} // cancel out UnmarshalText method with collision
512 }
513 onlyMethodJSONv2 struct {
514 allMethods
515 MarshalJSON struct{} // cancel out MarshalJSON method with collision
516 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
517 MarshalText struct{} // cancel out MarshalText method with collision
518 UnmarshalText struct{} // cancel out UnmarshalText method with collision
519 }
520 onlyMethodJSONv1 struct {
521 allMethods
522 MarshalJSONTo struct{} // cancel out MarshalJSONTo method with collision
523 UnmarshalJSONFrom struct{} // cancel out UnmarshalJSONFrom method with collision
524 MarshalText struct{} // cancel out MarshalText method with collision
525 UnmarshalText struct{} // cancel out UnmarshalText method with collision
526 }
527 onlyMethodText struct {
528 allMethods
529 MarshalJSONTo struct{} // cancel out MarshalJSONTo method with collision
530 UnmarshalJSONFrom struct{} // cancel out UnmarshalJSONFrom method with collision
531 MarshalJSON struct{} // cancel out MarshalJSON method with collision
532 UnmarshalJSON struct{} // cancel out UnmarshalJSON method with collision
533 }
534
535 structMethodJSONv2 struct{ value string }
536 structMethodJSONv1 struct{ value string }
537 structMethodText struct{ value string }
538
539 marshalJSONv2Func func(*jsontext.Encoder) error
540 marshalJSONv1Func func() ([]byte, error)
541 appendTextFunc func([]byte) ([]byte, error)
542 marshalTextFunc func() ([]byte, error)
543 unmarshalJSONv2Func func(*jsontext.Decoder) error
544 unmarshalJSONv1Func func([]byte) error
545 unmarshalTextFunc func([]byte) error
546
547 nocaseString string
548
549 stringMarshalEmpty string
550 stringMarshalNonEmpty string
551 bytesMarshalEmpty []byte
552 bytesMarshalNonEmpty []byte
553 mapMarshalEmpty map[string]string
554 mapMarshalNonEmpty map[string]string
555 sliceMarshalEmpty []string
556 sliceMarshalNonEmpty []string
557
558 valueAlwaysZero string
559 valueNeverZero string
560 pointerAlwaysZero string
561 pointerNeverZero string
562
563 valueStringer struct{}
564 pointerStringer struct{}
565
566 cyclicA struct {
567 B1 cyclicB `json:",inline"`
568 B2 cyclicB `json:",inline"`
569 }
570 cyclicB struct {
571 F int
572 A *cyclicA `json:",inline"`
573 }
574 )
575
576 func (structUnexportedEmbeddedMethodTag) MarshalText() {}
577 func (structUnexportedEmbeddedMethodTag) AppendText() {}
578
579 func (p *allMethods) MarshalJSONTo(enc *jsontext.Encoder) error {
580 if got, want := "MarshalJSONTo", p.method; got != want {
581 return fmt.Errorf("called wrong method: got %v, want %v", got, want)
582 }
583 return enc.WriteValue(p.value)
584 }
585 func (p *allMethods) MarshalJSON() ([]byte, error) {
586 if got, want := "MarshalJSON", p.method; got != want {
587 return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
588 }
589 return p.value, nil
590 }
591 func (p *allMethods) MarshalText() ([]byte, error) {
592 if got, want := "MarshalText", p.method; got != want {
593 return nil, fmt.Errorf("called wrong method: got %v, want %v", got, want)
594 }
595 return p.value, nil
596 }
597
598 func (p *allMethods) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
599 p.method = "UnmarshalJSONFrom"
600 val, err := dec.ReadValue()
601 p.value = val
602 return err
603 }
604 func (p *allMethods) UnmarshalJSON(val []byte) error {
605 p.method = "UnmarshalJSON"
606 p.value = val
607 return nil
608 }
609 func (p *allMethods) UnmarshalText(val []byte) error {
610 p.method = "UnmarshalText"
611 p.value = val
612 return nil
613 }
614
615 func (s structMethodJSONv2) MarshalJSONTo(enc *jsontext.Encoder) error {
616 return enc.WriteToken(jsontext.String(s.value))
617 }
618 func (s *structMethodJSONv2) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
619 tok, err := dec.ReadToken()
620 if err != nil {
621 return err
622 }
623 if k := tok.Kind(); k != '"' {
624 return EU(nil).withType(k, T[structMethodJSONv2]())
625 }
626 s.value = tok.String()
627 return nil
628 }
629
630 func (s structMethodJSONv1) MarshalJSON() ([]byte, error) {
631 return jsontext.AppendQuote(nil, s.value)
632 }
633 func (s *structMethodJSONv1) UnmarshalJSON(b []byte) error {
634 if k := jsontext.Value(b).Kind(); k != '"' {
635 return EU(nil).withType(k, T[structMethodJSONv1]())
636 }
637 b, _ = jsontext.AppendUnquote(nil, b)
638 s.value = string(b)
639 return nil
640 }
641
642 func (s structMethodText) MarshalText() ([]byte, error) {
643 return []byte(s.value), nil
644 }
645 func (s *structMethodText) UnmarshalText(b []byte) error {
646 s.value = string(b)
647 return nil
648 }
649
650 func (f marshalJSONv2Func) MarshalJSONTo(enc *jsontext.Encoder) error {
651 return f(enc)
652 }
653 func (f marshalJSONv1Func) MarshalJSON() ([]byte, error) {
654 return f()
655 }
656 func (f appendTextFunc) AppendText(b []byte) ([]byte, error) {
657 return f(b)
658 }
659 func (f marshalTextFunc) MarshalText() ([]byte, error) {
660 return f()
661 }
662 func (f unmarshalJSONv2Func) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
663 return f(dec)
664 }
665 func (f unmarshalJSONv1Func) UnmarshalJSON(b []byte) error {
666 return f(b)
667 }
668 func (f unmarshalTextFunc) UnmarshalText(b []byte) error {
669 return f(b)
670 }
671
672 func (k nocaseString) MarshalText() ([]byte, error) {
673 return []byte(strings.ToLower(string(k))), nil
674 }
675 func (k *nocaseString) UnmarshalText(b []byte) error {
676 *k = nocaseString(strings.ToLower(string(b)))
677 return nil
678 }
679
680 func (stringMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`""`), nil }
681 func (stringMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`"value"`), nil }
682 func (bytesMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
683 func (bytesMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
684 func (mapMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`{}`), nil }
685 func (mapMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`{"key":"value"}`), nil }
686 func (sliceMarshalEmpty) MarshalJSON() ([]byte, error) { return []byte(`[]`), nil }
687 func (sliceMarshalNonEmpty) MarshalJSON() ([]byte, error) { return []byte(`["value"]`), nil }
688
689 func (valueAlwaysZero) IsZero() bool { return true }
690 func (valueNeverZero) IsZero() bool { return false }
691 func (*pointerAlwaysZero) IsZero() bool { return true }
692 func (*pointerNeverZero) IsZero() bool { return false }
693
694 func (valueStringer) String() string { return "" }
695 func (*pointerStringer) String() string { return "" }
696
697 func addr[T any](v T) *T {
698 return &v
699 }
700
701 func mustParseTime(layout, value string) time.Time {
702 t, err := time.Parse(layout, value)
703 if err != nil {
704 panic(err)
705 }
706 return t
707 }
708
709 var invalidFormatOption = &jsonopts.Struct{
710 ArshalValues: jsonopts.ArshalValues{FormatDepth: 1000, Format: "invalid"},
711 }
712
713 func TestMarshal(t *testing.T) {
714 tests := []struct {
715 name jsontest.CaseName
716 opts []Options
717 in any
718 want string
719 wantErr error
720
721 canonicalize bool // canonicalize the output before comparing?
722 useWriter bool // call MarshalWrite instead of Marshal
723 }{{
724 name: jsontest.Name("Nil"),
725 in: nil,
726 want: `null`,
727 }, {
728 name: jsontest.Name("Bools"),
729 in: []bool{false, true},
730 want: `[false,true]`,
731 }, {
732 name: jsontest.Name("Bools/Named"),
733 in: []namedBool{false, true},
734 want: `[false,true]`,
735 }, {
736 name: jsontest.Name("Bools/NotStringified"),
737 opts: []Options{StringifyNumbers(true)},
738 in: []bool{false, true},
739 want: `[false,true]`,
740 }, {
741 name: jsontest.Name("Bools/StringifiedBool"),
742 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
743 in: []bool{false, true},
744 want: `["false","true"]`,
745 }, {
746 name: jsontest.Name("Bools/IgnoreInvalidFormat"),
747 opts: []Options{invalidFormatOption},
748 in: true,
749 want: `true`,
750 }, {
751 name: jsontest.Name("Strings"),
752 in: []string{"", "hello", "世界"},
753 want: `["","hello","世界"]`,
754 }, {
755 name: jsontest.Name("Strings/Named"),
756 in: []namedString{"", "hello", "世界"},
757 want: `["","hello","世界"]`,
758 }, {
759 name: jsontest.Name("Strings/StringifiedBool"),
760 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
761 in: []string{"", "hello", "世界"},
762 want: `["\"\"","\"hello\"","\"世界\""]`,
763 }, {
764 name: jsontest.Name("Strings/IgnoreInvalidFormat"),
765 opts: []Options{invalidFormatOption},
766 in: "string",
767 want: `"string"`,
768 }, {
769 name: jsontest.Name("Bytes"),
770 in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
771 want: `["","","AQ==","AQI=","AQID"]`,
772 }, {
773 name: jsontest.Name("Bytes/FormatNilSliceAsNull"),
774 opts: []Options{FormatNilSliceAsNull(true)},
775 in: [][]byte{nil, {}},
776 want: `[null,""]`,
777 }, {
778 name: jsontest.Name("Bytes/Large"),
779 in: []byte("the quick brown fox jumped over the lazy dog and ate the homework that I spent so much time on."),
780 want: `"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgYW5kIGF0ZSB0aGUgaG9tZXdvcmsgdGhhdCBJIHNwZW50IHNvIG11Y2ggdGltZSBvbi4="`,
781 }, {
782 name: jsontest.Name("Bytes/Named"),
783 in: []namedBytes{nil, {}, {1}, {1, 2}, {1, 2, 3}},
784 want: `["","","AQ==","AQI=","AQID"]`,
785 }, {
786 name: jsontest.Name("Bytes/NotStringified"),
787 opts: []Options{StringifyNumbers(true)},
788 in: [][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
789 want: `["","","AQ==","AQI=","AQID"]`,
790 }, {
791 // NOTE: []namedByte is not assignable to []byte,
792 // so the following should be treated as a slice of uints.
793 name: jsontest.Name("Bytes/Invariant"),
794 in: [][]namedByte{nil, {}, {1}, {1, 2}, {1, 2, 3}},
795 want: `[[],[],[1],[1,2],[1,2,3]]`,
796 }, {
797 // NOTE: This differs in behavior from v1,
798 // but keeps the representation of slices and arrays more consistent.
799 name: jsontest.Name("Bytes/ByteArray"),
800 in: [5]byte{'h', 'e', 'l', 'l', 'o'},
801 want: `"aGVsbG8="`,
802 }, {
803 // NOTE: []namedByte is not assignable to []byte,
804 // so the following should be treated as an array of uints.
805 name: jsontest.Name("Bytes/NamedByteArray"),
806 in: [5]namedByte{'h', 'e', 'l', 'l', 'o'},
807 want: `[104,101,108,108,111]`,
808 }, {
809 name: jsontest.Name("Bytes/IgnoreInvalidFormat"),
810 opts: []Options{invalidFormatOption},
811 in: []byte("hello"),
812 want: `"aGVsbG8="`,
813 }, {
814 name: jsontest.Name("Ints"),
815 in: []any{
816 int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
817 },
818 want: `[0,-128,-32768,-2147483648,-9223372036854775808,-6464]`,
819 }, {
820 name: jsontest.Name("Ints/Stringified"),
821 opts: []Options{StringifyNumbers(true)},
822 in: []any{
823 int(0), int8(math.MinInt8), int16(math.MinInt16), int32(math.MinInt32), int64(math.MinInt64), namedInt64(-6464),
824 },
825 want: `["0","-128","-32768","-2147483648","-9223372036854775808","-6464"]`,
826 }, {
827 name: jsontest.Name("Ints/IgnoreInvalidFormat"),
828 opts: []Options{invalidFormatOption},
829 in: int(0),
830 want: `0`,
831 }, {
832 name: jsontest.Name("Uints"),
833 in: []any{
834 uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464), uintptr(1234),
835 },
836 want: `[0,255,65535,4294967295,18446744073709551615,6464,1234]`,
837 }, {
838 name: jsontest.Name("Uints/Stringified"),
839 opts: []Options{StringifyNumbers(true)},
840 in: []any{
841 uint(0), uint8(math.MaxUint8), uint16(math.MaxUint16), uint32(math.MaxUint32), uint64(math.MaxUint64), namedUint64(6464),
842 },
843 want: `["0","255","65535","4294967295","18446744073709551615","6464"]`,
844 }, {
845 name: jsontest.Name("Uints/IgnoreInvalidFormat"),
846 opts: []Options{invalidFormatOption},
847 in: uint(0),
848 want: `0`,
849 }, {
850 name: jsontest.Name("Floats"),
851 in: []any{
852 float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
853 },
854 want: `[3.4028235e+38,1.7976931348623157e+308,64.64]`,
855 }, {
856 name: jsontest.Name("Floats/Stringified"),
857 opts: []Options{StringifyNumbers(true)},
858 in: []any{
859 float32(math.MaxFloat32), float64(math.MaxFloat64), namedFloat64(64.64),
860 },
861 want: `["3.4028235e+38","1.7976931348623157e+308","64.64"]`,
862 }, {
863 name: jsontest.Name("Floats/Invalid/NaN"),
864 opts: []Options{StringifyNumbers(true)},
865 in: math.NaN(),
866 wantErr: EM(fmt.Errorf("unsupported value: %v", math.NaN())).withType(0, float64Type),
867 }, {
868 name: jsontest.Name("Floats/Invalid/PositiveInfinity"),
869 in: math.Inf(+1),
870 wantErr: EM(fmt.Errorf("unsupported value: %v", math.Inf(+1))).withType(0, float64Type),
871 }, {
872 name: jsontest.Name("Floats/Invalid/NegativeInfinity"),
873 in: math.Inf(-1),
874 wantErr: EM(fmt.Errorf("unsupported value: %v", math.Inf(-1))).withType(0, float64Type),
875 }, {
876 name: jsontest.Name("Floats/IgnoreInvalidFormat"),
877 opts: []Options{invalidFormatOption},
878 in: float64(0),
879 want: `0`,
880 }, {
881 name: jsontest.Name("Maps/InvalidKey/Bool"),
882 in: map[bool]string{false: "value"},
883 want: `{`,
884 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, boolType),
885 }, {
886 name: jsontest.Name("Maps/InvalidKey/NamedBool"),
887 in: map[namedBool]string{false: "value"},
888 want: `{`,
889 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[namedBool]()),
890 }, {
891 name: jsontest.Name("Maps/InvalidKey/Array"),
892 in: map[[1]string]string{{"key"}: "value"},
893 want: `{`,
894 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[[1]string]()),
895 }, {
896 name: jsontest.Name("Maps/InvalidKey/Channel"),
897 in: map[chan string]string{make(chan string): "value"},
898 want: `{`,
899 wantErr: EM(nil).withPos(`{`, "").withType(0, T[chan string]()),
900 }, {
901 name: jsontest.Name("Maps/ValidKey/Int"),
902 in: map[int64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
903 canonicalize: true,
904 want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
905 }, {
906 name: jsontest.Name("Maps/ValidKey/PointerInt"),
907 in: map[*int64]string{addr(int64(math.MinInt64)): "MinInt64", addr(int64(0)): "Zero", addr(int64(math.MaxInt64)): "MaxInt64"},
908 canonicalize: true,
909 want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
910 }, {
911 name: jsontest.Name("Maps/DuplicateName/PointerInt"),
912 in: map[*int64]string{addr(int64(0)): "0", addr(int64(0)): "0"},
913 canonicalize: true,
914 want: `{"0":"0"`,
915 wantErr: newDuplicateNameError("", []byte(`"0"`), len64(`{"0":"0",`)),
916 }, {
917 name: jsontest.Name("Maps/ValidKey/NamedInt"),
918 in: map[namedInt64]string{math.MinInt64: "MinInt64", 0: "Zero", math.MaxInt64: "MaxInt64"},
919 canonicalize: true,
920 want: `{"-9223372036854775808":"MinInt64","0":"Zero","9223372036854775807":"MaxInt64"}`,
921 }, {
922 name: jsontest.Name("Maps/ValidKey/Uint"),
923 in: map[uint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
924 canonicalize: true,
925 want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
926 }, {
927 name: jsontest.Name("Maps/ValidKey/NamedUint"),
928 in: map[namedUint64]string{0: "Zero", math.MaxUint64: "MaxUint64"},
929 canonicalize: true,
930 want: `{"0":"Zero","18446744073709551615":"MaxUint64"}`,
931 }, {
932 name: jsontest.Name("Maps/ValidKey/Float"),
933 in: map[float64]string{3.14159: "value"},
934 want: `{"3.14159":"value"}`,
935 }, {
936 name: jsontest.Name("Maps/InvalidKey/Float/NaN"),
937 in: map[float64]string{math.NaN(): "NaN", math.NaN(): "NaN"},
938 want: `{`,
939 wantErr: EM(errors.New("unsupported value: NaN")).withPos(`{`, "").withType(0, float64Type),
940 }, {
941 name: jsontest.Name("Maps/ValidKey/Interface"),
942 in: map[any]any{
943 "key": "key",
944 namedInt64(-64): int32(-32),
945 namedUint64(+64): uint32(+32),
946 namedFloat64(64.64): float32(32.32),
947 },
948 canonicalize: true,
949 want: `{"-64":-32,"64":32,"64.64":32.32,"key":"key"}`,
950 }, {
951 name: jsontest.Name("Maps/DuplicateName/String/AllowInvalidUTF8+AllowDuplicateNames"),
952 opts: []Options{jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(true)},
953 in: map[string]string{"\x80": "", "\x81": ""},
954 want: `{"�":"","�":""}`,
955 }, {
956 name: jsontest.Name("Maps/DuplicateName/String/AllowInvalidUTF8"),
957 opts: []Options{jsontext.AllowInvalidUTF8(true)},
958 in: map[string]string{"\x80": "", "\x81": ""},
959 want: `{"�":""`,
960 wantErr: newDuplicateNameError("", []byte(`"�"`), len64(`{"�":"",`)),
961 }, {
962 name: jsontest.Name("Maps/DuplicateName/NoCaseString/AllowDuplicateNames"),
963 opts: []Options{jsontext.AllowDuplicateNames(true)},
964 in: map[nocaseString]string{"hello": "", "HELLO": ""},
965 want: `{"hello":"","hello":""}`,
966 }, {
967 name: jsontest.Name("Maps/DuplicateName/NoCaseString"),
968 in: map[nocaseString]string{"hello": "", "HELLO": ""},
969 want: `{"hello":""`,
970 wantErr: EM(newDuplicateNameError("", []byte(`"hello"`), len64(`{"hello":"",`))).withPos(`{"hello":"",`, "").withType(0, T[nocaseString]()),
971 }, {
972 name: jsontest.Name("Maps/DuplicateName/NaNs/Deterministic+AllowDuplicateNames"),
973 opts: []Options{
974 WithMarshalers(
975 MarshalFunc(func(v float64) ([]byte, error) { return []byte(`"NaN"`), nil }),
976 ),
977 Deterministic(true),
978 jsontext.AllowDuplicateNames(true),
979 },
980 in: map[float64]string{math.NaN(): "NaN", math.NaN(): "NaN"},
981 want: `{"NaN":"NaN","NaN":"NaN"}`,
982 }, {
983 name: jsontest.Name("Maps/InvalidValue/Channel"),
984 in: map[string]chan string{
985 "key": nil,
986 },
987 want: `{"key"`,
988 wantErr: EM(nil).withPos(`{"key":`, "/key").withType(0, T[chan string]()),
989 }, {
990 name: jsontest.Name("Maps/String/Deterministic"),
991 opts: []Options{Deterministic(true)},
992 in: map[string]int{"a": 0, "b": 1, "c": 2},
993 want: `{"a":0,"b":1,"c":2}`,
994 }, {
995 name: jsontest.Name("Maps/String/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
996 opts: []Options{
997 Deterministic(true),
998 jsontext.AllowInvalidUTF8(true),
999 jsontext.AllowDuplicateNames(false),
1000 },
1001 in: map[string]int{"\xff": 0, "\xfe": 1},
1002 want: `{"�":1`,
1003 wantErr: newDuplicateNameError("", []byte(`"�"`), len64(`{"�":1,`)),
1004 }, {
1005 name: jsontest.Name("Maps/String/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
1006 opts: []Options{
1007 Deterministic(true),
1008 jsontext.AllowInvalidUTF8(true),
1009 jsontext.AllowDuplicateNames(true),
1010 },
1011 in: map[string]int{"\xff": 0, "\xfe": 1},
1012 want: `{"�":1,"�":0}`,
1013 }, {
1014 name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs"),
1015 opts: []Options{
1016 Deterministic(true),
1017 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v string) error {
1018 if p := enc.StackPointer(); p != "/X" {
1019 return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
1020 }
1021 switch v {
1022 case "a":
1023 return enc.WriteToken(jsontext.String("b"))
1024 case "b":
1025 return enc.WriteToken(jsontext.String("a"))
1026 default:
1027 return fmt.Errorf("invalid value: %q", v)
1028 }
1029 })),
1030 },
1031 in: map[namedString]map[string]int{"X": {"a": -1, "b": 1}},
1032 want: `{"X":{"a":1,"b":-1}}`,
1033 }, {
1034 name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs+RejectDuplicateNames"),
1035 opts: []Options{
1036 Deterministic(true),
1037 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v string) error {
1038 if p := enc.StackPointer(); p != "/X" {
1039 return fmt.Errorf("invalid stack pointer: got %s, want /X", p)
1040 }
1041 switch v {
1042 case "a", "b":
1043 return enc.WriteToken(jsontext.String("x"))
1044 default:
1045 return fmt.Errorf("invalid value: %q", v)
1046 }
1047 })),
1048 jsontext.AllowDuplicateNames(false),
1049 },
1050 in: map[namedString]map[string]int{"X": {"a": 1, "b": 1}},
1051 want: `{"X":{"x":1`,
1052 wantErr: newDuplicateNameError("/X/x", nil, len64(`{"X":{"x":1,`)),
1053 }, {
1054 name: jsontest.Name("Maps/String/Deterministic+MarshalFuncs+AllowDuplicateNames"),
1055 opts: []Options{
1056 Deterministic(true),
1057 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v string) error {
1058 if p := enc.StackPointer(); p != "/X" {
1059 return fmt.Errorf("invalid stack pointer: got %s, want /0", p)
1060 }
1061 switch v {
1062 case "a", "b":
1063 return enc.WriteToken(jsontext.String("x"))
1064 default:
1065 return fmt.Errorf("invalid value: %q", v)
1066 }
1067 })),
1068 jsontext.AllowDuplicateNames(true),
1069 },
1070 in: map[namedString]map[string]int{"X": {"a": 1, "b": 1}},
1071 // NOTE: Since the names are identical, the exact values may be
1072 // non-deterministic since sort cannot distinguish between members.
1073 want: `{"X":{"x":1,"x":1}}`,
1074 }, {
1075 name: jsontest.Name("Maps/RecursiveMap"),
1076 in: recursiveMap{
1077 "fizz": {
1078 "foo": {},
1079 "bar": nil,
1080 },
1081 "buzz": nil,
1082 },
1083 canonicalize: true,
1084 want: `{"buzz":{},"fizz":{"bar":{},"foo":{}}}`,
1085 }, {
1086 name: jsontest.Name("Maps/CyclicMap"),
1087 in: func() recursiveMap {
1088 m := recursiveMap{"k": nil}
1089 m["k"] = m
1090 return m
1091 }(),
1092 want: strings.Repeat(`{"k":`, startDetectingCyclesAfter) + `{"k"`,
1093 wantErr: EM(internal.ErrCycle).withPos(strings.Repeat(`{"k":`, startDetectingCyclesAfter+1), jsontext.Pointer(strings.Repeat("/k", startDetectingCyclesAfter+1))).withType(0, T[recursiveMap]()),
1094 }, {
1095 name: jsontest.Name("Maps/IgnoreInvalidFormat"),
1096 opts: []Options{invalidFormatOption},
1097 in: map[string]string{},
1098 want: `{}`,
1099 }, {
1100 name: jsontest.Name("Structs/Empty"),
1101 in: structEmpty{},
1102 want: `{}`,
1103 }, {
1104 name: jsontest.Name("Structs/UnexportedIgnored"),
1105 in: structUnexportedIgnored{ignored: "ignored"},
1106 want: `{}`,
1107 }, {
1108 name: jsontest.Name("Structs/IgnoredUnexportedEmbedded"),
1109 in: structIgnoredUnexportedEmbedded{namedString: "ignored"},
1110 want: `{}`,
1111 }, {
1112 name: jsontest.Name("Structs/WeirdNames"),
1113 in: structWeirdNames{Empty: "empty", Comma: "comma", Quote: "quote"},
1114 want: `{"":"empty",",":"comma","\"":"quote"}`,
1115 }, {
1116 name: jsontest.Name("Structs/EscapedNames"),
1117 opts: []Options{jsontext.EscapeForHTML(true), jsontext.EscapeForJS(true)},
1118 in: struct {
1119 S string "json:\"'abc<>&\u2028\u2029xyz'\""
1120 M any
1121 I structInlineTextValue
1122 }{
1123 S: "abc<>&\u2028\u2029xyz",
1124 M: map[string]string{"abc<>&\u2028\u2029xyz": "abc<>&\u2028\u2029xyz"},
1125 I: structInlineTextValue{X: jsontext.Value(`{"abc<>&` + "\u2028\u2029" + `xyz":"abc<>&` + "\u2028\u2029" + `xyz"}`)},
1126 },
1127 want: `{"abc\u003c\u003e\u0026\u2028\u2029xyz":"abc\u003c\u003e\u0026\u2028\u2029xyz","M":{"abc\u003c\u003e\u0026\u2028\u2029xyz":"abc\u003c\u003e\u0026\u2028\u2029xyz"},"I":{"abc\u003c\u003e\u0026\u2028\u2029xyz":"abc\u003c\u003e\u0026\u2028\u2029xyz"}}`,
1128 }, {
1129 name: jsontest.Name("Structs/NoCase"),
1130 in: structNoCase{AaA: "AaA", AAa: "AAa", Aaa: "Aaa", AAA: "AAA", AA_A: "AA_A"},
1131 want: `{"Aaa":"Aaa","AA_A":"AA_A","AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
1132 }, {
1133 name: jsontest.Name("Structs/NoCase/MatchCaseInsensitiveNames"),
1134 opts: []Options{MatchCaseInsensitiveNames(true)},
1135 in: structNoCase{AaA: "AaA", AAa: "AAa", Aaa: "Aaa", AAA: "AAA", AA_A: "AA_A"},
1136 want: `{"Aaa":"Aaa","AA_A":"AA_A","AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
1137 }, {
1138 name: jsontest.Name("Structs/NoCase/MatchCaseInsensitiveNames+MatchCaseSensitiveDelimiter"),
1139 opts: []Options{MatchCaseInsensitiveNames(true), jsonflags.MatchCaseSensitiveDelimiter | 1},
1140 in: structNoCase{AaA: "AaA", AAa: "AAa", Aaa: "Aaa", AAA: "AAA", AA_A: "AA_A"},
1141 want: `{"Aaa":"Aaa","AA_A":"AA_A","AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
1142 }, {
1143 name: jsontest.Name("Structs/Normal"),
1144 opts: []Options{jsontext.Multiline(true)},
1145 in: structAll{
1146 Bool: true,
1147 String: "hello",
1148 Bytes: []byte{1, 2, 3},
1149 Int: -64,
1150 Uint: +64,
1151 Float: 3.14159,
1152 Map: map[string]string{"key": "value"},
1153 StructScalars: structScalars{
1154 Bool: true,
1155 String: "hello",
1156 Bytes: []byte{1, 2, 3},
1157 Int: -64,
1158 Uint: +64,
1159 Float: 3.14159,
1160 },
1161 StructMaps: structMaps{
1162 MapBool: map[string]bool{"": true},
1163 MapString: map[string]string{"": "hello"},
1164 MapBytes: map[string][]byte{"": {1, 2, 3}},
1165 MapInt: map[string]int64{"": -64},
1166 MapUint: map[string]uint64{"": +64},
1167 MapFloat: map[string]float64{"": 3.14159},
1168 },
1169 StructSlices: structSlices{
1170 SliceBool: []bool{true},
1171 SliceString: []string{"hello"},
1172 SliceBytes: [][]byte{{1, 2, 3}},
1173 SliceInt: []int64{-64},
1174 SliceUint: []uint64{+64},
1175 SliceFloat: []float64{3.14159},
1176 },
1177 Slice: []string{"fizz", "buzz"},
1178 Array: [1]string{"goodbye"},
1179 Pointer: new(structAll),
1180 Interface: (*structAll)(nil),
1181 },
1182 want: `{
1183 "Bool": true,
1184 "String": "hello",
1185 "Bytes": "AQID",
1186 "Int": -64,
1187 "Uint": 64,
1188 "Float": 3.14159,
1189 "Map": {
1190 "key": "value"
1191 },
1192 "StructScalars": {
1193 "Bool": true,
1194 "String": "hello",
1195 "Bytes": "AQID",
1196 "Int": -64,
1197 "Uint": 64,
1198 "Float": 3.14159
1199 },
1200 "StructMaps": {
1201 "MapBool": {
1202 "": true
1203 },
1204 "MapString": {
1205 "": "hello"
1206 },
1207 "MapBytes": {
1208 "": "AQID"
1209 },
1210 "MapInt": {
1211 "": -64
1212 },
1213 "MapUint": {
1214 "": 64
1215 },
1216 "MapFloat": {
1217 "": 3.14159
1218 }
1219 },
1220 "StructSlices": {
1221 "SliceBool": [
1222 true
1223 ],
1224 "SliceString": [
1225 "hello"
1226 ],
1227 "SliceBytes": [
1228 "AQID"
1229 ],
1230 "SliceInt": [
1231 -64
1232 ],
1233 "SliceUint": [
1234 64
1235 ],
1236 "SliceFloat": [
1237 3.14159
1238 ]
1239 },
1240 "Slice": [
1241 "fizz",
1242 "buzz"
1243 ],
1244 "Array": [
1245 "goodbye"
1246 ],
1247 "Pointer": {
1248 "Bool": false,
1249 "String": "",
1250 "Bytes": "",
1251 "Int": 0,
1252 "Uint": 0,
1253 "Float": 0,
1254 "Map": {},
1255 "StructScalars": {
1256 "Bool": false,
1257 "String": "",
1258 "Bytes": "",
1259 "Int": 0,
1260 "Uint": 0,
1261 "Float": 0
1262 },
1263 "StructMaps": {
1264 "MapBool": {},
1265 "MapString": {},
1266 "MapBytes": {},
1267 "MapInt": {},
1268 "MapUint": {},
1269 "MapFloat": {}
1270 },
1271 "StructSlices": {
1272 "SliceBool": [],
1273 "SliceString": [],
1274 "SliceBytes": [],
1275 "SliceInt": [],
1276 "SliceUint": [],
1277 "SliceFloat": []
1278 },
1279 "Slice": [],
1280 "Array": [
1281 ""
1282 ],
1283 "Pointer": null,
1284 "Interface": null
1285 },
1286 "Interface": null
1287 }`,
1288 }, {
1289 name: jsontest.Name("Structs/SpaceAfterColonAndComma"),
1290 opts: []Options{jsontext.SpaceAfterColon(true), jsontext.SpaceAfterComma(true)},
1291 in: structOmitZeroAll{Int: 1, Uint: 1},
1292 want: `{"Int": 1, "Uint": 1}`,
1293 }, {
1294 name: jsontest.Name("Structs/SpaceAfterColon"),
1295 opts: []Options{jsontext.SpaceAfterColon(true)},
1296 in: structOmitZeroAll{Int: 1, Uint: 1},
1297 want: `{"Int": 1,"Uint": 1}`,
1298 }, {
1299 name: jsontest.Name("Structs/SpaceAfterComma"),
1300 opts: []Options{jsontext.SpaceAfterComma(true)},
1301 in: structOmitZeroAll{Int: 1, Uint: 1, Slice: []string{"a", "b"}},
1302 want: `{"Int":1, "Uint":1, "Slice":["a", "b"]}`,
1303 }, {
1304 name: jsontest.Name("Structs/Stringified"),
1305 opts: []Options{jsontext.Multiline(true)},
1306 in: structStringifiedAll{
1307 Bool: true,
1308 String: "hello",
1309 Bytes: []byte{1, 2, 3},
1310 Int: -64, // should be stringified
1311 Uint: +64, // should be stringified
1312 Float: 3.14159, // should be stringified
1313 Map: map[string]string{"key": "value"},
1314 StructScalars: structScalars{
1315 Bool: true,
1316 String: "hello",
1317 Bytes: []byte{1, 2, 3},
1318 Int: -64, // should be stringified
1319 Uint: +64, // should be stringified
1320 Float: 3.14159, // should be stringified
1321 },
1322 StructMaps: structMaps{
1323 MapBool: map[string]bool{"": true},
1324 MapString: map[string]string{"": "hello"},
1325 MapBytes: map[string][]byte{"": {1, 2, 3}},
1326 MapInt: map[string]int64{"": -64}, // should be stringified
1327 MapUint: map[string]uint64{"": +64}, // should be stringified
1328 MapFloat: map[string]float64{"": 3.14159}, // should be stringified
1329 },
1330 StructSlices: structSlices{
1331 SliceBool: []bool{true},
1332 SliceString: []string{"hello"},
1333 SliceBytes: [][]byte{{1, 2, 3}},
1334 SliceInt: []int64{-64}, // should be stringified
1335 SliceUint: []uint64{+64}, // should be stringified
1336 SliceFloat: []float64{3.14159}, // should be stringified
1337 },
1338 Slice: []string{"fizz", "buzz"},
1339 Array: [1]string{"goodbye"},
1340 Pointer: new(structStringifiedAll), // should be stringified
1341 Interface: (*structStringifiedAll)(nil),
1342 },
1343 want: `{
1344 "Bool": true,
1345 "String": "hello",
1346 "Bytes": "AQID",
1347 "Int": "-64",
1348 "Uint": "64",
1349 "Float": "3.14159",
1350 "Map": {
1351 "key": "value"
1352 },
1353 "StructScalars": {
1354 "Bool": true,
1355 "String": "hello",
1356 "Bytes": "AQID",
1357 "Int": "-64",
1358 "Uint": "64",
1359 "Float": "3.14159"
1360 },
1361 "StructMaps": {
1362 "MapBool": {
1363 "": true
1364 },
1365 "MapString": {
1366 "": "hello"
1367 },
1368 "MapBytes": {
1369 "": "AQID"
1370 },
1371 "MapInt": {
1372 "": "-64"
1373 },
1374 "MapUint": {
1375 "": "64"
1376 },
1377 "MapFloat": {
1378 "": "3.14159"
1379 }
1380 },
1381 "StructSlices": {
1382 "SliceBool": [
1383 true
1384 ],
1385 "SliceString": [
1386 "hello"
1387 ],
1388 "SliceBytes": [
1389 "AQID"
1390 ],
1391 "SliceInt": [
1392 "-64"
1393 ],
1394 "SliceUint": [
1395 "64"
1396 ],
1397 "SliceFloat": [
1398 "3.14159"
1399 ]
1400 },
1401 "Slice": [
1402 "fizz",
1403 "buzz"
1404 ],
1405 "Array": [
1406 "goodbye"
1407 ],
1408 "Pointer": {
1409 "Bool": false,
1410 "String": "",
1411 "Bytes": "",
1412 "Int": "0",
1413 "Uint": "0",
1414 "Float": "0",
1415 "Map": {},
1416 "StructScalars": {
1417 "Bool": false,
1418 "String": "",
1419 "Bytes": "",
1420 "Int": "0",
1421 "Uint": "0",
1422 "Float": "0"
1423 },
1424 "StructMaps": {
1425 "MapBool": {},
1426 "MapString": {},
1427 "MapBytes": {},
1428 "MapInt": {},
1429 "MapUint": {},
1430 "MapFloat": {}
1431 },
1432 "StructSlices": {
1433 "SliceBool": [],
1434 "SliceString": [],
1435 "SliceBytes": [],
1436 "SliceInt": [],
1437 "SliceUint": [],
1438 "SliceFloat": []
1439 },
1440 "Slice": [],
1441 "Array": [
1442 ""
1443 ],
1444 "Pointer": null,
1445 "Interface": null
1446 },
1447 "Interface": null
1448 }`,
1449 }, {
1450 name: jsontest.Name("Structs/LegacyStringified"),
1451 opts: []Options{jsontext.Multiline(true), jsonflags.StringifyWithLegacySemantics | 1},
1452 in: structStringifiedAll{
1453 Bool: true, // should be stringified
1454 String: "hello", // should be stringified
1455 Bytes: []byte{1, 2, 3},
1456 Int: -64, // should be stringified
1457 Uint: +64, // should be stringified
1458 Float: 3.14159, // should be stringified
1459 Map: map[string]string{"key": "value"},
1460 StructScalars: structScalars{
1461 Bool: true,
1462 String: "hello",
1463 Bytes: []byte{1, 2, 3},
1464 Int: -64,
1465 Uint: +64,
1466 Float: 3.14159,
1467 },
1468 StructMaps: structMaps{
1469 MapBool: map[string]bool{"": true},
1470 MapString: map[string]string{"": "hello"},
1471 MapBytes: map[string][]byte{"": {1, 2, 3}},
1472 MapInt: map[string]int64{"": -64},
1473 MapUint: map[string]uint64{"": +64},
1474 MapFloat: map[string]float64{"": 3.14159},
1475 },
1476 StructSlices: structSlices{
1477 SliceBool: []bool{true},
1478 SliceString: []string{"hello"},
1479 SliceBytes: [][]byte{{1, 2, 3}},
1480 SliceInt: []int64{-64},
1481 SliceUint: []uint64{+64},
1482 SliceFloat: []float64{3.14159},
1483 },
1484 Slice: []string{"fizz", "buzz"},
1485 Array: [1]string{"goodbye"},
1486 Pointer: new(structStringifiedAll), // should be stringified
1487 Interface: (*structStringifiedAll)(nil),
1488 },
1489 want: `{
1490 "Bool": "true",
1491 "String": "\"hello\"",
1492 "Bytes": "AQID",
1493 "Int": "-64",
1494 "Uint": "64",
1495 "Float": "3.14159",
1496 "Map": {
1497 "key": "value"
1498 },
1499 "StructScalars": {
1500 "Bool": true,
1501 "String": "hello",
1502 "Bytes": "AQID",
1503 "Int": -64,
1504 "Uint": 64,
1505 "Float": 3.14159
1506 },
1507 "StructMaps": {
1508 "MapBool": {
1509 "": true
1510 },
1511 "MapString": {
1512 "": "hello"
1513 },
1514 "MapBytes": {
1515 "": "AQID"
1516 },
1517 "MapInt": {
1518 "": -64
1519 },
1520 "MapUint": {
1521 "": 64
1522 },
1523 "MapFloat": {
1524 "": 3.14159
1525 }
1526 },
1527 "StructSlices": {
1528 "SliceBool": [
1529 true
1530 ],
1531 "SliceString": [
1532 "hello"
1533 ],
1534 "SliceBytes": [
1535 "AQID"
1536 ],
1537 "SliceInt": [
1538 -64
1539 ],
1540 "SliceUint": [
1541 64
1542 ],
1543 "SliceFloat": [
1544 3.14159
1545 ]
1546 },
1547 "Slice": [
1548 "fizz",
1549 "buzz"
1550 ],
1551 "Array": [
1552 "goodbye"
1553 ],
1554 "Pointer": {
1555 "Bool": "false",
1556 "String": "\"\"",
1557 "Bytes": "",
1558 "Int": "0",
1559 "Uint": "0",
1560 "Float": "0",
1561 "Map": {},
1562 "StructScalars": {
1563 "Bool": false,
1564 "String": "",
1565 "Bytes": "",
1566 "Int": 0,
1567 "Uint": 0,
1568 "Float": 0
1569 },
1570 "StructMaps": {
1571 "MapBool": {},
1572 "MapString": {},
1573 "MapBytes": {},
1574 "MapInt": {},
1575 "MapUint": {},
1576 "MapFloat": {}
1577 },
1578 "StructSlices": {
1579 "SliceBool": [],
1580 "SliceString": [],
1581 "SliceBytes": [],
1582 "SliceInt": [],
1583 "SliceUint": [],
1584 "SliceFloat": []
1585 },
1586 "Slice": [],
1587 "Array": [
1588 ""
1589 ],
1590 "Pointer": null,
1591 "Interface": null
1592 },
1593 "Interface": null
1594 }`,
1595 }, {
1596 name: jsontest.Name("Structs/OmitZero/Zero"),
1597 in: structOmitZeroAll{},
1598 want: `{}`,
1599 }, {
1600 name: jsontest.Name("Structs/OmitZeroOption/Zero"),
1601 opts: []Options{OmitZeroStructFields(true)},
1602 in: structAll{},
1603 want: `{}`,
1604 }, {
1605 name: jsontest.Name("Structs/OmitZero/NonZero"),
1606 opts: []Options{jsontext.Multiline(true)},
1607 in: structOmitZeroAll{
1608 Bool: true, // not omitted since true is non-zero
1609 String: " ", // not omitted since non-empty string is non-zero
1610 Bytes: []byte{}, // not omitted since allocated slice is non-zero
1611 Int: 1, // not omitted since 1 is non-zero
1612 Uint: 1, // not omitted since 1 is non-zero
1613 Float: math.SmallestNonzeroFloat64, // not omitted since still slightly above zero
1614 Map: map[string]string{}, // not omitted since allocated map is non-zero
1615 StructScalars: structScalars{unexported: true}, // not omitted since unexported is non-zero
1616 StructSlices: structSlices{Ignored: true}, // not omitted since Ignored is non-zero
1617 StructMaps: structMaps{MapBool: map[string]bool{}}, // not omitted since MapBool is non-zero
1618 Slice: []string{}, // not omitted since allocated slice is non-zero
1619 Array: [1]string{" "}, // not omitted since single array element is non-zero
1620 Pointer: new(structOmitZeroAll), // not omitted since pointer is non-zero (even if all fields of the struct value are zero)
1621 Interface: (*structOmitZeroAll)(nil), // not omitted since interface value is non-zero (even if interface value is a nil pointer)
1622 },
1623 want: `{
1624 "Bool": true,
1625 "String": " ",
1626 "Bytes": "",
1627 "Int": 1,
1628 "Uint": 1,
1629 "Float": 5e-324,
1630 "Map": {},
1631 "StructScalars": {
1632 "Bool": false,
1633 "String": "",
1634 "Bytes": "",
1635 "Int": 0,
1636 "Uint": 0,
1637 "Float": 0
1638 },
1639 "StructMaps": {
1640 "MapBool": {},
1641 "MapString": {},
1642 "MapBytes": {},
1643 "MapInt": {},
1644 "MapUint": {},
1645 "MapFloat": {}
1646 },
1647 "StructSlices": {
1648 "SliceBool": [],
1649 "SliceString": [],
1650 "SliceBytes": [],
1651 "SliceInt": [],
1652 "SliceUint": [],
1653 "SliceFloat": []
1654 },
1655 "Slice": [],
1656 "Array": [
1657 " "
1658 ],
1659 "Pointer": {},
1660 "Interface": null
1661 }`,
1662 }, {
1663 name: jsontest.Name("Structs/OmitZeroOption/NonZero"),
1664 opts: []Options{OmitZeroStructFields(true), jsontext.Multiline(true)},
1665 in: structAll{
1666 Bool: true,
1667 String: " ",
1668 Bytes: []byte{},
1669 Int: 1,
1670 Uint: 1,
1671 Float: math.SmallestNonzeroFloat64,
1672 Map: map[string]string{},
1673 StructScalars: structScalars{unexported: true},
1674 StructSlices: structSlices{Ignored: true},
1675 StructMaps: structMaps{MapBool: map[string]bool{}},
1676 Slice: []string{},
1677 Array: [1]string{" "},
1678 Pointer: new(structAll),
1679 Interface: (*structAll)(nil),
1680 },
1681 want: `{
1682 "Bool": true,
1683 "String": " ",
1684 "Bytes": "",
1685 "Int": 1,
1686 "Uint": 1,
1687 "Float": 5e-324,
1688 "Map": {},
1689 "StructScalars": {},
1690 "StructMaps": {
1691 "MapBool": {}
1692 },
1693 "StructSlices": {},
1694 "Slice": [],
1695 "Array": [
1696 " "
1697 ],
1698 "Pointer": {},
1699 "Interface": null
1700 }`,
1701 }, {
1702 name: jsontest.Name("Structs/OmitZeroMethod/Zero"),
1703 in: structOmitZeroMethodAll{},
1704 want: `{"ValueNeverZero":"","PointerNeverZero":""}`,
1705 }, {
1706 name: jsontest.Name("Structs/OmitZeroMethod/NonZero"),
1707 opts: []Options{jsontext.Multiline(true)},
1708 in: structOmitZeroMethodAll{
1709 ValueAlwaysZero: valueAlwaysZero("nonzero"),
1710 ValueNeverZero: valueNeverZero("nonzero"),
1711 PointerAlwaysZero: pointerAlwaysZero("nonzero"),
1712 PointerNeverZero: pointerNeverZero("nonzero"),
1713 PointerValueAlwaysZero: addr(valueAlwaysZero("nonzero")),
1714 PointerValueNeverZero: addr(valueNeverZero("nonzero")),
1715 PointerPointerAlwaysZero: addr(pointerAlwaysZero("nonzero")),
1716 PointerPointerNeverZero: addr(pointerNeverZero("nonzero")),
1717 PointerPointerValueAlwaysZero: addr(addr(valueAlwaysZero("nonzero"))), // marshaled since **valueAlwaysZero does not implement IsZero
1718 PointerPointerValueNeverZero: addr(addr(valueNeverZero("nonzero"))),
1719 PointerPointerPointerAlwaysZero: addr(addr(pointerAlwaysZero("nonzero"))), // marshaled since **pointerAlwaysZero does not implement IsZero
1720 PointerPointerPointerNeverZero: addr(addr(pointerNeverZero("nonzero"))),
1721 },
1722 want: `{
1723 "ValueNeverZero": "nonzero",
1724 "PointerNeverZero": "nonzero",
1725 "PointerValueNeverZero": "nonzero",
1726 "PointerPointerNeverZero": "nonzero",
1727 "PointerPointerValueAlwaysZero": "nonzero",
1728 "PointerPointerValueNeverZero": "nonzero",
1729 "PointerPointerPointerAlwaysZero": "nonzero",
1730 "PointerPointerPointerNeverZero": "nonzero"
1731 }`,
1732 }, {
1733 name: jsontest.Name("Structs/OmitZeroMethod/Interface/Zero"),
1734 opts: []Options{jsontext.Multiline(true)},
1735 in: structOmitZeroMethodInterfaceAll{},
1736 want: `{}`,
1737 }, {
1738 name: jsontest.Name("Structs/OmitZeroMethod/Interface/PartialZero"),
1739 opts: []Options{jsontext.Multiline(true)},
1740 in: structOmitZeroMethodInterfaceAll{
1741 ValueAlwaysZero: valueAlwaysZero(""),
1742 ValueNeverZero: valueNeverZero(""),
1743 PointerValueAlwaysZero: (*valueAlwaysZero)(nil),
1744 PointerValueNeverZero: (*valueNeverZero)(nil), // nil pointer, so method not called
1745 PointerPointerAlwaysZero: (*pointerAlwaysZero)(nil),
1746 PointerPointerNeverZero: (*pointerNeverZero)(nil), // nil pointer, so method not called
1747 },
1748 want: `{
1749 "ValueNeverZero": ""
1750 }`,
1751 }, {
1752 name: jsontest.Name("Structs/OmitZeroMethod/Interface/NonZero"),
1753 opts: []Options{jsontext.Multiline(true)},
1754 in: structOmitZeroMethodInterfaceAll{
1755 ValueAlwaysZero: valueAlwaysZero("nonzero"),
1756 ValueNeverZero: valueNeverZero("nonzero"),
1757 PointerValueAlwaysZero: addr(valueAlwaysZero("nonzero")),
1758 PointerValueNeverZero: addr(valueNeverZero("nonzero")),
1759 PointerPointerAlwaysZero: addr(pointerAlwaysZero("nonzero")),
1760 PointerPointerNeverZero: addr(pointerNeverZero("nonzero")),
1761 },
1762 want: `{
1763 "ValueNeverZero": "nonzero",
1764 "PointerValueNeverZero": "nonzero",
1765 "PointerPointerNeverZero": "nonzero"
1766 }`,
1767 }, {
1768 name: jsontest.Name("Structs/OmitEmpty/Zero"),
1769 opts: []Options{jsontext.Multiline(true)},
1770 in: structOmitEmptyAll{},
1771 want: `{
1772 "Bool": false,
1773 "StringNonEmpty": "value",
1774 "BytesNonEmpty": [
1775 "value"
1776 ],
1777 "Float": 0,
1778 "MapNonEmpty": {
1779 "key": "value"
1780 },
1781 "SliceNonEmpty": [
1782 "value"
1783 ]
1784 }`,
1785 }, {
1786 name: jsontest.Name("Structs/OmitEmpty/EmptyNonZero"),
1787 opts: []Options{jsontext.Multiline(true)},
1788 in: structOmitEmptyAll{
1789 String: string(""),
1790 StringEmpty: stringMarshalEmpty(""),
1791 StringNonEmpty: stringMarshalNonEmpty(""),
1792 PointerString: addr(string("")),
1793 PointerStringEmpty: addr(stringMarshalEmpty("")),
1794 PointerStringNonEmpty: addr(stringMarshalNonEmpty("")),
1795 Bytes: []byte(""),
1796 BytesEmpty: bytesMarshalEmpty([]byte("")),
1797 BytesNonEmpty: bytesMarshalNonEmpty([]byte("")),
1798 PointerBytes: addr([]byte("")),
1799 PointerBytesEmpty: addr(bytesMarshalEmpty([]byte(""))),
1800 PointerBytesNonEmpty: addr(bytesMarshalNonEmpty([]byte(""))),
1801 Map: map[string]string{},
1802 MapEmpty: mapMarshalEmpty{},
1803 MapNonEmpty: mapMarshalNonEmpty{},
1804 PointerMap: addr(map[string]string{}),
1805 PointerMapEmpty: addr(mapMarshalEmpty{}),
1806 PointerMapNonEmpty: addr(mapMarshalNonEmpty{}),
1807 Slice: []string{},
1808 SliceEmpty: sliceMarshalEmpty{},
1809 SliceNonEmpty: sliceMarshalNonEmpty{},
1810 PointerSlice: addr([]string{}),
1811 PointerSliceEmpty: addr(sliceMarshalEmpty{}),
1812 PointerSliceNonEmpty: addr(sliceMarshalNonEmpty{}),
1813 Pointer: &structOmitZeroEmptyAll{},
1814 Interface: []string{},
1815 },
1816 want: `{
1817 "Bool": false,
1818 "StringNonEmpty": "value",
1819 "PointerStringNonEmpty": "value",
1820 "BytesNonEmpty": [
1821 "value"
1822 ],
1823 "PointerBytesNonEmpty": [
1824 "value"
1825 ],
1826 "Float": 0,
1827 "MapNonEmpty": {
1828 "key": "value"
1829 },
1830 "PointerMapNonEmpty": {
1831 "key": "value"
1832 },
1833 "SliceNonEmpty": [
1834 "value"
1835 ],
1836 "PointerSliceNonEmpty": [
1837 "value"
1838 ]
1839 }`,
1840 }, {
1841 name: jsontest.Name("Structs/OmitEmpty/NonEmpty"),
1842 opts: []Options{jsontext.Multiline(true)},
1843 in: structOmitEmptyAll{
1844 Bool: true,
1845 PointerBool: addr(true),
1846 String: string("value"),
1847 StringEmpty: stringMarshalEmpty("value"),
1848 StringNonEmpty: stringMarshalNonEmpty("value"),
1849 PointerString: addr(string("value")),
1850 PointerStringEmpty: addr(stringMarshalEmpty("value")),
1851 PointerStringNonEmpty: addr(stringMarshalNonEmpty("value")),
1852 Bytes: []byte("value"),
1853 BytesEmpty: bytesMarshalEmpty([]byte("value")),
1854 BytesNonEmpty: bytesMarshalNonEmpty([]byte("value")),
1855 PointerBytes: addr([]byte("value")),
1856 PointerBytesEmpty: addr(bytesMarshalEmpty([]byte("value"))),
1857 PointerBytesNonEmpty: addr(bytesMarshalNonEmpty([]byte("value"))),
1858 Float: math.Copysign(0, -1),
1859 PointerFloat: addr(math.Copysign(0, -1)),
1860 Map: map[string]string{"": ""},
1861 MapEmpty: mapMarshalEmpty{"key": "value"},
1862 MapNonEmpty: mapMarshalNonEmpty{"key": "value"},
1863 PointerMap: addr(map[string]string{"": ""}),
1864 PointerMapEmpty: addr(mapMarshalEmpty{"key": "value"}),
1865 PointerMapNonEmpty: addr(mapMarshalNonEmpty{"key": "value"}),
1866 Slice: []string{""},
1867 SliceEmpty: sliceMarshalEmpty{"value"},
1868 SliceNonEmpty: sliceMarshalNonEmpty{"value"},
1869 PointerSlice: addr([]string{""}),
1870 PointerSliceEmpty: addr(sliceMarshalEmpty{"value"}),
1871 PointerSliceNonEmpty: addr(sliceMarshalNonEmpty{"value"}),
1872 Pointer: &structOmitZeroEmptyAll{Float: math.SmallestNonzeroFloat64},
1873 Interface: []string{""},
1874 },
1875 want: `{
1876 "Bool": true,
1877 "PointerBool": true,
1878 "String": "value",
1879 "StringNonEmpty": "value",
1880 "PointerString": "value",
1881 "PointerStringNonEmpty": "value",
1882 "Bytes": "dmFsdWU=",
1883 "BytesNonEmpty": [
1884 "value"
1885 ],
1886 "PointerBytes": "dmFsdWU=",
1887 "PointerBytesNonEmpty": [
1888 "value"
1889 ],
1890 "Float": -0,
1891 "PointerFloat": -0,
1892 "Map": {
1893 "": ""
1894 },
1895 "MapNonEmpty": {
1896 "key": "value"
1897 },
1898 "PointerMap": {
1899 "": ""
1900 },
1901 "PointerMapNonEmpty": {
1902 "key": "value"
1903 },
1904 "Slice": [
1905 ""
1906 ],
1907 "SliceNonEmpty": [
1908 "value"
1909 ],
1910 "PointerSlice": [
1911 ""
1912 ],
1913 "PointerSliceNonEmpty": [
1914 "value"
1915 ],
1916 "Pointer": {
1917 "Float": 5e-324
1918 },
1919 "Interface": [
1920 ""
1921 ]
1922 }`,
1923 }, {
1924 name: jsontest.Name("Structs/OmitEmpty/Legacy/Zero"),
1925 opts: []Options{jsonflags.OmitEmptyWithLegacySemantics | 1},
1926 in: structOmitEmptyAll{},
1927 want: `{}`,
1928 }, {
1929 name: jsontest.Name("Structs/OmitEmpty/Legacy/NonEmpty"),
1930 opts: []Options{jsontext.Multiline(true), jsonflags.OmitEmptyWithLegacySemantics | 1},
1931 in: structOmitEmptyAll{
1932 Bool: true,
1933 PointerBool: addr(true),
1934 String: string("value"),
1935 StringEmpty: stringMarshalEmpty("value"),
1936 StringNonEmpty: stringMarshalNonEmpty("value"),
1937 PointerString: addr(string("value")),
1938 PointerStringEmpty: addr(stringMarshalEmpty("value")),
1939 PointerStringNonEmpty: addr(stringMarshalNonEmpty("value")),
1940 Bytes: []byte("value"),
1941 BytesEmpty: bytesMarshalEmpty([]byte("value")),
1942 BytesNonEmpty: bytesMarshalNonEmpty([]byte("value")),
1943 PointerBytes: addr([]byte("value")),
1944 PointerBytesEmpty: addr(bytesMarshalEmpty([]byte("value"))),
1945 PointerBytesNonEmpty: addr(bytesMarshalNonEmpty([]byte("value"))),
1946 Float: math.Copysign(0, -1),
1947 PointerFloat: addr(math.Copysign(0, -1)),
1948 Map: map[string]string{"": ""},
1949 MapEmpty: mapMarshalEmpty{"key": "value"},
1950 MapNonEmpty: mapMarshalNonEmpty{"key": "value"},
1951 PointerMap: addr(map[string]string{"": ""}),
1952 PointerMapEmpty: addr(mapMarshalEmpty{"key": "value"}),
1953 PointerMapNonEmpty: addr(mapMarshalNonEmpty{"key": "value"}),
1954 Slice: []string{""},
1955 SliceEmpty: sliceMarshalEmpty{"value"},
1956 SliceNonEmpty: sliceMarshalNonEmpty{"value"},
1957 PointerSlice: addr([]string{""}),
1958 PointerSliceEmpty: addr(sliceMarshalEmpty{"value"}),
1959 PointerSliceNonEmpty: addr(sliceMarshalNonEmpty{"value"}),
1960 Pointer: &structOmitZeroEmptyAll{Float: math.Copysign(0, -1)},
1961 Interface: []string{""},
1962 },
1963 want: `{
1964 "Bool": true,
1965 "PointerBool": true,
1966 "String": "value",
1967 "StringEmpty": "",
1968 "StringNonEmpty": "value",
1969 "PointerString": "value",
1970 "PointerStringEmpty": "",
1971 "PointerStringNonEmpty": "value",
1972 "Bytes": "dmFsdWU=",
1973 "BytesEmpty": [],
1974 "BytesNonEmpty": [
1975 "value"
1976 ],
1977 "PointerBytes": "dmFsdWU=",
1978 "PointerBytesEmpty": [],
1979 "PointerBytesNonEmpty": [
1980 "value"
1981 ],
1982 "PointerFloat": -0,
1983 "Map": {
1984 "": ""
1985 },
1986 "MapEmpty": {},
1987 "MapNonEmpty": {
1988 "key": "value"
1989 },
1990 "PointerMap": {
1991 "": ""
1992 },
1993 "PointerMapEmpty": {},
1994 "PointerMapNonEmpty": {
1995 "key": "value"
1996 },
1997 "Slice": [
1998 ""
1999 ],
2000 "SliceEmpty": [],
2001 "SliceNonEmpty": [
2002 "value"
2003 ],
2004 "PointerSlice": [
2005 ""
2006 ],
2007 "PointerSliceEmpty": [],
2008 "PointerSliceNonEmpty": [
2009 "value"
2010 ],
2011 "Pointer": {},
2012 "Interface": [
2013 ""
2014 ]
2015 }`,
2016 }, {
2017 name: jsontest.Name("Structs/OmitEmpty/NonEmptyString"),
2018 in: struct {
2019 X string `json:",omitempty"`
2020 }{`"`},
2021 want: `{"X":"\""}`,
2022 }, {
2023 name: jsontest.Name("Structs/OmitZeroEmpty/Zero"),
2024 in: structOmitZeroEmptyAll{},
2025 want: `{}`,
2026 }, {
2027 name: jsontest.Name("Structs/OmitZeroEmpty/Empty"),
2028 in: structOmitZeroEmptyAll{
2029 Bytes: []byte{},
2030 Map: map[string]string{},
2031 Slice: []string{},
2032 Pointer: &structOmitZeroEmptyAll{},
2033 Interface: []string{},
2034 },
2035 want: `{}`,
2036 }, {
2037 name: jsontest.Name("Structs/OmitEmpty/PathologicalDepth"),
2038 in: func() any {
2039 type X struct {
2040 X *X `json:",omitempty"`
2041 }
2042 var make func(int) *X
2043 make = func(n int) *X {
2044 if n == 0 {
2045 return nil
2046 }
2047 return &X{make(n - 1)}
2048 }
2049 return make(100)
2050 }(),
2051 want: `{}`,
2052 useWriter: true,
2053 }, {
2054 name: jsontest.Name("Structs/OmitEmpty/PathologicalBreadth"),
2055 in: func() any {
2056 var fields []reflect.StructField
2057 for i := range 100 {
2058 fields = append(fields, reflect.StructField{
2059 Name: fmt.Sprintf("X%d", i),
2060 Type: T[stringMarshalEmpty](),
2061 Tag: `json:",omitempty"`,
2062 })
2063 }
2064 return reflect.New(reflect.StructOf(fields)).Interface()
2065 }(),
2066 want: `{}`,
2067 useWriter: true,
2068 }, {
2069 name: jsontest.Name("Structs/OmitEmpty/PathologicalTree"),
2070 in: func() any {
2071 type X struct {
2072 XL, XR *X `json:",omitempty"`
2073 }
2074 var make func(int) *X
2075 make = func(n int) *X {
2076 if n == 0 {
2077 return nil
2078 }
2079 return &X{make(n - 1), make(n - 1)}
2080 }
2081 return make(8)
2082 }(),
2083 want: `{}`,
2084 useWriter: true,
2085 }, {
2086 name: jsontest.Name("Structs/OmitZeroEmpty/NonEmpty"),
2087 in: structOmitZeroEmptyAll{
2088 Bytes: []byte("value"),
2089 Map: map[string]string{"": ""},
2090 Slice: []string{""},
2091 Pointer: &structOmitZeroEmptyAll{Bool: true},
2092 Interface: []string{""},
2093 },
2094 want: `{"Bytes":"dmFsdWU=","Map":{"":""},"Slice":[""],"Pointer":{"Bool":true},"Interface":[""]}`,
2095 }, {
2096 name: jsontest.Name("Structs/Format/Bytes"),
2097 opts: []Options{jsontext.Multiline(true)},
2098 in: structFormatBytes{
2099 Base16: []byte("\x01\x23\x45\x67\x89\xab\xcd\xef"),
2100 Base32: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
2101 Base32Hex: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
2102 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߿"),
2103 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߿"),
2104 Array: []byte{1, 2, 3, 4},
2105 },
2106 want: `{
2107 "Base16": "0123456789abcdef",
2108 "Base32": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
2109 "Base32Hex": "0123456789ABCDEFGHIJKLMNOPQRSTUV",
2110 "Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
2111 "Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
2112 "Array": [
2113 1,
2114 2,
2115 3,
2116 4
2117 ]
2118 }`}, {
2119 name: jsontest.Name("Structs/Format/ArrayBytes"),
2120 opts: []Options{jsontext.Multiline(true)},
2121 in: structFormatArrayBytes{
2122 Base16: [4]byte{1, 2, 3, 4},
2123 Base32: [4]byte{1, 2, 3, 4},
2124 Base32Hex: [4]byte{1, 2, 3, 4},
2125 Base64: [4]byte{1, 2, 3, 4},
2126 Base64URL: [4]byte{1, 2, 3, 4},
2127 Array: [4]byte{1, 2, 3, 4},
2128 Default: [4]byte{1, 2, 3, 4},
2129 },
2130 want: `{
2131 "Base16": "01020304",
2132 "Base32": "AEBAGBA=",
2133 "Base32Hex": "0410610=",
2134 "Base64": "AQIDBA==",
2135 "Base64URL": "AQIDBA==",
2136 "Array": [
2137 1,
2138 2,
2139 3,
2140 4
2141 ],
2142 "Default": "AQIDBA=="
2143 }`}, {
2144 name: jsontest.Name("Structs/Format/ArrayBytes/Legacy"),
2145 opts: []Options{jsontext.Multiline(true), jsonflags.FormatByteArrayAsArray | jsonflags.FormatBytesWithLegacySemantics | 1},
2146 in: structFormatArrayBytes{
2147 Base16: [4]byte{1, 2, 3, 4},
2148 Base32: [4]byte{1, 2, 3, 4},
2149 Base32Hex: [4]byte{1, 2, 3, 4},
2150 Base64: [4]byte{1, 2, 3, 4},
2151 Base64URL: [4]byte{1, 2, 3, 4},
2152 Array: [4]byte{1, 2, 3, 4},
2153 Default: [4]byte{1, 2, 3, 4},
2154 },
2155 want: `{
2156 "Base16": "01020304",
2157 "Base32": "AEBAGBA=",
2158 "Base32Hex": "0410610=",
2159 "Base64": "AQIDBA==",
2160 "Base64URL": "AQIDBA==",
2161 "Array": [
2162 1,
2163 2,
2164 3,
2165 4
2166 ],
2167 "Default": [
2168 1,
2169 2,
2170 3,
2171 4
2172 ]
2173 }`}, {
2174 name: jsontest.Name("Structs/Format/Bytes/Array"),
2175 opts: []Options{
2176 WithMarshalers(MarshalFunc(func(in byte) ([]byte, error) {
2177 if in > 3 {
2178 return []byte("true"), nil
2179 } else {
2180 return []byte("false"), nil
2181 }
2182 })),
2183 },
2184 in: struct {
2185 Array []byte `json:",format:array"`
2186 }{
2187 Array: []byte{1, 6, 2, 5, 3, 4},
2188 },
2189 want: `{"Array":[false,true,false,true,false,true]}`,
2190 }, {
2191 name: jsontest.Name("Structs/Format/Floats"),
2192 opts: []Options{jsontext.Multiline(true)},
2193 in: []structFormatFloats{
2194 {NonFinite: math.Pi, PointerNonFinite: addr(math.Pi)},
2195 {NonFinite: math.NaN(), PointerNonFinite: addr(math.NaN())},
2196 {NonFinite: math.Inf(-1), PointerNonFinite: addr(math.Inf(-1))},
2197 {NonFinite: math.Inf(+1), PointerNonFinite: addr(math.Inf(+1))},
2198 },
2199 want: `[
2200 {
2201 "NonFinite": 3.141592653589793,
2202 "PointerNonFinite": 3.141592653589793
2203 },
2204 {
2205 "NonFinite": "NaN",
2206 "PointerNonFinite": "NaN"
2207 },
2208 {
2209 "NonFinite": "-Infinity",
2210 "PointerNonFinite": "-Infinity"
2211 },
2212 {
2213 "NonFinite": "Infinity",
2214 "PointerNonFinite": "Infinity"
2215 }
2216 ]`,
2217 }, {
2218 name: jsontest.Name("Structs/Format/Maps"),
2219 opts: []Options{jsontext.Multiline(true)},
2220 in: []structFormatMaps{{
2221 EmitNull: map[string]string(nil), PointerEmitNull: addr(map[string]string(nil)),
2222 EmitEmpty: map[string]string(nil), PointerEmitEmpty: addr(map[string]string(nil)),
2223 EmitDefault: map[string]string(nil), PointerEmitDefault: addr(map[string]string(nil)),
2224 }, {
2225 EmitNull: map[string]string{}, PointerEmitNull: addr(map[string]string{}),
2226 EmitEmpty: map[string]string{}, PointerEmitEmpty: addr(map[string]string{}),
2227 EmitDefault: map[string]string{}, PointerEmitDefault: addr(map[string]string{}),
2228 }, {
2229 EmitNull: map[string]string{"k": "v"}, PointerEmitNull: addr(map[string]string{"k": "v"}),
2230 EmitEmpty: map[string]string{"k": "v"}, PointerEmitEmpty: addr(map[string]string{"k": "v"}),
2231 EmitDefault: map[string]string{"k": "v"}, PointerEmitDefault: addr(map[string]string{"k": "v"}),
2232 }},
2233 want: `[
2234 {
2235 "EmitNull": null,
2236 "PointerEmitNull": null,
2237 "EmitEmpty": {},
2238 "PointerEmitEmpty": {},
2239 "EmitDefault": {},
2240 "PointerEmitDefault": {}
2241 },
2242 {
2243 "EmitNull": {},
2244 "PointerEmitNull": {},
2245 "EmitEmpty": {},
2246 "PointerEmitEmpty": {},
2247 "EmitDefault": {},
2248 "PointerEmitDefault": {}
2249 },
2250 {
2251 "EmitNull": {
2252 "k": "v"
2253 },
2254 "PointerEmitNull": {
2255 "k": "v"
2256 },
2257 "EmitEmpty": {
2258 "k": "v"
2259 },
2260 "PointerEmitEmpty": {
2261 "k": "v"
2262 },
2263 "EmitDefault": {
2264 "k": "v"
2265 },
2266 "PointerEmitDefault": {
2267 "k": "v"
2268 }
2269 }
2270 ]`,
2271 }, {
2272 name: jsontest.Name("Structs/Format/Maps/FormatNilMapAsNull"),
2273 opts: []Options{
2274 FormatNilMapAsNull(true),
2275 jsontext.Multiline(true),
2276 },
2277 in: []structFormatMaps{{
2278 EmitNull: map[string]string(nil), PointerEmitNull: addr(map[string]string(nil)),
2279 EmitEmpty: map[string]string(nil), PointerEmitEmpty: addr(map[string]string(nil)),
2280 EmitDefault: map[string]string(nil), PointerEmitDefault: addr(map[string]string(nil)),
2281 }, {
2282 EmitNull: map[string]string{}, PointerEmitNull: addr(map[string]string{}),
2283 EmitEmpty: map[string]string{}, PointerEmitEmpty: addr(map[string]string{}),
2284 EmitDefault: map[string]string{}, PointerEmitDefault: addr(map[string]string{}),
2285 }, {
2286 EmitNull: map[string]string{"k": "v"}, PointerEmitNull: addr(map[string]string{"k": "v"}),
2287 EmitEmpty: map[string]string{"k": "v"}, PointerEmitEmpty: addr(map[string]string{"k": "v"}),
2288 EmitDefault: map[string]string{"k": "v"}, PointerEmitDefault: addr(map[string]string{"k": "v"}),
2289 }},
2290 want: `[
2291 {
2292 "EmitNull": null,
2293 "PointerEmitNull": null,
2294 "EmitEmpty": {},
2295 "PointerEmitEmpty": {},
2296 "EmitDefault": null,
2297 "PointerEmitDefault": null
2298 },
2299 {
2300 "EmitNull": {},
2301 "PointerEmitNull": {},
2302 "EmitEmpty": {},
2303 "PointerEmitEmpty": {},
2304 "EmitDefault": {},
2305 "PointerEmitDefault": {}
2306 },
2307 {
2308 "EmitNull": {
2309 "k": "v"
2310 },
2311 "PointerEmitNull": {
2312 "k": "v"
2313 },
2314 "EmitEmpty": {
2315 "k": "v"
2316 },
2317 "PointerEmitEmpty": {
2318 "k": "v"
2319 },
2320 "EmitDefault": {
2321 "k": "v"
2322 },
2323 "PointerEmitDefault": {
2324 "k": "v"
2325 }
2326 }
2327 ]`,
2328 }, {
2329 name: jsontest.Name("Structs/Format/Slices"),
2330 opts: []Options{jsontext.Multiline(true)},
2331 in: []structFormatSlices{{
2332 EmitNull: []string(nil), PointerEmitNull: addr([]string(nil)),
2333 EmitEmpty: []string(nil), PointerEmitEmpty: addr([]string(nil)),
2334 EmitDefault: []string(nil), PointerEmitDefault: addr([]string(nil)),
2335 }, {
2336 EmitNull: []string{}, PointerEmitNull: addr([]string{}),
2337 EmitEmpty: []string{}, PointerEmitEmpty: addr([]string{}),
2338 EmitDefault: []string{}, PointerEmitDefault: addr([]string{}),
2339 }, {
2340 EmitNull: []string{"v"}, PointerEmitNull: addr([]string{"v"}),
2341 EmitEmpty: []string{"v"}, PointerEmitEmpty: addr([]string{"v"}),
2342 EmitDefault: []string{"v"}, PointerEmitDefault: addr([]string{"v"}),
2343 }},
2344 want: `[
2345 {
2346 "EmitNull": null,
2347 "PointerEmitNull": null,
2348 "EmitEmpty": [],
2349 "PointerEmitEmpty": [],
2350 "EmitDefault": [],
2351 "PointerEmitDefault": []
2352 },
2353 {
2354 "EmitNull": [],
2355 "PointerEmitNull": [],
2356 "EmitEmpty": [],
2357 "PointerEmitEmpty": [],
2358 "EmitDefault": [],
2359 "PointerEmitDefault": []
2360 },
2361 {
2362 "EmitNull": [
2363 "v"
2364 ],
2365 "PointerEmitNull": [
2366 "v"
2367 ],
2368 "EmitEmpty": [
2369 "v"
2370 ],
2371 "PointerEmitEmpty": [
2372 "v"
2373 ],
2374 "EmitDefault": [
2375 "v"
2376 ],
2377 "PointerEmitDefault": [
2378 "v"
2379 ]
2380 }
2381 ]`,
2382 }, {
2383 name: jsontest.Name("Structs/Format/Invalid/Bool"),
2384 in: structFormatInvalid{Bool: true},
2385 want: `{"Bool"`,
2386 wantErr: EM(errInvalidFormatFlag).withPos(`{"Bool":`, "/Bool").withType(0, boolType),
2387 }, {
2388 name: jsontest.Name("Structs/Format/Invalid/String"),
2389 in: structFormatInvalid{String: "string"},
2390 want: `{"String"`,
2391 wantErr: EM(errInvalidFormatFlag).withPos(`{"String":`, "/String").withType(0, stringType),
2392 }, {
2393 name: jsontest.Name("Structs/Format/Invalid/Bytes"),
2394 in: structFormatInvalid{Bytes: []byte("bytes")},
2395 want: `{"Bytes"`,
2396 wantErr: EM(errInvalidFormatFlag).withPos(`{"Bytes":`, "/Bytes").withType(0, bytesType),
2397 }, {
2398 name: jsontest.Name("Structs/Format/Invalid/Int"),
2399 in: structFormatInvalid{Int: 1},
2400 want: `{"Int"`,
2401 wantErr: EM(errInvalidFormatFlag).withPos(`{"Int":`, "/Int").withType(0, T[int64]()),
2402 }, {
2403 name: jsontest.Name("Structs/Format/Invalid/Uint"),
2404 in: structFormatInvalid{Uint: 1},
2405 want: `{"Uint"`,
2406 wantErr: EM(errInvalidFormatFlag).withPos(`{"Uint":`, "/Uint").withType(0, T[uint64]()),
2407 }, {
2408 name: jsontest.Name("Structs/Format/Invalid/Float"),
2409 in: structFormatInvalid{Float: 1},
2410 want: `{"Float"`,
2411 wantErr: EM(errInvalidFormatFlag).withPos(`{"Float":`, "/Float").withType(0, T[float64]()),
2412 }, {
2413 name: jsontest.Name("Structs/Format/Invalid/Map"),
2414 in: structFormatInvalid{Map: map[string]string{}},
2415 want: `{"Map"`,
2416 wantErr: EM(errInvalidFormatFlag).withPos(`{"Map":`, "/Map").withType(0, T[map[string]string]()),
2417 }, {
2418 name: jsontest.Name("Structs/Format/Invalid/Struct"),
2419 in: structFormatInvalid{Struct: structAll{Bool: true}},
2420 want: `{"Struct"`,
2421 wantErr: EM(errInvalidFormatFlag).withPos(`{"Struct":`, "/Struct").withType(0, T[structAll]()),
2422 }, {
2423 name: jsontest.Name("Structs/Format/Invalid/Slice"),
2424 in: structFormatInvalid{Slice: []string{}},
2425 want: `{"Slice"`,
2426 wantErr: EM(errInvalidFormatFlag).withPos(`{"Slice":`, "/Slice").withType(0, T[[]string]()),
2427 }, {
2428 name: jsontest.Name("Structs/Format/Invalid/Array"),
2429 in: structFormatInvalid{Array: [1]string{"string"}},
2430 want: `{"Array"`,
2431 wantErr: EM(errInvalidFormatFlag).withPos(`{"Array":`, "/Array").withType(0, T[[1]string]()),
2432 }, {
2433 name: jsontest.Name("Structs/Format/Invalid/Interface"),
2434 in: structFormatInvalid{Interface: "anything"},
2435 want: `{"Interface"`,
2436 wantErr: EM(errInvalidFormatFlag).withPos(`{"Interface":`, "/Interface").withType(0, T[any]()),
2437 }, {
2438 name: jsontest.Name("Structs/Inline/Zero"),
2439 in: structInlined{},
2440 want: `{"D":""}`,
2441 }, {
2442 name: jsontest.Name("Structs/Inline/Alloc"),
2443 in: structInlined{
2444 X: structInlinedL1{
2445 X: &structInlinedL2{},
2446 StructEmbed1: StructEmbed1{},
2447 },
2448 StructEmbed2: &StructEmbed2{},
2449 },
2450 want: `{"A":"","B":"","D":"","E":"","F":"","G":""}`,
2451 }, {
2452 name: jsontest.Name("Structs/Inline/NonZero"),
2453 in: structInlined{
2454 X: structInlinedL1{
2455 X: &structInlinedL2{A: "A1", B: "B1", C: "C1"},
2456 StructEmbed1: StructEmbed1{C: "C2", D: "D2", E: "E2"},
2457 },
2458 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
2459 },
2460 want: `{"A":"A1","B":"B1","D":"D2","E":"E3","F":"F3","G":"G3"}`,
2461 }, {
2462 name: jsontest.Name("Structs/Inline/DualCycle"),
2463 in: cyclicA{
2464 B1: cyclicB{F: 1}, // B1.F ignored since it conflicts with B2.F
2465 B2: cyclicB{F: 2}, // B2.F ignored since it conflicts with B1.F
2466 },
2467 want: `{}`,
2468 }, {
2469 name: jsontest.Name("Structs/InlinedFallback/TextValue/Nil"),
2470 in: structInlineTextValue{X: jsontext.Value(nil)},
2471 want: `{}`,
2472 }, {
2473 name: jsontest.Name("Structs/InlinedFallback/TextValue/Empty"),
2474 in: structInlineTextValue{X: jsontext.Value("")},
2475 want: `{}`,
2476 }, {
2477 name: jsontest.Name("Structs/InlinedFallback/TextValue/NonEmptyN1"),
2478 in: structInlineTextValue{X: jsontext.Value(` { "fizz" : "buzz" } `)},
2479 want: `{"fizz":"buzz"}`,
2480 }, {
2481 name: jsontest.Name("Structs/InlinedFallback/TextValue/NonEmptyN2"),
2482 in: structInlineTextValue{X: jsontext.Value(` { "fizz" : "buzz" , "foo" : "bar" } `)},
2483 want: `{"fizz":"buzz","foo":"bar"}`,
2484 }, {
2485 name: jsontest.Name("Structs/InlinedFallback/TextValue/NonEmptyWithOthers"),
2486 in: structInlineTextValue{
2487 A: 1,
2488 X: jsontext.Value(` { "fizz" : "buzz" , "foo" : "bar" } `),
2489 B: 2,
2490 },
2491 // NOTE: Inlined fallback fields are always serialized last.
2492 want: `{"A":1,"B":2,"fizz":"buzz","foo":"bar"}`,
2493 }, {
2494 name: jsontest.Name("Structs/InlinedFallback/TextValue/RejectDuplicateNames"),
2495 opts: []Options{jsontext.AllowDuplicateNames(false)},
2496 in: structInlineTextValue{X: jsontext.Value(` { "fizz" : "buzz" , "fizz" : "buzz" } `)},
2497 want: `{"fizz":"buzz"`,
2498 wantErr: newDuplicateNameError("/fizz", nil, len64(`{"fizz":"buzz"`)),
2499 }, {
2500 name: jsontest.Name("Structs/InlinedFallback/TextValue/AllowDuplicateNames"),
2501 opts: []Options{jsontext.AllowDuplicateNames(true)},
2502 in: structInlineTextValue{X: jsontext.Value(` { "fizz" : "buzz" , "fizz" : "buzz" } `)},
2503 want: `{"fizz":"buzz","fizz":"buzz"}`,
2504 }, {
2505 name: jsontest.Name("Structs/InlinedFallback/TextValue/RejectInvalidUTF8"),
2506 opts: []Options{jsontext.AllowInvalidUTF8(false)},
2507 in: structInlineTextValue{X: jsontext.Value(`{"` + "\xde\xad\xbe\xef" + `":"value"}`)},
2508 want: `{`,
2509 wantErr: newInvalidUTF8Error(len64(`{"`+"\xde\xad"), ""),
2510 }, {
2511 name: jsontest.Name("Structs/InlinedFallback/TextValue/AllowInvalidUTF8"),
2512 opts: []Options{jsontext.AllowInvalidUTF8(true)},
2513 in: structInlineTextValue{X: jsontext.Value(`{"` + "\xde\xad\xbe\xef" + `":"value"}`)},
2514 want: `{"ޭ��":"value"}`,
2515 }, {
2516 name: jsontest.Name("Structs/InlinedFallback/TextValue/InvalidWhitespace"),
2517 in: structInlineTextValue{X: jsontext.Value("\n\r\t ")},
2518 want: `{`,
2519 wantErr: EM(io.ErrUnexpectedEOF).withPos(`{`, "").withType(0, T[jsontext.Value]()),
2520 }, {
2521 name: jsontest.Name("Structs/InlinedFallback/TextValue/InvalidObject"),
2522 in: structInlineTextValue{X: jsontext.Value(` true `)},
2523 want: `{`,
2524 wantErr: EM(errRawInlinedNotObject).withPos(`{`, "").withType(0, T[jsontext.Value]()),
2525 }, {
2526 name: jsontest.Name("Structs/InlinedFallback/TextValue/InvalidObjectName"),
2527 in: structInlineTextValue{X: jsontext.Value(` { true : false } `)},
2528 want: `{`,
2529 wantErr: EM(newNonStringNameError(len64(" { "), "")).withPos(`{`, "").withType(0, T[jsontext.Value]()),
2530 }, {
2531 name: jsontest.Name("Structs/InlinedFallback/TextValue/InvalidEndObject"),
2532 in: structInlineTextValue{X: jsontext.Value(` { "name" : false , } `)},
2533 want: `{"name":false`,
2534 wantErr: EM(newInvalidCharacterError(",", "at start of value", len64(` { "name" : false `), "")).withPos(`{"name":false,`, "").withType(0, T[jsontext.Value]()),
2535 }, {
2536 name: jsontest.Name("Structs/InlinedFallback/TextValue/InvalidDualObject"),
2537 in: structInlineTextValue{X: jsontext.Value(`{}{}`)},
2538 want: `{`,
2539 wantErr: EM(newInvalidCharacterError("{", "after top-level value", len64(`{}`), "")).withPos(`{`, "").withType(0, T[jsontext.Value]()),
2540 }, {
2541 name: jsontest.Name("Structs/InlinedFallback/TextValue/Nested/Nil"),
2542 in: structInlinePointerInlineTextValue{},
2543 want: `{}`,
2544 }, {
2545 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Nil"),
2546 in: structInlinePointerTextValue{},
2547 want: `{}`,
2548 }, {
2549 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/NonEmpty"),
2550 in: structInlinePointerTextValue{X: addr(jsontext.Value(` { "fizz" : "buzz" } `))},
2551 want: `{"fizz":"buzz"}`,
2552 }, {
2553 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Nested/Nil"),
2554 in: structInlineInlinePointerTextValue{},
2555 want: `{}`,
2556 }, {
2557 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Nil"),
2558 in: structInlineMapStringAny{X: nil},
2559 want: `{}`,
2560 }, {
2561 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Empty"),
2562 in: structInlineMapStringAny{X: make(jsonObject)},
2563 want: `{}`,
2564 }, {
2565 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/NonEmptyN1"),
2566 in: structInlineMapStringAny{X: jsonObject{"fizz": nil}},
2567 want: `{"fizz":null}`,
2568 }, {
2569 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/NonEmptyN2"),
2570 in: structInlineMapStringAny{X: jsonObject{"fizz": time.Time{}, "buzz": math.Pi}},
2571 want: `{"buzz":3.141592653589793,"fizz":"0001-01-01T00:00:00Z"}`,
2572 canonicalize: true,
2573 }, {
2574 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/NonEmptyWithOthers"),
2575 in: structInlineMapStringAny{
2576 A: 1,
2577 X: jsonObject{"fizz": nil},
2578 B: 2,
2579 },
2580 // NOTE: Inlined fallback fields are always serialized last.
2581 want: `{"A":1,"B":2,"fizz":null}`,
2582 }, {
2583 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/RejectInvalidUTF8"),
2584 opts: []Options{jsontext.AllowInvalidUTF8(false)},
2585 in: structInlineMapStringAny{X: jsonObject{"\xde\xad\xbe\xef": nil}},
2586 want: `{`,
2587 wantErr: EM(jsonwire.ErrInvalidUTF8).withPos(`{`, "").withType(0, stringType),
2588 }, {
2589 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/AllowInvalidUTF8"),
2590 opts: []Options{jsontext.AllowInvalidUTF8(true)},
2591 in: structInlineMapStringAny{X: jsonObject{"\xde\xad\xbe\xef": nil}},
2592 want: `{"ޭ��":null}`,
2593 }, {
2594 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/InvalidValue"),
2595 opts: []Options{jsontext.AllowInvalidUTF8(true)},
2596 in: structInlineMapStringAny{X: jsonObject{"name": make(chan string)}},
2597 want: `{"name"`,
2598 wantErr: EM(nil).withPos(`{"name":`, "/name").withType(0, T[chan string]()),
2599 }, {
2600 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Nested/Nil"),
2601 in: structInlinePointerInlineMapStringAny{},
2602 want: `{}`,
2603 }, {
2604 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MarshalFunc"),
2605 opts: []Options{
2606 WithMarshalers(MarshalFunc(func(v float64) ([]byte, error) {
2607 return []byte(fmt.Sprintf(`"%v"`, v)), nil
2608 })),
2609 },
2610 in: structInlineMapStringAny{X: jsonObject{"fizz": 3.14159}},
2611 want: `{"fizz":"3.14159"}`,
2612 }, {
2613 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Nil"),
2614 in: structInlinePointerMapStringAny{X: nil},
2615 want: `{}`,
2616 }, {
2617 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/NonEmpty"),
2618 in: structInlinePointerMapStringAny{X: addr(jsonObject{"name": "value"})},
2619 want: `{"name":"value"}`,
2620 }, {
2621 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Nested/Nil"),
2622 in: structInlineInlinePointerMapStringAny{},
2623 want: `{}`,
2624 }, {
2625 name: jsontest.Name("Structs/InlinedFallback/MapStringInt"),
2626 in: structInlineMapStringInt{
2627 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2628 },
2629 want: `{"one":1,"two":2,"zero":0}`,
2630 canonicalize: true,
2631 }, {
2632 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/Deterministic"),
2633 opts: []Options{Deterministic(true)},
2634 in: structInlineMapStringInt{
2635 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2636 },
2637 want: `{"one":1,"two":2,"zero":0}`,
2638 }, {
2639 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
2640 opts: []Options{Deterministic(true), jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(false)},
2641 in: structInlineMapStringInt{
2642 X: map[string]int{"\xff": 0, "\xfe": 1},
2643 },
2644 want: `{"�":1`,
2645 wantErr: newDuplicateNameError("", []byte(`"�"`), len64(`{"�":1`)),
2646 }, {
2647 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
2648 opts: []Options{Deterministic(true), jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(true)},
2649 in: structInlineMapStringInt{
2650 X: map[string]int{"\xff": 0, "\xfe": 1},
2651 },
2652 want: `{"�":1,"�":0}`,
2653 }, {
2654 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/StringifiedNumbers"),
2655 opts: []Options{StringifyNumbers(true)},
2656 in: structInlineMapStringInt{
2657 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2658 },
2659 want: `{"one":"1","two":"2","zero":"0"}`,
2660 canonicalize: true,
2661 }, {
2662 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/MarshalFunc"),
2663 opts: []Options{
2664 WithMarshalers(JoinMarshalers(
2665 // Marshalers do not affect the string key of inlined maps.
2666 MarshalFunc(func(v string) ([]byte, error) {
2667 return []byte(fmt.Sprintf(`"%q"`, strings.ToUpper(v))), nil
2668 }),
2669 MarshalFunc(func(v int) ([]byte, error) {
2670 return []byte(fmt.Sprintf(`"%v"`, v)), nil
2671 }),
2672 )),
2673 },
2674 in: structInlineMapStringInt{
2675 X: map[string]int{"zero": 0, "one": 1, "two": 2},
2676 },
2677 want: `{"one":"1","two":"2","zero":"0"}`,
2678 canonicalize: true,
2679 }, {
2680 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt"),
2681 in: structInlineMapNamedStringInt{
2682 X: map[namedString]int{"zero": 0, "one": 1, "two": 2},
2683 },
2684 want: `{"one":1,"two":2,"zero":0}`,
2685 canonicalize: true,
2686 }, {
2687 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt/Deterministic"),
2688 opts: []Options{Deterministic(true)},
2689 in: structInlineMapNamedStringInt{
2690 X: map[namedString]int{"zero": 0, "one": 1, "two": 2},
2691 },
2692 want: `{"one":1,"two":2,"zero":0}`,
2693 }, {
2694 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/Nil"),
2695 in: structInlineMapNamedStringAny{X: nil},
2696 want: `{}`,
2697 }, {
2698 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/Empty"),
2699 in: structInlineMapNamedStringAny{X: make(map[namedString]any)},
2700 want: `{}`,
2701 }, {
2702 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/NonEmptyN1"),
2703 in: structInlineMapNamedStringAny{X: map[namedString]any{"fizz": nil}},
2704 want: `{"fizz":null}`,
2705 }, {
2706 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/NonEmptyN2"),
2707 in: structInlineMapNamedStringAny{X: map[namedString]any{"fizz": time.Time{}, "buzz": math.Pi}},
2708 want: `{"buzz":3.141592653589793,"fizz":"0001-01-01T00:00:00Z"}`,
2709 canonicalize: true,
2710 }, {
2711 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/NonEmptyWithOthers"),
2712 in: structInlineMapNamedStringAny{
2713 A: 1,
2714 X: map[namedString]any{"fizz": nil},
2715 B: 2,
2716 },
2717 // NOTE: Inlined fallback fields are always serialized last.
2718 want: `{"A":1,"B":2,"fizz":null}`,
2719 }, {
2720 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/RejectInvalidUTF8"),
2721 opts: []Options{jsontext.AllowInvalidUTF8(false)},
2722 in: structInlineMapNamedStringAny{X: map[namedString]any{"\xde\xad\xbe\xef": nil}},
2723 want: `{`,
2724 wantErr: EM(jsonwire.ErrInvalidUTF8).withPos(`{`, "").withType(0, T[namedString]()),
2725 }, {
2726 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/AllowInvalidUTF8"),
2727 opts: []Options{jsontext.AllowInvalidUTF8(true)},
2728 in: structInlineMapNamedStringAny{X: map[namedString]any{"\xde\xad\xbe\xef": nil}},
2729 want: `{"ޭ��":null}`,
2730 }, {
2731 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/InvalidValue"),
2732 opts: []Options{jsontext.AllowInvalidUTF8(true)},
2733 in: structInlineMapNamedStringAny{X: map[namedString]any{"name": make(chan string)}},
2734 want: `{"name"`,
2735 wantErr: EM(nil).withPos(`{"name":`, "/name").withType(0, T[chan string]()),
2736 }, {
2737 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MarshalFunc"),
2738 opts: []Options{
2739 WithMarshalers(MarshalFunc(func(v float64) ([]byte, error) {
2740 return []byte(fmt.Sprintf(`"%v"`, v)), nil
2741 })),
2742 },
2743 in: structInlineMapNamedStringAny{X: map[namedString]any{"fizz": 3.14159}},
2744 want: `{"fizz":"3.14159"}`,
2745 }, {
2746 name: jsontest.Name("Structs/InlinedFallback/DiscardUnknownMembers"),
2747 opts: []Options{DiscardUnknownMembers(true)},
2748 in: structInlineTextValue{
2749 A: 1,
2750 X: jsontext.Value(` { "fizz" : "buzz" } `),
2751 B: 2,
2752 },
2753 // NOTE: DiscardUnknownMembers has no effect since this is "inline".
2754 want: `{"A":1,"B":2,"fizz":"buzz"}`,
2755 }, {
2756 name: jsontest.Name("Structs/UnknownFallback/DiscardUnknownMembers"),
2757 opts: []Options{DiscardUnknownMembers(true)},
2758 in: structUnknownTextValue{
2759 A: 1,
2760 X: jsontext.Value(` { "fizz" : "buzz" } `),
2761 B: 2,
2762 },
2763 want: `{"A":1,"B":2}`,
2764 }, {
2765 name: jsontest.Name("Structs/UnknownFallback"),
2766 in: structUnknownTextValue{
2767 A: 1,
2768 X: jsontext.Value(` { "fizz" : "buzz" } `),
2769 B: 2,
2770 },
2771 want: `{"A":1,"B":2,"fizz":"buzz"}`,
2772 }, {
2773 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/Other"),
2774 in: structNoCaseInlineTextValue{
2775 X: jsontext.Value(`{"dupe":"","dupe":""}`),
2776 },
2777 want: `{"dupe":""`,
2778 wantErr: newDuplicateNameError("", []byte(`"dupe"`), len64(`{"dupe":""`)),
2779 }, {
2780 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/Other/AllowDuplicateNames"),
2781 opts: []Options{jsontext.AllowDuplicateNames(true)},
2782 in: structNoCaseInlineTextValue{
2783 X: jsontext.Value(`{"dupe": "", "dupe": ""}`),
2784 },
2785 want: `{"dupe":"","dupe":""}`,
2786 }, {
2787 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/ExactDifferent"),
2788 in: structNoCaseInlineTextValue{
2789 X: jsontext.Value(`{"Aaa": "", "AaA": "", "AAa": "", "AAA": ""}`),
2790 },
2791 want: `{"Aaa":"","AaA":"","AAa":"","AAA":""}`,
2792 }, {
2793 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/ExactConflict"),
2794 in: structNoCaseInlineTextValue{
2795 X: jsontext.Value(`{"Aaa": "", "Aaa": ""}`),
2796 },
2797 want: `{"Aaa":""`,
2798 wantErr: newDuplicateNameError("", []byte(`"Aaa"`), len64(`{"Aaa":""`)),
2799 }, {
2800 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/ExactConflict/AllowDuplicateNames"),
2801 opts: []Options{jsontext.AllowDuplicateNames(true)},
2802 in: structNoCaseInlineTextValue{
2803 X: jsontext.Value(`{"Aaa": "", "Aaa": ""}`),
2804 },
2805 want: `{"Aaa":"","Aaa":""}`,
2806 }, {
2807 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/NoCaseConflict"),
2808 in: structNoCaseInlineTextValue{
2809 X: jsontext.Value(`{"Aaa": "", "AaA": "", "aaa": ""}`),
2810 },
2811 want: `{"Aaa":"","AaA":""`,
2812 wantErr: newDuplicateNameError("", []byte(`"aaa"`), len64(`{"Aaa":"","AaA":""`)),
2813 }, {
2814 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/NoCaseConflict/AllowDuplicateNames"),
2815 opts: []Options{jsontext.AllowDuplicateNames(true)},
2816 in: structNoCaseInlineTextValue{
2817 X: jsontext.Value(`{"Aaa": "", "AaA": "", "aaa": ""}`),
2818 },
2819 want: `{"Aaa":"","AaA":"","aaa":""}`,
2820 }, {
2821 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/ExactDifferentWithField"),
2822 in: structNoCaseInlineTextValue{
2823 AAA: "x",
2824 AaA: "x",
2825 X: jsontext.Value(`{"Aaa": ""}`),
2826 },
2827 want: `{"AAA":"x","AaA":"x","Aaa":""}`,
2828 }, {
2829 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/ExactConflictWithField"),
2830 in: structNoCaseInlineTextValue{
2831 AAA: "x",
2832 AaA: "x",
2833 X: jsontext.Value(`{"AAA": ""}`),
2834 },
2835 want: `{"AAA":"x","AaA":"x"`,
2836 wantErr: newDuplicateNameError("", []byte(`"AAA"`), len64(`{"AAA":"x","AaA":"x"`)),
2837 }, {
2838 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineTextValue/NoCaseConflictWithField"),
2839 in: structNoCaseInlineTextValue{
2840 AAA: "x",
2841 AaA: "x",
2842 X: jsontext.Value(`{"aaa": ""}`),
2843 },
2844 want: `{"AAA":"x","AaA":"x"`,
2845 wantErr: newDuplicateNameError("", []byte(`"aaa"`), len64(`{"AAA":"x","AaA":"x"`)),
2846 }, {
2847 name: jsontest.Name("Structs/DuplicateName/MatchCaseInsensitiveDelimiter"),
2848 in: structNoCaseInlineTextValue{
2849 AaA: "x",
2850 X: jsontext.Value(`{"aa_a": ""}`),
2851 },
2852 want: `{"AaA":"x"`,
2853 wantErr: newDuplicateNameError("", []byte(`"aa_a"`), len64(`{"AaA":"x"`)),
2854 }, {
2855 name: jsontest.Name("Structs/DuplicateName/MatchCaseSensitiveDelimiter"),
2856 opts: []Options{jsonflags.MatchCaseSensitiveDelimiter | 1},
2857 in: structNoCaseInlineTextValue{
2858 AaA: "x",
2859 X: jsontext.Value(`{"aa_a": ""}`),
2860 },
2861 want: `{"AaA":"x","aa_a":""}`,
2862 }, {
2863 name: jsontest.Name("Structs/DuplicateName/MatchCaseInsensitiveNames+MatchCaseSensitiveDelimiter"),
2864 opts: []Options{MatchCaseInsensitiveNames(true), jsonflags.MatchCaseSensitiveDelimiter | 1},
2865 in: structNoCaseInlineTextValue{
2866 AaA: "x",
2867 X: jsontext.Value(`{"aa_a": ""}`),
2868 },
2869 want: `{"AaA":"x","aa_a":""}`,
2870 }, {
2871 name: jsontest.Name("Structs/DuplicateName/MatchCaseInsensitiveNames+MatchCaseSensitiveDelimiter"),
2872 opts: []Options{MatchCaseInsensitiveNames(true), jsonflags.MatchCaseSensitiveDelimiter | 1},
2873 in: structNoCaseInlineTextValue{
2874 AA_b: "x",
2875 X: jsontext.Value(`{"aa_b": ""}`),
2876 },
2877 want: `{"AA_b":"x"`,
2878 wantErr: newDuplicateNameError("", []byte(`"aa_b"`), len64(`{"AA_b":"x"`)),
2879 }, {
2880 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactDifferent"),
2881 in: structNoCaseInlineMapStringAny{
2882 X: jsonObject{"Aaa": "", "AaA": "", "AAa": "", "AAA": ""},
2883 },
2884 want: `{"AAA":"","AAa":"","AaA":"","Aaa":""}`,
2885 canonicalize: true,
2886 }, {
2887 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactDifferentWithField"),
2888 in: structNoCaseInlineMapStringAny{
2889 AAA: "x",
2890 AaA: "x",
2891 X: jsonObject{"Aaa": ""},
2892 },
2893 want: `{"AAA":"x","AaA":"x","Aaa":""}`,
2894 }, {
2895 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineMapStringAny/ExactConflictWithField"),
2896 in: structNoCaseInlineMapStringAny{
2897 AAA: "x",
2898 AaA: "x",
2899 X: jsonObject{"AAA": ""},
2900 },
2901 want: `{"AAA":"x","AaA":"x"`,
2902 wantErr: newDuplicateNameError("", []byte(`"AAA"`), len64(`{"AAA":"x","AaA":"x"`)),
2903 }, {
2904 name: jsontest.Name("Structs/DuplicateName/NoCaseInlineMapStringAny/NoCaseConflictWithField"),
2905 in: structNoCaseInlineMapStringAny{
2906 AAA: "x",
2907 AaA: "x",
2908 X: jsonObject{"aaa": ""},
2909 },
2910 want: `{"AAA":"x","AaA":"x"`,
2911 wantErr: newDuplicateNameError("", []byte(`"aaa"`), len64(`{"AAA":"x","AaA":"x"`)),
2912 }, {
2913 name: jsontest.Name("Structs/Invalid/Conflicting"),
2914 in: structConflicting{},
2915 want: ``,
2916 wantErr: EM(errors.New("Go struct fields A and B conflict over JSON object name \"conflict\"")).withType(0, T[structConflicting]()),
2917 }, {
2918 name: jsontest.Name("Structs/Invalid/NoneExported"),
2919 in: structNoneExported{},
2920 want: ``,
2921 wantErr: EM(errNoExportedFields).withType(0, T[structNoneExported]()),
2922 }, {
2923 name: jsontest.Name("Structs/Invalid/MalformedTag"),
2924 in: structMalformedTag{},
2925 want: ``,
2926 wantErr: EM(errors.New("Go struct field Malformed has malformed `json` tag: invalid character '\"' at start of option (expecting Unicode letter or single quote)")).withType(0, T[structMalformedTag]()),
2927 }, {
2928 name: jsontest.Name("Structs/Invalid/UnexportedTag"),
2929 in: structUnexportedTag{},
2930 want: ``,
2931 wantErr: EM(errors.New("unexported Go struct field unexported cannot have non-ignored `json:\"name\"` tag")).withType(0, T[structUnexportedTag]()),
2932 }, {
2933 name: jsontest.Name("Structs/Invalid/ExportedEmbedded"),
2934 in: structExportedEmbedded{"hello"},
2935 want: ``,
2936 wantErr: EM(errors.New("embedded Go struct field NamedString of non-struct type must be explicitly given a JSON name")).withType(0, T[structExportedEmbedded]()),
2937 }, {
2938 name: jsontest.Name("Structs/Valid/ExportedEmbedded"),
2939 opts: []Options{jsonflags.ReportErrorsWithLegacySemantics | 1},
2940 in: structExportedEmbedded{"hello"},
2941 want: `{"NamedString":"hello"}`,
2942 }, {
2943 name: jsontest.Name("Structs/Valid/ExportedEmbeddedTag"),
2944 in: structExportedEmbeddedTag{"hello"},
2945 want: `{"name":"hello"}`,
2946 }, {
2947 name: jsontest.Name("Structs/Invalid/UnexportedEmbedded"),
2948 in: structUnexportedEmbedded{},
2949 want: ``,
2950 wantErr: EM(errors.New("embedded Go struct field namedString of non-struct type must be explicitly given a JSON name")).withType(0, T[structUnexportedEmbedded]()),
2951 }, {
2952 name: jsontest.Name("Structs/Valid/UnexportedEmbedded"),
2953 opts: []Options{jsonflags.ReportErrorsWithLegacySemantics | 1},
2954 in: structUnexportedEmbedded{},
2955 want: `{}`,
2956 }, {
2957 name: jsontest.Name("Structs/Invalid/UnexportedEmbeddedTag"),
2958 in: structUnexportedEmbeddedTag{},
2959 wantErr: EM(errors.New("Go struct field namedString is not exported")).withType(0, T[structUnexportedEmbeddedTag]()),
2960 }, {
2961 name: jsontest.Name("Structs/Valid/UnexportedEmbeddedTag"),
2962 opts: []Options{jsonflags.ReportErrorsWithLegacySemantics | 1},
2963 in: structUnexportedEmbeddedTag{},
2964 want: `{}`,
2965 }, {
2966 name: jsontest.Name("Structs/Invalid/UnexportedEmbeddedMethodTag"),
2967 opts: []Options{jsonflags.ReportErrorsWithLegacySemantics | 1},
2968 in: structUnexportedEmbeddedMethodTag{},
2969 want: `{}`,
2970 }, {
2971 name: jsontest.Name("Structs/UnexportedEmbeddedStruct/Zero"),
2972 in: structUnexportedEmbeddedStruct{},
2973 want: `{"FizzBuzz":0,"Addr":""}`,
2974 }, {
2975 name: jsontest.Name("Structs/UnexportedEmbeddedStruct/NonZero"),
2976 in: structUnexportedEmbeddedStruct{structOmitZeroAll{Bool: true}, 5, structNestedAddr{netip.AddrFrom4([4]byte{192, 168, 0, 1})}},
2977 want: `{"Bool":true,"FizzBuzz":5,"Addr":"192.168.0.1"}`,
2978 }, {
2979 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/Nil"),
2980 in: structUnexportedEmbeddedStructPointer{},
2981 want: `{"FizzBuzz":0}`,
2982 }, {
2983 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/Zero"),
2984 in: structUnexportedEmbeddedStructPointer{&structOmitZeroAll{}, 0, &structNestedAddr{}},
2985 want: `{"FizzBuzz":0,"Addr":""}`,
2986 }, {
2987 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/NonZero"),
2988 in: structUnexportedEmbeddedStructPointer{&structOmitZeroAll{Bool: true}, 5, &structNestedAddr{netip.AddrFrom4([4]byte{192, 168, 0, 1})}},
2989 want: `{"Bool":true,"FizzBuzz":5,"Addr":"192.168.0.1"}`,
2990 }, {
2991 name: jsontest.Name("Structs/IgnoreInvalidFormat"),
2992 opts: []Options{invalidFormatOption},
2993 in: struct{}{},
2994 want: `{}`,
2995 }, {
2996 name: jsontest.Name("Slices/Interface"),
2997 in: []any{
2998 false, true,
2999 "hello", []byte("world"),
3000 int32(-32), namedInt64(-64),
3001 uint32(+32), namedUint64(+64),
3002 float32(32.32), namedFloat64(64.64),
3003 },
3004 want: `[false,true,"hello","d29ybGQ=",-32,-64,32,64,32.32,64.64]`,
3005 }, {
3006 name: jsontest.Name("Slices/Invalid/Channel"),
3007 in: [](chan string){nil},
3008 want: `[`,
3009 wantErr: EM(nil).withPos(`[`, "/0").withType(0, T[chan string]()),
3010 }, {
3011 name: jsontest.Name("Slices/RecursiveSlice"),
3012 in: recursiveSlice{
3013 nil,
3014 {},
3015 {nil},
3016 {nil, {}},
3017 },
3018 want: `[[],[],[[]],[[],[]]]`,
3019 }, {
3020 name: jsontest.Name("Slices/CyclicSlice"),
3021 in: func() recursiveSlice {
3022 s := recursiveSlice{{}}
3023 s[0] = s
3024 return s
3025 }(),
3026 want: strings.Repeat(`[`, startDetectingCyclesAfter) + `[`,
3027 wantErr: EM(internal.ErrCycle).withPos(strings.Repeat("[", startDetectingCyclesAfter+1), jsontext.Pointer(strings.Repeat("/0", startDetectingCyclesAfter+1))).withType(0, T[recursiveSlice]()),
3028 }, {
3029 name: jsontest.Name("Slices/NonCyclicSlice"),
3030 in: func() []any {
3031 v := []any{nil, nil}
3032 v[1] = v[:1]
3033 for i := 1000; i > 0; i-- {
3034 v = []any{v}
3035 }
3036 return v
3037 }(),
3038 want: strings.Repeat(`[`, startDetectingCyclesAfter) + `[null,[null]]` + strings.Repeat(`]`, startDetectingCyclesAfter),
3039 }, {
3040 name: jsontest.Name("Slices/IgnoreInvalidFormat"),
3041 opts: []Options{invalidFormatOption},
3042 in: []string{"hello", "goodbye"},
3043 want: `["hello","goodbye"]`,
3044 }, {
3045 name: jsontest.Name("Arrays/Empty"),
3046 in: [0]struct{}{},
3047 want: `[]`,
3048 }, {
3049 name: jsontest.Name("Arrays/Bool"),
3050 in: [2]bool{false, true},
3051 want: `[false,true]`,
3052 }, {
3053 name: jsontest.Name("Arrays/String"),
3054 in: [2]string{"hello", "goodbye"},
3055 want: `["hello","goodbye"]`,
3056 }, {
3057 name: jsontest.Name("Arrays/Bytes"),
3058 in: [2][]byte{[]byte("hello"), []byte("goodbye")},
3059 want: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
3060 }, {
3061 name: jsontest.Name("Arrays/Int"),
3062 in: [2]int64{math.MinInt64, math.MaxInt64},
3063 want: `[-9223372036854775808,9223372036854775807]`,
3064 }, {
3065 name: jsontest.Name("Arrays/Uint"),
3066 in: [2]uint64{0, math.MaxUint64},
3067 want: `[0,18446744073709551615]`,
3068 }, {
3069 name: jsontest.Name("Arrays/Float"),
3070 in: [2]float64{-math.MaxFloat64, +math.MaxFloat64},
3071 want: `[-1.7976931348623157e+308,1.7976931348623157e+308]`,
3072 }, {
3073 name: jsontest.Name("Arrays/Invalid/Channel"),
3074 in: new([1]chan string),
3075 want: `[`,
3076 wantErr: EM(nil).withPos(`[`, "/0").withType(0, T[chan string]()),
3077 }, {
3078 name: jsontest.Name("Arrays/IgnoreInvalidFormat"),
3079 opts: []Options{invalidFormatOption},
3080 in: [2]string{"hello", "goodbye"},
3081 want: `["hello","goodbye"]`,
3082 }, {
3083 name: jsontest.Name("Pointers/NilL0"),
3084 in: (*int)(nil),
3085 want: `null`,
3086 }, {
3087 name: jsontest.Name("Pointers/NilL1"),
3088 in: new(*int),
3089 want: `null`,
3090 }, {
3091 name: jsontest.Name("Pointers/Bool"),
3092 in: addr(addr(bool(true))),
3093 want: `true`,
3094 }, {
3095 name: jsontest.Name("Pointers/String"),
3096 in: addr(addr(string("string"))),
3097 want: `"string"`,
3098 }, {
3099 name: jsontest.Name("Pointers/Bytes"),
3100 in: addr(addr([]byte("bytes"))),
3101 want: `"Ynl0ZXM="`,
3102 }, {
3103 name: jsontest.Name("Pointers/Int"),
3104 in: addr(addr(int(-100))),
3105 want: `-100`,
3106 }, {
3107 name: jsontest.Name("Pointers/Uint"),
3108 in: addr(addr(uint(100))),
3109 want: `100`,
3110 }, {
3111 name: jsontest.Name("Pointers/Float"),
3112 in: addr(addr(float64(3.14159))),
3113 want: `3.14159`,
3114 }, {
3115 name: jsontest.Name("Pointers/CyclicPointer"),
3116 in: func() *recursivePointer {
3117 p := new(recursivePointer)
3118 p.P = p
3119 return p
3120 }(),
3121 want: strings.Repeat(`{"P":`, startDetectingCyclesAfter) + `{"P"`,
3122 wantErr: EM(internal.ErrCycle).withPos(strings.Repeat(`{"P":`, startDetectingCyclesAfter+1), jsontext.Pointer(strings.Repeat("/P", startDetectingCyclesAfter+1))).withType(0, T[*recursivePointer]()),
3123 }, {
3124 name: jsontest.Name("Pointers/IgnoreInvalidFormat"),
3125 opts: []Options{invalidFormatOption},
3126 in: addr(addr(bool(true))),
3127 want: `true`,
3128 }, {
3129 name: jsontest.Name("Interfaces/Nil/Empty"),
3130 in: [1]any{nil},
3131 want: `[null]`,
3132 }, {
3133 name: jsontest.Name("Interfaces/Nil/NonEmpty"),
3134 in: [1]io.Reader{nil},
3135 want: `[null]`,
3136 }, {
3137 name: jsontest.Name("Interfaces/IgnoreInvalidFormat"),
3138 opts: []Options{invalidFormatOption},
3139 in: [1]io.Reader{nil},
3140 want: `[null]`,
3141 }, {
3142 name: jsontest.Name("Interfaces/Any"),
3143 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}, [8]byte{}}},
3144 want: `{"X":[null,false,"",0,{},[],"AAAAAAAAAAA="]}`,
3145 }, {
3146 name: jsontest.Name("Interfaces/Any/Named"),
3147 in: struct{ X namedAny }{[]namedAny{nil, false, "", 0.0, map[string]namedAny{}, []namedAny{}, [8]byte{}}},
3148 want: `{"X":[null,false,"",0,{},[],"AAAAAAAAAAA="]}`,
3149 }, {
3150 name: jsontest.Name("Interfaces/Any/Stringified"),
3151 opts: []Options{StringifyNumbers(true)},
3152 in: struct{ X any }{0.0},
3153 want: `{"X":"0"}`,
3154 }, {
3155 name: jsontest.Name("Interfaces/Any/MarshalFunc/Any"),
3156 opts: []Options{
3157 WithMarshalers(MarshalFunc(func(v any) ([]byte, error) {
3158 return []byte(`"called"`), nil
3159 })),
3160 },
3161 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3162 want: `"called"`,
3163 }, {
3164 name: jsontest.Name("Interfaces/Any/MarshalFunc/Bool"),
3165 opts: []Options{
3166 WithMarshalers(MarshalFunc(func(v bool) ([]byte, error) {
3167 return []byte(`"called"`), nil
3168 })),
3169 },
3170 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3171 want: `{"X":[null,"called","",0,{},[]]}`,
3172 }, {
3173 name: jsontest.Name("Interfaces/Any/MarshalFunc/String"),
3174 opts: []Options{
3175 WithMarshalers(MarshalFunc(func(v string) ([]byte, error) {
3176 return []byte(`"called"`), nil
3177 })),
3178 },
3179 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3180 want: `{"X":[null,false,"called",0,{},[]]}`,
3181 }, {
3182 name: jsontest.Name("Interfaces/Any/MarshalFunc/Float64"),
3183 opts: []Options{
3184 WithMarshalers(MarshalFunc(func(v float64) ([]byte, error) {
3185 return []byte(`"called"`), nil
3186 })),
3187 },
3188 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3189 want: `{"X":[null,false,"","called",{},[]]}`,
3190 }, {
3191 name: jsontest.Name("Interfaces/Any/MarshalFunc/MapStringAny"),
3192 opts: []Options{
3193 WithMarshalers(MarshalFunc(func(v map[string]any) ([]byte, error) {
3194 return []byte(`"called"`), nil
3195 })),
3196 },
3197 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3198 want: `{"X":[null,false,"",0,"called",[]]}`,
3199 }, {
3200 name: jsontest.Name("Interfaces/Any/MarshalFunc/SliceAny"),
3201 opts: []Options{
3202 WithMarshalers(MarshalFunc(func(v []any) ([]byte, error) {
3203 return []byte(`"called"`), nil
3204 })),
3205 },
3206 in: struct{ X any }{[]any{nil, false, "", 0.0, map[string]any{}, []any{}}},
3207 want: `{"X":"called"}`,
3208 }, {
3209 name: jsontest.Name("Interfaces/Any/MarshalFunc/Bytes"),
3210 opts: []Options{
3211 WithMarshalers(MarshalFunc(func(v [8]byte) ([]byte, error) {
3212 return []byte(`"called"`), nil
3213 })),
3214 },
3215 in: struct{ X any }{[8]byte{}},
3216 want: `{"X":"called"}`,
3217 }, {
3218 name: jsontest.Name("Interfaces/Any/Float/NaN"),
3219 in: struct{ X any }{math.NaN()},
3220 want: `{"X"`,
3221 wantErr: EM(fmt.Errorf("unsupported value: %v", math.NaN())).withType(0, reflect.TypeFor[float64]()).withPos(`{"X":`, "/X"),
3222 }, {
3223 name: jsontest.Name("Interfaces/Any/Maps/Nil"),
3224 in: struct{ X any }{map[string]any(nil)},
3225 want: `{"X":{}}`,
3226 }, {
3227 name: jsontest.Name("Interfaces/Any/Maps/Nil/FormatNilMapAsNull"),
3228 opts: []Options{FormatNilMapAsNull(true)},
3229 in: struct{ X any }{map[string]any(nil)},
3230 want: `{"X":null}`,
3231 }, {
3232 name: jsontest.Name("Interfaces/Any/Maps/Empty"),
3233 in: struct{ X any }{map[string]any{}},
3234 want: `{"X":{}}`,
3235 }, {
3236 name: jsontest.Name("Interfaces/Any/Maps/Empty/Multiline"),
3237 opts: []Options{jsontext.Multiline(true), jsontext.WithIndent("")},
3238 in: struct{ X any }{map[string]any{}},
3239 want: "{\n\"X\": {}\n}",
3240 }, {
3241 name: jsontest.Name("Interfaces/Any/Maps/NonEmpty"),
3242 in: struct{ X any }{map[string]any{"fizz": "buzz"}},
3243 want: `{"X":{"fizz":"buzz"}}`,
3244 }, {
3245 name: jsontest.Name("Interfaces/Any/Maps/Deterministic"),
3246 opts: []Options{Deterministic(true)},
3247 in: struct{ X any }{map[string]any{"alpha": "", "bravo": ""}},
3248 want: `{"X":{"alpha":"","bravo":""}}`,
3249 }, {
3250 name: jsontest.Name("Interfaces/Any/Maps/Deterministic+AllowInvalidUTF8+RejectDuplicateNames"),
3251 opts: []Options{Deterministic(true), jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(false)},
3252 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
3253 want: `{"X":{"�":""`,
3254 wantErr: newDuplicateNameError("/X", []byte(`"�"`), len64(`{"X":{"�":"",`)),
3255 }, {
3256 name: jsontest.Name("Interfaces/Any/Maps/Deterministic+AllowInvalidUTF8+AllowDuplicateNames"),
3257 opts: []Options{Deterministic(true), jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(true)},
3258 in: struct{ X any }{map[string]any{"\xff": "alpha", "\xfe": "bravo"}},
3259 want: `{"X":{"�":"bravo","�":"alpha"}}`,
3260 }, {
3261 name: jsontest.Name("Interfaces/Any/Maps/RejectInvalidUTF8"),
3262 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
3263 want: `{"X":{`,
3264 wantErr: newInvalidUTF8Error(len64(`{"X":{`), "/X"),
3265 }, {
3266 name: jsontest.Name("Interfaces/Any/Maps/AllowInvalidUTF8+RejectDuplicateNames"),
3267 opts: []Options{jsontext.AllowInvalidUTF8(true)},
3268 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
3269 want: `{"X":{"�":""`,
3270 wantErr: newDuplicateNameError("/X", []byte(`"�"`), len64(`{"X":{"�":"",`)),
3271 }, {
3272 name: jsontest.Name("Interfaces/Any/Maps/AllowInvalidUTF8+AllowDuplicateNames"),
3273 opts: []Options{jsontext.AllowInvalidUTF8(true), jsontext.AllowDuplicateNames(true)},
3274 in: struct{ X any }{map[string]any{"\xff": "", "\xfe": ""}},
3275 want: `{"X":{"�":"","�":""}}`,
3276 }, {
3277 name: jsontest.Name("Interfaces/Any/Maps/Cyclic"),
3278 in: func() any {
3279 m := map[string]any{}
3280 m[""] = m
3281 return struct{ X any }{m}
3282 }(),
3283 want: `{"X"` + strings.Repeat(`:{""`, startDetectingCyclesAfter),
3284 wantErr: EM(internal.ErrCycle).withPos(`{"X":`+strings.Repeat(`{"":`, startDetectingCyclesAfter), "/X"+jsontext.Pointer(strings.Repeat("/", startDetectingCyclesAfter))).withType(0, T[map[string]any]()),
3285 }, {
3286 name: jsontest.Name("Interfaces/Any/Slices/Nil"),
3287 in: struct{ X any }{[]any(nil)},
3288 want: `{"X":[]}`,
3289 }, {
3290 name: jsontest.Name("Interfaces/Any/Slices/Nil/FormatNilSliceAsNull"),
3291 opts: []Options{FormatNilSliceAsNull(true)},
3292 in: struct{ X any }{[]any(nil)},
3293 want: `{"X":null}`,
3294 }, {
3295 name: jsontest.Name("Interfaces/Any/Slices/Empty"),
3296 in: struct{ X any }{[]any{}},
3297 want: `{"X":[]}`,
3298 }, {
3299 name: jsontest.Name("Interfaces/Any/Slices/Empty/Multiline"),
3300 opts: []Options{jsontext.Multiline(true), jsontext.WithIndent("")},
3301 in: struct{ X any }{[]any{}},
3302 want: "{\n\"X\": []\n}",
3303 }, {
3304 name: jsontest.Name("Interfaces/Any/Slices/NonEmpty"),
3305 in: struct{ X any }{[]any{"fizz", "buzz"}},
3306 want: `{"X":["fizz","buzz"]}`,
3307 }, {
3308 name: jsontest.Name("Interfaces/Any/Slices/Cyclic"),
3309 in: func() any {
3310 s := make([]any, 1)
3311 s[0] = s
3312 return struct{ X any }{s}
3313 }(),
3314 want: `{"X":` + strings.Repeat(`[`, startDetectingCyclesAfter),
3315 wantErr: EM(internal.ErrCycle).withPos(`{"X":`+strings.Repeat(`[`, startDetectingCyclesAfter), "/X"+jsontext.Pointer(strings.Repeat("/0", startDetectingCyclesAfter))).withType(0, T[[]any]()),
3316 }, {
3317 name: jsontest.Name("Methods/NilPointer"),
3318 in: struct{ X *allMethods }{X: (*allMethods)(nil)}, // method should not be called
3319 want: `{"X":null}`,
3320 }, {
3321 // NOTE: Fixes https://github.com/dominikh/go-tools/issues/975.
3322 name: jsontest.Name("Methods/NilInterface"),
3323 in: struct{ X MarshalerTo }{X: (*allMethods)(nil)}, // method should not be called
3324 want: `{"X":null}`,
3325 }, {
3326 name: jsontest.Name("Methods/AllMethods"),
3327 in: struct{ X *allMethods }{X: &allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)}},
3328 want: `{"X":"hello"}`,
3329 }, {
3330 name: jsontest.Name("Methods/AllMethodsExceptJSONv2"),
3331 in: struct{ X *allMethodsExceptJSONv2 }{X: &allMethodsExceptJSONv2{allMethods: allMethods{method: "MarshalJSON", value: []byte(`"hello"`)}}},
3332 want: `{"X":"hello"}`,
3333 }, {
3334 name: jsontest.Name("Methods/AllMethodsExceptJSONv1"),
3335 in: struct{ X *allMethodsExceptJSONv1 }{X: &allMethodsExceptJSONv1{allMethods: allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)}}},
3336 want: `{"X":"hello"}`,
3337 }, {
3338 name: jsontest.Name("Methods/AllMethodsExceptText"),
3339 in: struct{ X *allMethodsExceptText }{X: &allMethodsExceptText{allMethods: allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)}}},
3340 want: `{"X":"hello"}`,
3341 }, {
3342 name: jsontest.Name("Methods/OnlyMethodJSONv2"),
3343 in: struct{ X *onlyMethodJSONv2 }{X: &onlyMethodJSONv2{allMethods: allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)}}},
3344 want: `{"X":"hello"}`,
3345 }, {
3346 name: jsontest.Name("Methods/OnlyMethodJSONv1"),
3347 in: struct{ X *onlyMethodJSONv1 }{X: &onlyMethodJSONv1{allMethods: allMethods{method: "MarshalJSON", value: []byte(`"hello"`)}}},
3348 want: `{"X":"hello"}`,
3349 }, {
3350 name: jsontest.Name("Methods/OnlyMethodText"),
3351 in: struct{ X *onlyMethodText }{X: &onlyMethodText{allMethods: allMethods{method: "MarshalText", value: []byte(`hello`)}}},
3352 want: `{"X":"hello"}`,
3353 }, {
3354 name: jsontest.Name("Methods/IP"),
3355 in: net.IPv4(192, 168, 0, 100),
3356 want: `"192.168.0.100"`,
3357 }, {
3358 name: jsontest.Name("Methods/NetIP"),
3359 in: struct {
3360 Addr netip.Addr
3361 AddrPort netip.AddrPort
3362 Prefix netip.Prefix
3363 }{
3364 Addr: netip.AddrFrom4([4]byte{1, 2, 3, 4}),
3365 AddrPort: netip.AddrPortFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 1234),
3366 Prefix: netip.PrefixFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 24),
3367 },
3368 want: `{"Addr":"1.2.3.4","AddrPort":"1.2.3.4:1234","Prefix":"1.2.3.4/24"}`,
3369 }, {
3370 // NOTE: Fixes https://go.dev/issue/46516.
3371 name: jsontest.Name("Methods/Anonymous"),
3372 in: struct{ X struct{ allMethods } }{X: struct{ allMethods }{allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)}}},
3373 want: `{"X":"hello"}`,
3374 }, {
3375 // NOTE: Fixes https://go.dev/issue/22967.
3376 name: jsontest.Name("Methods/Addressable"),
3377 in: struct {
3378 V allMethods
3379 M map[string]allMethods
3380 I any
3381 }{
3382 V: allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)},
3383 M: map[string]allMethods{"K": {method: "MarshalJSONTo", value: []byte(`"hello"`)}},
3384 I: allMethods{method: "MarshalJSONTo", value: []byte(`"hello"`)},
3385 },
3386 want: `{"V":"hello","M":{"K":"hello"},"I":"hello"}`,
3387 }, {
3388 // NOTE: Fixes https://go.dev/issue/29732.
3389 name: jsontest.Name("Methods/MapKey/JSONv2"),
3390 in: map[structMethodJSONv2]string{{"k1"}: "v1", {"k2"}: "v2"},
3391 want: `{"k1":"v1","k2":"v2"}`,
3392 canonicalize: true,
3393 }, {
3394 // NOTE: Fixes https://go.dev/issue/29732.
3395 name: jsontest.Name("Methods/MapKey/JSONv1"),
3396 in: map[structMethodJSONv1]string{{"k1"}: "v1", {"k2"}: "v2"},
3397 want: `{"k1":"v1","k2":"v2"}`,
3398 canonicalize: true,
3399 }, {
3400 name: jsontest.Name("Methods/MapKey/Text"),
3401 in: map[structMethodText]string{{"k1"}: "v1", {"k2"}: "v2"},
3402 want: `{"k1":"v1","k2":"v2"}`,
3403 canonicalize: true,
3404 }, {
3405 name: jsontest.Name("Methods/Invalid/JSONv2/Error"),
3406 in: marshalJSONv2Func(func(*jsontext.Encoder) error {
3407 return errSomeError
3408 }),
3409 wantErr: EM(errSomeError).withType(0, T[marshalJSONv2Func]()),
3410 }, {
3411 name: jsontest.Name("Methods/Invalid/JSONv2/TooFew"),
3412 in: marshalJSONv2Func(func(*jsontext.Encoder) error {
3413 return nil // do nothing
3414 }),
3415 wantErr: EM(errNonSingularValue).withType(0, T[marshalJSONv2Func]()),
3416 }, {
3417 name: jsontest.Name("Methods/Invalid/JSONv2/TooMany"),
3418 in: marshalJSONv2Func(func(enc *jsontext.Encoder) error {
3419 enc.WriteToken(jsontext.Null)
3420 enc.WriteToken(jsontext.Null)
3421 return nil
3422 }),
3423 want: `nullnull`,
3424 wantErr: EM(errNonSingularValue).withPos(`nullnull`, "").withType(0, T[marshalJSONv2Func]()),
3425 }, {
3426 name: jsontest.Name("Methods/Invalid/JSONv2/SkipFunc"),
3427 in: marshalJSONv2Func(func(enc *jsontext.Encoder) error {
3428 return SkipFunc
3429 }),
3430 wantErr: EM(errors.New("marshal method cannot be skipped")).withType(0, T[marshalJSONv2Func]()),
3431 }, {
3432 name: jsontest.Name("Methods/Invalid/JSONv1/Error"),
3433 in: marshalJSONv1Func(func() ([]byte, error) {
3434 return nil, errSomeError
3435 }),
3436 wantErr: EM(errSomeError).withType(0, T[marshalJSONv1Func]()),
3437 }, {
3438 name: jsontest.Name("Methods/Invalid/JSONv1/Syntax"),
3439 in: marshalJSONv1Func(func() ([]byte, error) {
3440 return []byte("invalid"), nil
3441 }),
3442 wantErr: EM(newInvalidCharacterError("i", "at start of value", 0, "")).withType(0, T[marshalJSONv1Func]()),
3443 }, {
3444 name: jsontest.Name("Methods/Invalid/JSONv1/SkipFunc"),
3445 in: marshalJSONv1Func(func() ([]byte, error) {
3446 return nil, SkipFunc
3447 }),
3448 wantErr: EM(errors.New("marshal method cannot be skipped")).withType(0, T[marshalJSONv1Func]()),
3449 }, {
3450 name: jsontest.Name("Methods/AppendText"),
3451 in: appendTextFunc(func(b []byte) ([]byte, error) { return append(b, "hello"...), nil }),
3452 want: `"hello"`,
3453 }, {
3454 name: jsontest.Name("Methods/AppendText/Error"),
3455 in: appendTextFunc(func(b []byte) ([]byte, error) { return append(b, "hello"...), errSomeError }),
3456 wantErr: EM(errSomeError).withType(0, T[appendTextFunc]()),
3457 }, {
3458 name: jsontest.Name("Methods/AppendText/NeedEscape"),
3459 in: appendTextFunc(func(b []byte) ([]byte, error) { return append(b, `"`...), nil }),
3460 want: `"\""`,
3461 }, {
3462 name: jsontest.Name("Methods/AppendText/RejectInvalidUTF8"),
3463 in: appendTextFunc(func(b []byte) ([]byte, error) { return append(b, "\xde\xad\xbe\xef"...), nil }),
3464 wantErr: EM(newInvalidUTF8Error(0, "")).withType(0, T[appendTextFunc]()),
3465 }, {
3466 name: jsontest.Name("Methods/AppendText/AllowInvalidUTF8"),
3467 opts: []Options{jsontext.AllowInvalidUTF8(true)},
3468 in: appendTextFunc(func(b []byte) ([]byte, error) { return append(b, "\xde\xad\xbe\xef"...), nil }),
3469 want: "\"\xde\xad\ufffd\ufffd\"",
3470 }, {
3471 name: jsontest.Name("Methods/Invalid/Text/Error"),
3472 in: marshalTextFunc(func() ([]byte, error) {
3473 return nil, errSomeError
3474 }),
3475 wantErr: EM(errSomeError).withType(0, T[marshalTextFunc]()),
3476 }, {
3477 name: jsontest.Name("Methods/Text/RejectInvalidUTF8"),
3478 in: marshalTextFunc(func() ([]byte, error) {
3479 return []byte("\xde\xad\xbe\xef"), nil
3480 }),
3481 wantErr: EM(newInvalidUTF8Error(0, "")).withType(0, T[marshalTextFunc]()),
3482 }, {
3483 name: jsontest.Name("Methods/Text/AllowInvalidUTF8"),
3484 opts: []Options{jsontext.AllowInvalidUTF8(true)},
3485 in: marshalTextFunc(func() ([]byte, error) {
3486 return []byte("\xde\xad\xbe\xef"), nil
3487 }),
3488 want: "\"\xde\xad\ufffd\ufffd\"",
3489 }, {
3490 name: jsontest.Name("Methods/Invalid/Text/SkipFunc"),
3491 in: marshalTextFunc(func() ([]byte, error) {
3492 return nil, SkipFunc
3493 }),
3494 wantErr: EM(wrapSkipFunc(SkipFunc, "marshal method")).withType(0, T[marshalTextFunc]()),
3495 }, {
3496 name: jsontest.Name("Methods/Invalid/MapKey/JSONv2/Syntax"),
3497 in: map[any]string{
3498 addr(marshalJSONv2Func(func(enc *jsontext.Encoder) error {
3499 return enc.WriteToken(jsontext.Null)
3500 })): "invalid",
3501 },
3502 want: `{`,
3503 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[marshalJSONv2Func]()),
3504 }, {
3505 name: jsontest.Name("Methods/Invalid/MapKey/JSONv1/Syntax"),
3506 in: map[any]string{
3507 addr(marshalJSONv1Func(func() ([]byte, error) {
3508 return []byte(`null`), nil
3509 })): "invalid",
3510 },
3511 want: `{`,
3512 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[marshalJSONv1Func]()),
3513 }, {
3514 name: jsontest.Name("Functions/Bool/V1"),
3515 opts: []Options{
3516 WithMarshalers(MarshalFunc(func(bool) ([]byte, error) {
3517 return []byte(`"called"`), nil
3518 })),
3519 },
3520 in: true,
3521 want: `"called"`,
3522 }, {
3523 name: jsontest.Name("Functions/Bool/Empty"),
3524 opts: []Options{WithMarshalers(nil)},
3525 in: true,
3526 want: `true`,
3527 }, {
3528 name: jsontest.Name("Functions/NamedBool/V1/NoMatch"),
3529 opts: []Options{
3530 WithMarshalers(MarshalFunc(func(namedBool) ([]byte, error) {
3531 return nil, errMustNotCall
3532 })),
3533 },
3534 in: true,
3535 want: `true`,
3536 }, {
3537 name: jsontest.Name("Functions/NamedBool/V1/Match"),
3538 opts: []Options{
3539 WithMarshalers(MarshalFunc(func(namedBool) ([]byte, error) {
3540 return []byte(`"called"`), nil
3541 })),
3542 },
3543 in: namedBool(true),
3544 want: `"called"`,
3545 }, {
3546 name: jsontest.Name("Functions/PointerBool/V1/Match"),
3547 opts: []Options{
3548 WithMarshalers(MarshalFunc(func(v *bool) ([]byte, error) {
3549 _ = *v // must be a non-nil pointer
3550 return []byte(`"called"`), nil
3551 })),
3552 },
3553 in: true,
3554 want: `"called"`,
3555 }, {
3556 name: jsontest.Name("Functions/Bool/V2"),
3557 opts: []Options{
3558 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3559 return enc.WriteToken(jsontext.String("called"))
3560 })),
3561 },
3562 in: true,
3563 want: `"called"`,
3564 }, {
3565 name: jsontest.Name("Functions/NamedBool/V2/NoMatch"),
3566 opts: []Options{
3567 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v namedBool) error {
3568 return errMustNotCall
3569 })),
3570 },
3571 in: true,
3572 want: `true`,
3573 }, {
3574 name: jsontest.Name("Functions/NamedBool/V2/Match"),
3575 opts: []Options{
3576 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v namedBool) error {
3577 return enc.WriteToken(jsontext.String("called"))
3578 })),
3579 },
3580 in: namedBool(true),
3581 want: `"called"`,
3582 }, {
3583 name: jsontest.Name("Functions/PointerBool/V2/Match"),
3584 opts: []Options{
3585 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *bool) error {
3586 _ = *v // must be a non-nil pointer
3587 return enc.WriteToken(jsontext.String("called"))
3588 })),
3589 },
3590 in: true,
3591 want: `"called"`,
3592 }, {
3593 name: jsontest.Name("Functions/Bool/Empty1/NoMatch"),
3594 opts: []Options{
3595 WithMarshalers(new(Marshalers)),
3596 },
3597 in: true,
3598 want: `true`,
3599 }, {
3600 name: jsontest.Name("Functions/Bool/Empty2/NoMatch"),
3601 opts: []Options{
3602 WithMarshalers(JoinMarshalers()),
3603 },
3604 in: true,
3605 want: `true`,
3606 }, {
3607 name: jsontest.Name("Functions/Bool/V1/DirectError"),
3608 opts: []Options{
3609 WithMarshalers(MarshalFunc(func(bool) ([]byte, error) {
3610 return nil, errSomeError
3611 })),
3612 },
3613 in: true,
3614 wantErr: EM(errSomeError).withType(0, T[bool]()),
3615 }, {
3616 name: jsontest.Name("Functions/Bool/V1/SkipError"),
3617 opts: []Options{
3618 WithMarshalers(MarshalFunc(func(bool) ([]byte, error) {
3619 return nil, SkipFunc
3620 })),
3621 },
3622 in: true,
3623 wantErr: EM(wrapSkipFunc(SkipFunc, "marshal function of type func(T) ([]byte, error)")).withType(0, T[bool]()),
3624 }, {
3625 name: jsontest.Name("Functions/Bool/V1/InvalidValue"),
3626 opts: []Options{
3627 WithMarshalers(MarshalFunc(func(bool) ([]byte, error) {
3628 return []byte("invalid"), nil
3629 })),
3630 },
3631 in: true,
3632 wantErr: EM(newInvalidCharacterError("i", "at start of value", 0, "")).withType(0, T[bool]()),
3633 }, {
3634 name: jsontest.Name("Functions/Bool/V2/DirectError"),
3635 opts: []Options{
3636 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3637 return errSomeError
3638 })),
3639 },
3640 in: true,
3641 wantErr: EM(errSomeError).withType(0, T[bool]()),
3642 }, {
3643 name: jsontest.Name("Functions/Bool/V2/TooFew"),
3644 opts: []Options{
3645 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3646 return nil
3647 })),
3648 },
3649 in: true,
3650 wantErr: EM(errNonSingularValue).withType(0, T[bool]()),
3651 }, {
3652 name: jsontest.Name("Functions/Bool/V2/TooMany"),
3653 opts: []Options{
3654 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3655 enc.WriteValue([]byte(`"hello"`))
3656 enc.WriteValue([]byte(`"world"`))
3657 return nil
3658 })),
3659 },
3660 in: true,
3661 want: `"hello""world"`,
3662 wantErr: EM(errNonSingularValue).withPos(`"hello""world"`, "").withType(0, T[bool]()),
3663 }, {
3664 name: jsontest.Name("Functions/Bool/V2/Skipped"),
3665 opts: []Options{
3666 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3667 return SkipFunc
3668 })),
3669 },
3670 in: true,
3671 want: `true`,
3672 }, {
3673 name: jsontest.Name("Functions/Bool/V2/ProcessBeforeSkip"),
3674 opts: []Options{
3675 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3676 enc.WriteValue([]byte(`"hello"`))
3677 return SkipFunc
3678 })),
3679 },
3680 in: true,
3681 want: `"hello"`,
3682 wantErr: EM(errSkipMutation).withPos(`"hello"`, "").withType(0, T[bool]()),
3683 }, {
3684 name: jsontest.Name("Functions/Bool/V2/WrappedSkipError"),
3685 opts: []Options{
3686 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
3687 return fmt.Errorf("wrap: %w", SkipFunc)
3688 })),
3689 },
3690 in: true,
3691 wantErr: EM(fmt.Errorf("wrap: %w", SkipFunc)).withType(0, T[bool]()),
3692 }, {
3693 name: jsontest.Name("Functions/Map/Key/NoCaseString/V1"),
3694 opts: []Options{
3695 WithMarshalers(MarshalFunc(func(v nocaseString) ([]byte, error) {
3696 return []byte(`"called"`), nil
3697 })),
3698 },
3699 in: map[nocaseString]string{"hello": "world"},
3700 want: `{"called":"world"}`,
3701 }, {
3702 name: jsontest.Name("Functions/Map/Key/PointerNoCaseString/V1"),
3703 opts: []Options{
3704 WithMarshalers(MarshalFunc(func(v *nocaseString) ([]byte, error) {
3705 _ = *v // must be a non-nil pointer
3706 return []byte(`"called"`), nil
3707 })),
3708 },
3709 in: map[nocaseString]string{"hello": "world"},
3710 want: `{"called":"world"}`,
3711 }, {
3712 name: jsontest.Name("Functions/Map/Key/TextMarshaler/V1"),
3713 opts: []Options{
3714 WithMarshalers(MarshalFunc(func(v encoding.TextMarshaler) ([]byte, error) {
3715 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3716 return []byte(`"called"`), nil
3717 })),
3718 },
3719 in: map[nocaseString]string{"hello": "world"},
3720 want: `{"called":"world"}`,
3721 }, {
3722 name: jsontest.Name("Functions/Map/Key/NoCaseString/V1/InvalidValue"),
3723 opts: []Options{
3724 WithMarshalers(MarshalFunc(func(v nocaseString) ([]byte, error) {
3725 return []byte(`null`), nil
3726 })),
3727 },
3728 in: map[nocaseString]string{"hello": "world"},
3729 want: `{`,
3730 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[nocaseString]()),
3731 }, {
3732 name: jsontest.Name("Functions/Map/Key/NoCaseString/V2/InvalidKind"),
3733 opts: []Options{
3734 WithMarshalers(MarshalFunc(func(v nocaseString) ([]byte, error) {
3735 return []byte(`null`), nil
3736 })),
3737 },
3738 in: map[nocaseString]string{"hello": "world"},
3739 want: `{`,
3740 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[nocaseString]()),
3741 }, {
3742 name: jsontest.Name("Functions/Map/Key/String/V1/DuplicateName"),
3743 opts: []Options{
3744 WithMarshalers(MarshalFunc(func(v string) ([]byte, error) {
3745 return []byte(`"name"`), nil
3746 })),
3747 },
3748 in: map[string]string{"name1": "value", "name2": "value"},
3749 want: `{"name":"name"`,
3750 wantErr: EM(newDuplicateNameError("", []byte(`"name"`), len64(`{"name":"name",`))).
3751 withPos(`{"name":"name",`, "").withType(0, T[string]()),
3752 }, {
3753 name: jsontest.Name("Functions/Map/Key/NoCaseString/V2"),
3754 opts: []Options{
3755 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v nocaseString) error {
3756 return enc.WriteValue([]byte(`"called"`))
3757 })),
3758 },
3759 in: map[nocaseString]string{"hello": "world"},
3760 want: `{"called":"world"}`,
3761 }, {
3762 name: jsontest.Name("Functions/Map/Key/PointerNoCaseString/V2"),
3763 opts: []Options{
3764 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *nocaseString) error {
3765 _ = *v // must be a non-nil pointer
3766 return enc.WriteValue([]byte(`"called"`))
3767 })),
3768 },
3769 in: map[nocaseString]string{"hello": "world"},
3770 want: `{"called":"world"}`,
3771 }, {
3772 name: jsontest.Name("Functions/Map/Key/TextMarshaler/V2"),
3773 opts: []Options{
3774 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v encoding.TextMarshaler) error {
3775 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3776 return enc.WriteValue([]byte(`"called"`))
3777 })),
3778 },
3779 in: map[nocaseString]string{"hello": "world"},
3780 want: `{"called":"world"}`,
3781 }, {
3782 name: jsontest.Name("Functions/Map/Key/NoCaseString/V2/InvalidToken"),
3783 opts: []Options{
3784 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v nocaseString) error {
3785 return enc.WriteToken(jsontext.Null)
3786 })),
3787 },
3788 in: map[nocaseString]string{"hello": "world"},
3789 want: `{`,
3790 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[nocaseString]()),
3791 }, {
3792 name: jsontest.Name("Functions/Map/Key/NoCaseString/V2/InvalidValue"),
3793 opts: []Options{
3794 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v nocaseString) error {
3795 return enc.WriteValue([]byte(`null`))
3796 })),
3797 },
3798 in: map[nocaseString]string{"hello": "world"},
3799 want: `{`,
3800 wantErr: EM(newNonStringNameError(len64(`{`), "")).withPos(`{`, "").withType(0, T[nocaseString]()),
3801 }, {
3802 name: jsontest.Name("Functions/Map/Value/NoCaseString/V1"),
3803 opts: []Options{
3804 WithMarshalers(MarshalFunc(func(v nocaseString) ([]byte, error) {
3805 return []byte(`"called"`), nil
3806 })),
3807 },
3808 in: map[string]nocaseString{"hello": "world"},
3809 want: `{"hello":"called"}`,
3810 }, {
3811 name: jsontest.Name("Functions/Map/Value/PointerNoCaseString/V1"),
3812 opts: []Options{
3813 WithMarshalers(MarshalFunc(func(v *nocaseString) ([]byte, error) {
3814 _ = *v // must be a non-nil pointer
3815 return []byte(`"called"`), nil
3816 })),
3817 },
3818 in: map[string]nocaseString{"hello": "world"},
3819 want: `{"hello":"called"}`,
3820 }, {
3821 name: jsontest.Name("Functions/Map/Value/TextMarshaler/V1"),
3822 opts: []Options{
3823 WithMarshalers(MarshalFunc(func(v encoding.TextMarshaler) ([]byte, error) {
3824 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3825 return []byte(`"called"`), nil
3826 })),
3827 },
3828 in: map[string]nocaseString{"hello": "world"},
3829 want: `{"hello":"called"}`,
3830 }, {
3831 name: jsontest.Name("Functions/Map/Value/NoCaseString/V2"),
3832 opts: []Options{
3833 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v nocaseString) error {
3834 return enc.WriteValue([]byte(`"called"`))
3835 })),
3836 },
3837 in: map[string]nocaseString{"hello": "world"},
3838 want: `{"hello":"called"}`,
3839 }, {
3840 name: jsontest.Name("Functions/Map/Value/PointerNoCaseString/V2"),
3841 opts: []Options{
3842 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *nocaseString) error {
3843 _ = *v // must be a non-nil pointer
3844 return enc.WriteValue([]byte(`"called"`))
3845 })),
3846 },
3847 in: map[string]nocaseString{"hello": "world"},
3848 want: `{"hello":"called"}`,
3849 }, {
3850 name: jsontest.Name("Functions/Map/Value/TextMarshaler/V2"),
3851 opts: []Options{
3852 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v encoding.TextMarshaler) error {
3853 _ = *v.(*nocaseString) // must be a non-nil *nocaseString
3854 return enc.WriteValue([]byte(`"called"`))
3855 })),
3856 },
3857 in: map[string]nocaseString{"hello": "world"},
3858 want: `{"hello":"called"}`,
3859 }, {
3860 name: jsontest.Name("Funtions/Struct/Fields"),
3861 opts: []Options{
3862 WithMarshalers(JoinMarshalers(
3863 MarshalFunc(func(v bool) ([]byte, error) {
3864 return []byte(`"called1"`), nil
3865 }),
3866 MarshalFunc(func(v *string) ([]byte, error) {
3867 return []byte(`"called2"`), nil
3868 }),
3869 MarshalToFunc(func(enc *jsontext.Encoder, v []byte) error {
3870 return enc.WriteValue([]byte(`"called3"`))
3871 }),
3872 MarshalToFunc(func(enc *jsontext.Encoder, v *int64) error {
3873 return enc.WriteValue([]byte(`"called4"`))
3874 }),
3875 )),
3876 },
3877 in: structScalars{},
3878 want: `{"Bool":"called1","String":"called2","Bytes":"called3","Int":"called4","Uint":0,"Float":0}`,
3879 }, {
3880 name: jsontest.Name("Functions/Struct/OmitEmpty"),
3881 opts: []Options{
3882 WithMarshalers(JoinMarshalers(
3883 MarshalFunc(func(v bool) ([]byte, error) {
3884 return []byte(`null`), nil
3885 }),
3886 MarshalFunc(func(v string) ([]byte, error) {
3887 return []byte(`"called1"`), nil
3888 }),
3889 MarshalFunc(func(v *stringMarshalNonEmpty) ([]byte, error) {
3890 return []byte(`""`), nil
3891 }),
3892 MarshalToFunc(func(enc *jsontext.Encoder, v bytesMarshalNonEmpty) error {
3893 return enc.WriteValue([]byte(`{}`))
3894 }),
3895 MarshalToFunc(func(enc *jsontext.Encoder, v *float64) error {
3896 return enc.WriteValue([]byte(`[]`))
3897 }),
3898 MarshalFunc(func(v mapMarshalNonEmpty) ([]byte, error) {
3899 return []byte(`"called2"`), nil
3900 }),
3901 MarshalFunc(func(v []string) ([]byte, error) {
3902 return []byte(`"called3"`), nil
3903 }),
3904 MarshalToFunc(func(enc *jsontext.Encoder, v *sliceMarshalNonEmpty) error {
3905 return enc.WriteValue([]byte(`"called4"`))
3906 }),
3907 )),
3908 },
3909 in: structOmitEmptyAll{},
3910 want: `{"String":"called1","MapNonEmpty":"called2","Slice":"called3","SliceNonEmpty":"called4"}`,
3911 }, {
3912 name: jsontest.Name("Functions/Struct/OmitZero"),
3913 opts: []Options{
3914 WithMarshalers(JoinMarshalers(
3915 MarshalFunc(func(v bool) ([]byte, error) {
3916 panic("should not be called")
3917 }),
3918 MarshalFunc(func(v *string) ([]byte, error) {
3919 panic("should not be called")
3920 }),
3921 MarshalToFunc(func(enc *jsontext.Encoder, v []byte) error {
3922 panic("should not be called")
3923 }),
3924 MarshalToFunc(func(enc *jsontext.Encoder, v *int64) error {
3925 panic("should not be called")
3926 }),
3927 )),
3928 },
3929 in: structOmitZeroAll{},
3930 want: `{}`,
3931 }, {
3932 name: jsontest.Name("Functions/Struct/Inlined"),
3933 opts: []Options{
3934 WithMarshalers(JoinMarshalers(
3935 MarshalFunc(func(v structInlinedL1) ([]byte, error) {
3936 panic("should not be called")
3937 }),
3938 MarshalToFunc(func(enc *jsontext.Encoder, v *StructEmbed2) error {
3939 panic("should not be called")
3940 }),
3941 )),
3942 },
3943 in: structInlined{},
3944 want: `{"D":""}`,
3945 }, {
3946 name: jsontest.Name("Functions/Slice/Elem"),
3947 opts: []Options{
3948 WithMarshalers(MarshalFunc(func(v bool) ([]byte, error) {
3949 return []byte(`"` + strconv.FormatBool(v) + `"`), nil
3950 })),
3951 },
3952 in: []bool{true, false},
3953 want: `["true","false"]`,
3954 }, {
3955 name: jsontest.Name("Functions/Array/Elem"),
3956 opts: []Options{
3957 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *bool) error {
3958 return enc.WriteValue([]byte(`"` + strconv.FormatBool(*v) + `"`))
3959 })),
3960 },
3961 in: [2]bool{true, false},
3962 want: `["true","false"]`,
3963 }, {
3964 name: jsontest.Name("Functions/Pointer/Nil"),
3965 opts: []Options{
3966 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *bool) error {
3967 panic("should not be called")
3968 })),
3969 },
3970 in: struct{ X *bool }{nil},
3971 want: `{"X":null}`,
3972 }, {
3973 name: jsontest.Name("Functions/Pointer/NonNil"),
3974 opts: []Options{
3975 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *bool) error {
3976 return enc.WriteValue([]byte(`"called"`))
3977 })),
3978 },
3979 in: struct{ X *bool }{addr(false)},
3980 want: `{"X":"called"}`,
3981 }, {
3982 name: jsontest.Name("Functions/Interface/Nil"),
3983 opts: []Options{
3984 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v fmt.Stringer) error {
3985 panic("should not be called")
3986 })),
3987 },
3988 in: struct{ X fmt.Stringer }{nil},
3989 want: `{"X":null}`,
3990 }, {
3991 name: jsontest.Name("Functions/Interface/NonNil/MatchInterface"),
3992 opts: []Options{
3993 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v fmt.Stringer) error {
3994 return enc.WriteValue([]byte(`"called"`))
3995 })),
3996 },
3997 in: struct{ X fmt.Stringer }{valueStringer{}},
3998 want: `{"X":"called"}`,
3999 }, {
4000 name: jsontest.Name("Functions/Interface/NonNil/MatchConcrete"),
4001 opts: []Options{
4002 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v valueStringer) error {
4003 return enc.WriteValue([]byte(`"called"`))
4004 })),
4005 },
4006 in: struct{ X fmt.Stringer }{valueStringer{}},
4007 want: `{"X":"called"}`,
4008 }, {
4009 name: jsontest.Name("Functions/Interface/NonNil/MatchPointer"),
4010 opts: []Options{
4011 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, v *valueStringer) error {
4012 return enc.WriteValue([]byte(`"called"`))
4013 })),
4014 },
4015 in: struct{ X fmt.Stringer }{valueStringer{}},
4016 want: `{"X":"called"}`,
4017 }, {
4018 name: jsontest.Name("Functions/Interface/Any"),
4019 in: []any{
4020 nil, // nil
4021 valueStringer{}, // T
4022 (*valueStringer)(nil), // *T
4023 addr(valueStringer{}), // *T
4024 (**valueStringer)(nil), // **T
4025 addr((*valueStringer)(nil)), // **T
4026 addr(addr(valueStringer{})), // **T
4027 pointerStringer{}, // T
4028 (*pointerStringer)(nil), // *T
4029 addr(pointerStringer{}), // *T
4030 (**pointerStringer)(nil), // **T
4031 addr((*pointerStringer)(nil)), // **T
4032 addr(addr(pointerStringer{})), // **T
4033 "LAST",
4034 },
4035 want: `[null,{},null,{},null,null,{},{},null,{},null,null,{},"LAST"]`,
4036 opts: []Options{
4037 WithMarshalers(func() *Marshalers {
4038 type P struct {
4039 D int
4040 N int64
4041 }
4042 type PV struct {
4043 P P
4044 V any
4045 }
4046
4047 var lastChecks []func() error
4048 checkLast := func() error {
4049 for _, fn := range lastChecks {
4050 if err := fn(); err != nil {
4051 return err
4052 }
4053 }
4054 return SkipFunc
4055 }
4056 makeValueChecker := func(name string, want []PV) func(e *jsontext.Encoder, v any) error {
4057 checkNext := func(e *jsontext.Encoder, v any) error {
4058 xe := export.Encoder(e)
4059 p := P{len(xe.Tokens.Stack), xe.Tokens.Last.Length()}
4060 rv := reflect.ValueOf(v)
4061 pv := PV{p, v}
4062 switch {
4063 case len(want) == 0:
4064 return fmt.Errorf("%s: %v: got more values than expected", name, p)
4065 case !rv.IsValid() || rv.Kind() != reflect.Pointer || rv.IsNil():
4066 return fmt.Errorf("%s: %v: got %#v, want non-nil pointer type", name, p, v)
4067 case !reflect.DeepEqual(pv, want[0]):
4068 return fmt.Errorf("%s:\n\tgot %#v\n\twant %#v", name, pv, want[0])
4069 default:
4070 want = want[1:]
4071 return SkipFunc
4072 }
4073 }
4074 lastChecks = append(lastChecks, func() error {
4075 if len(want) > 0 {
4076 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
4077 }
4078 return nil
4079 })
4080 return checkNext
4081 }
4082 makePositionChecker := func(name string, want []P) func(e *jsontext.Encoder, v any) error {
4083 checkNext := func(e *jsontext.Encoder, v any) error {
4084 xe := export.Encoder(e)
4085 p := P{len(xe.Tokens.Stack), xe.Tokens.Last.Length()}
4086 switch {
4087 case len(want) == 0:
4088 return fmt.Errorf("%s: %v: got more values than wanted", name, p)
4089 case p != want[0]:
4090 return fmt.Errorf("%s: got %v, want %v", name, p, want[0])
4091 default:
4092 want = want[1:]
4093 return SkipFunc
4094 }
4095 }
4096 lastChecks = append(lastChecks, func() error {
4097 if len(want) > 0 {
4098 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
4099 }
4100 return nil
4101 })
4102 return checkNext
4103 }
4104
4105 wantAny := []PV{
4106 {P{0, 0}, addr([]any{
4107 nil,
4108 valueStringer{},
4109 (*valueStringer)(nil),
4110 addr(valueStringer{}),
4111 (**valueStringer)(nil),
4112 addr((*valueStringer)(nil)),
4113 addr(addr(valueStringer{})),
4114 pointerStringer{},
4115 (*pointerStringer)(nil),
4116 addr(pointerStringer{}),
4117 (**pointerStringer)(nil),
4118 addr((*pointerStringer)(nil)),
4119 addr(addr(pointerStringer{})),
4120 "LAST",
4121 })},
4122 {P{1, 0}, addr(any(nil))},
4123 {P{1, 1}, addr(any(valueStringer{}))},
4124 {P{1, 1}, addr(valueStringer{})},
4125 {P{1, 2}, addr(any((*valueStringer)(nil)))},
4126 {P{1, 2}, addr((*valueStringer)(nil))},
4127 {P{1, 3}, addr(any(addr(valueStringer{})))},
4128 {P{1, 3}, addr(addr(valueStringer{}))},
4129 {P{1, 3}, addr(valueStringer{})},
4130 {P{1, 4}, addr(any((**valueStringer)(nil)))},
4131 {P{1, 4}, addr((**valueStringer)(nil))},
4132 {P{1, 5}, addr(any(addr((*valueStringer)(nil))))},
4133 {P{1, 5}, addr(addr((*valueStringer)(nil)))},
4134 {P{1, 5}, addr((*valueStringer)(nil))},
4135 {P{1, 6}, addr(any(addr(addr(valueStringer{}))))},
4136 {P{1, 6}, addr(addr(addr(valueStringer{})))},
4137 {P{1, 6}, addr(addr(valueStringer{}))},
4138 {P{1, 6}, addr(valueStringer{})},
4139 {P{1, 7}, addr(any(pointerStringer{}))},
4140 {P{1, 7}, addr(pointerStringer{})},
4141 {P{1, 8}, addr(any((*pointerStringer)(nil)))},
4142 {P{1, 8}, addr((*pointerStringer)(nil))},
4143 {P{1, 9}, addr(any(addr(pointerStringer{})))},
4144 {P{1, 9}, addr(addr(pointerStringer{}))},
4145 {P{1, 9}, addr(pointerStringer{})},
4146 {P{1, 10}, addr(any((**pointerStringer)(nil)))},
4147 {P{1, 10}, addr((**pointerStringer)(nil))},
4148 {P{1, 11}, addr(any(addr((*pointerStringer)(nil))))},
4149 {P{1, 11}, addr(addr((*pointerStringer)(nil)))},
4150 {P{1, 11}, addr((*pointerStringer)(nil))},
4151 {P{1, 12}, addr(any(addr(addr(pointerStringer{}))))},
4152 {P{1, 12}, addr(addr(addr(pointerStringer{})))},
4153 {P{1, 12}, addr(addr(pointerStringer{}))},
4154 {P{1, 12}, addr(pointerStringer{})},
4155 {P{1, 13}, addr(any("LAST"))},
4156 {P{1, 13}, addr("LAST")},
4157 }
4158 checkAny := makeValueChecker("any", wantAny)
4159 anyMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v any) error {
4160 return checkAny(enc, v)
4161 })
4162
4163 var wantPointerAny []PV
4164 for _, v := range wantAny {
4165 if _, ok := v.V.(*any); ok {
4166 wantPointerAny = append(wantPointerAny, v)
4167 }
4168 }
4169 checkPointerAny := makeValueChecker("*any", wantPointerAny)
4170 pointerAnyMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v *any) error {
4171 return checkPointerAny(enc, v)
4172 })
4173
4174 checkNamedAny := makeValueChecker("namedAny", wantAny)
4175 namedAnyMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v namedAny) error {
4176 return checkNamedAny(enc, v)
4177 })
4178
4179 checkPointerNamedAny := makeValueChecker("*namedAny", nil)
4180 pointerNamedAnyMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v *namedAny) error {
4181 return checkPointerNamedAny(enc, v)
4182 })
4183
4184 type stringer = fmt.Stringer
4185 var wantStringer []PV
4186 for _, v := range wantAny {
4187 if _, ok := v.V.(stringer); ok {
4188 wantStringer = append(wantStringer, v)
4189 }
4190 }
4191 checkStringer := makeValueChecker("stringer", wantStringer)
4192 stringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v stringer) error {
4193 return checkStringer(enc, v)
4194 })
4195
4196 checkPointerStringer := makeValueChecker("*stringer", nil)
4197 pointerStringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v *stringer) error {
4198 return checkPointerStringer(enc, v)
4199 })
4200
4201 wantValueStringer := []P{{1, 1}, {1, 3}, {1, 6}}
4202 checkValueValueStringer := makePositionChecker("valueStringer", wantValueStringer)
4203 valueValueStringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v valueStringer) error {
4204 return checkValueValueStringer(enc, v)
4205 })
4206
4207 checkPointerValueStringer := makePositionChecker("*valueStringer", wantValueStringer)
4208 pointerValueStringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v *valueStringer) error {
4209 return checkPointerValueStringer(enc, v)
4210 })
4211
4212 wantPointerStringer := []P{{1, 7}, {1, 9}, {1, 12}}
4213 checkValuePointerStringer := makePositionChecker("pointerStringer", wantPointerStringer)
4214 valuePointerStringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v pointerStringer) error {
4215 return checkValuePointerStringer(enc, v)
4216 })
4217
4218 checkPointerPointerStringer := makePositionChecker("*pointerStringer", wantPointerStringer)
4219 pointerPointerStringerMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v *pointerStringer) error {
4220 return checkPointerPointerStringer(enc, v)
4221 })
4222
4223 lastMarshaler := MarshalToFunc(func(enc *jsontext.Encoder, v string) error {
4224 return checkLast()
4225 })
4226
4227 return JoinMarshalers(
4228 anyMarshaler,
4229 pointerAnyMarshaler,
4230 namedAnyMarshaler,
4231 pointerNamedAnyMarshaler, // never called
4232 stringerMarshaler,
4233 pointerStringerMarshaler, // never called
4234 valueValueStringerMarshaler,
4235 pointerValueStringerMarshaler,
4236 valuePointerStringerMarshaler,
4237 pointerPointerStringerMarshaler,
4238 lastMarshaler,
4239 )
4240 }()),
4241 },
4242 }, {
4243 name: jsontest.Name("Functions/Precedence/V1First"),
4244 opts: []Options{
4245 WithMarshalers(JoinMarshalers(
4246 MarshalFunc(func(bool) ([]byte, error) {
4247 return []byte(`"called"`), nil
4248 }),
4249 MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
4250 panic("should not be called")
4251 }),
4252 )),
4253 },
4254 in: true,
4255 want: `"called"`,
4256 }, {
4257 name: jsontest.Name("Functions/Precedence/V2First"),
4258 opts: []Options{
4259 WithMarshalers(JoinMarshalers(
4260 MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
4261 return enc.WriteToken(jsontext.String("called"))
4262 }),
4263 MarshalFunc(func(bool) ([]byte, error) {
4264 panic("should not be called")
4265 }),
4266 )),
4267 },
4268 in: true,
4269 want: `"called"`,
4270 }, {
4271 name: jsontest.Name("Functions/Precedence/V2Skipped"),
4272 opts: []Options{
4273 WithMarshalers(JoinMarshalers(
4274 MarshalToFunc(func(enc *jsontext.Encoder, v bool) error {
4275 return SkipFunc
4276 }),
4277 MarshalFunc(func(bool) ([]byte, error) {
4278 return []byte(`"called"`), nil
4279 }),
4280 )),
4281 },
4282 in: true,
4283 want: `"called"`,
4284 }, {
4285 name: jsontest.Name("Functions/Precedence/NestedFirst"),
4286 opts: []Options{
4287 WithMarshalers(JoinMarshalers(
4288 JoinMarshalers(
4289 MarshalFunc(func(bool) ([]byte, error) {
4290 return []byte(`"called"`), nil
4291 }),
4292 ),
4293 MarshalFunc(func(bool) ([]byte, error) {
4294 panic("should not be called")
4295 }),
4296 )),
4297 },
4298 in: true,
4299 want: `"called"`,
4300 }, {
4301 name: jsontest.Name("Functions/Precedence/NestedLast"),
4302 opts: []Options{
4303 WithMarshalers(JoinMarshalers(
4304 MarshalFunc(func(bool) ([]byte, error) {
4305 return []byte(`"called"`), nil
4306 }),
4307 JoinMarshalers(
4308 MarshalFunc(func(bool) ([]byte, error) {
4309 panic("should not be called")
4310 }),
4311 ),
4312 )),
4313 },
4314 in: true,
4315 want: `"called"`,
4316 }, {
4317 name: jsontest.Name("Duration/Zero"),
4318 in: struct {
4319 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
4320 D2 time.Duration `json:",format:nano"`
4321 }{0, 0},
4322 want: `{"D1":"0s","D2":0}`,
4323 }, {
4324 name: jsontest.Name("Duration/Positive"),
4325 in: struct {
4326 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
4327 D2 time.Duration `json:",format:nano"`
4328 }{
4329 123456789123456789,
4330 123456789123456789,
4331 },
4332 want: `{"D1":"34293h33m9.123456789s","D2":123456789123456789}`,
4333 }, {
4334 name: jsontest.Name("Duration/Negative"),
4335 in: struct {
4336 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
4337 D2 time.Duration `json:",format:nano"`
4338 }{
4339 -123456789123456789,
4340 -123456789123456789,
4341 },
4342 want: `{"D1":"-34293h33m9.123456789s","D2":-123456789123456789}`,
4343 }, {
4344 name: jsontest.Name("Duration/Nanos/String"),
4345 in: struct {
4346 D1 time.Duration `json:",string,format:nano"`
4347 D2 time.Duration `json:",string,format:nano"`
4348 D3 time.Duration `json:",string,format:nano"`
4349 }{
4350 math.MinInt64,
4351 0,
4352 math.MaxInt64,
4353 },
4354 want: `{"D1":"-9223372036854775808","D2":"0","D3":"9223372036854775807"}`,
4355 }, {
4356 name: jsontest.Name("Duration/Format/Invalid"),
4357 in: struct {
4358 D time.Duration `json:",format:invalid"`
4359 }{},
4360 want: `{"D"`,
4361 wantErr: EM(errInvalidFormatFlag).withPos(`{"D":`, "/D").withType(0, T[time.Duration]()),
4362 }, {
4363 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
4364 name: jsontest.Name("Duration/IgnoreInvalidFormat"),
4365 opts: []Options{invalidFormatOption},
4366 in: time.Duration(0),
4367 want: `"0s"`,
4368 }, { */
4369 name: jsontest.Name("Duration/Format"),
4370 opts: []Options{jsontext.Multiline(true)},
4371 in: structDurationFormat{
4372 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4373 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4374 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4375 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4376 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4377 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4378 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4379 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4380 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4381 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4382 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4383 },
4384 want: `{
4385 "D1": "12h34m56.078090012s",
4386 "D2": "12h34m56.078090012s",
4387 "D3": 45296.078090012,
4388 "D4": "45296.078090012",
4389 "D5": 45296078.090012,
4390 "D6": "45296078.090012",
4391 "D7": 45296078090.012,
4392 "D8": "45296078090.012",
4393 "D9": 45296078090012,
4394 "D10": "45296078090012",
4395 "D11": "PT12H34M56.078090012S"
4396 }`,
4397 }, {
4398 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
4399 name: jsontest.Name("Duration/Format/Legacy"),
4400 opts: []Options{jsonflags.FormatDurationAsNano | 1},
4401 in: structDurationFormat{
4402 D1: 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4403 D2: 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
4404 },
4405 want: `{"D1":45296078090012,"D2":"12h34m56.078090012s","D3":0,"D4":"0","D5":0,"D6":"0","D7":0,"D8":"0","D9":0,"D10":"0","D11":"PT0S"}`,
4406 }, { */
4407 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
4408 name: jsontest.Name("Duration/MapKey"),
4409 in: map[time.Duration]string{time.Second: ""},
4410 want: `{"1s":""}`,
4411 }, { */
4412 name: jsontest.Name("Duration/MapKey/Legacy"),
4413 opts: []Options{jsonflags.FormatDurationAsNano | 1},
4414 in: map[time.Duration]string{time.Second: ""},
4415 want: `{"1000000000":""}`,
4416 }, {
4417 name: jsontest.Name("Time/Zero"),
4418 in: struct {
4419 T1 time.Time
4420 T2 time.Time `json:",format:RFC822"`
4421 T3 time.Time `json:",format:'2006-01-02'"`
4422 T4 time.Time `json:",omitzero"`
4423 T5 time.Time `json:",omitempty"`
4424 }{
4425 time.Time{},
4426 time.Time{},
4427 time.Time{},
4428 // This is zero according to time.Time.IsZero,
4429 // but non-zero according to reflect.Value.IsZero.
4430 time.Date(1, 1, 1, 0, 0, 0, 0, time.FixedZone("UTC", 0)),
4431 time.Time{},
4432 },
4433 want: `{"T1":"0001-01-01T00:00:00Z","T2":"01 Jan 01 00:00 UTC","T3":"0001-01-01","T5":"0001-01-01T00:00:00Z"}`,
4434 }, {
4435 name: jsontest.Name("Time/Format"),
4436 opts: []Options{jsontext.Multiline(true)},
4437 in: structTimeFormat{
4438 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4439 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4440 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4441 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4442 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4443 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4444 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4445 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4446 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4447 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4448 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4449 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4450 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4451 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4452 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4453 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4454 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4455 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4456 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4457 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4458 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4459 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4460 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4461 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4462 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4463 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4464 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4465 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4466 time.Date(1234, 1, 2, 3, 4, 5, 6, time.UTC),
4467 },
4468 want: `{
4469 "T1": "1234-01-02T03:04:05.000000006Z",
4470 "T2": "Mon Jan 2 03:04:05 1234",
4471 "T3": "Mon Jan 2 03:04:05 UTC 1234",
4472 "T4": "Mon Jan 02 03:04:05 +0000 1234",
4473 "T5": "02 Jan 34 03:04 UTC",
4474 "T6": "02 Jan 34 03:04 +0000",
4475 "T7": "Monday, 02-Jan-34 03:04:05 UTC",
4476 "T8": "Mon, 02 Jan 1234 03:04:05 UTC",
4477 "T9": "Mon, 02 Jan 1234 03:04:05 +0000",
4478 "T10": "1234-01-02T03:04:05Z",
4479 "T11": "1234-01-02T03:04:05.000000006Z",
4480 "T12": "3:04AM",
4481 "T13": "Jan 2 03:04:05",
4482 "T14": "Jan 2 03:04:05.000",
4483 "T15": "Jan 2 03:04:05.000000",
4484 "T16": "Jan 2 03:04:05.000000006",
4485 "T17": "1234-01-02 03:04:05",
4486 "T18": "1234-01-02",
4487 "T19": "03:04:05",
4488 "T20": "1234-01-02",
4489 "T21": "\"weird\"1234",
4490 "T22": -23225777754.999999994,
4491 "T23": "-23225777754.999999994",
4492 "T24": -23225777754999.999994,
4493 "T25": "-23225777754999.999994",
4494 "T26": -23225777754999999.994,
4495 "T27": "-23225777754999999.994",
4496 "T28": -23225777754999999994,
4497 "T29": "-23225777754999999994"
4498 }`,
4499 }, {
4500 name: jsontest.Name("Time/Format/Invalid"),
4501 in: struct {
4502 T time.Time `json:",format:UndefinedConstant"`
4503 }{},
4504 want: `{"T"`,
4505 wantErr: EM(errors.New(`invalid format flag "UndefinedConstant"`)).withPos(`{"T":`, "/T").withType(0, timeTimeType),
4506 }, {
4507 name: jsontest.Name("Time/Format/YearOverflow"),
4508 in: struct {
4509 T1 time.Time
4510 T2 time.Time
4511 }{
4512 time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second),
4513 time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC),
4514 },
4515 want: `{"T1":"9999-12-31T23:59:59Z","T2"`,
4516 wantErr: EM(errors.New(`year outside of range [0,9999]`)).withPos(`{"T1":"9999-12-31T23:59:59Z","T2":`, "/T2").withType(0, timeTimeType),
4517 }, {
4518 name: jsontest.Name("Time/Format/YearUnderflow"),
4519 in: struct {
4520 T1 time.Time
4521 T2 time.Time
4522 }{
4523 time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC),
4524 time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second),
4525 },
4526 want: `{"T1":"0000-01-01T00:00:00Z","T2"`,
4527 wantErr: EM(errors.New(`year outside of range [0,9999]`)).withPos(`{"T1":"0000-01-01T00:00:00Z","T2":`, "/T2").withType(0, timeTimeType),
4528 }, {
4529 name: jsontest.Name("Time/Format/YearUnderflow"),
4530 in: struct{ T time.Time }{time.Date(-998, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second)},
4531 want: `{"T"`,
4532 wantErr: EM(errors.New(`year outside of range [0,9999]`)).withPos(`{"T":`, "/T").withType(0, timeTimeType),
4533 }, {
4534 name: jsontest.Name("Time/Format/ZoneExact"),
4535 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 23*60*60+59*60))},
4536 want: `{"T":"2020-01-01T00:00:00+23:59"}`,
4537 }, {
4538 name: jsontest.Name("Time/Format/ZoneHourOverflow"),
4539 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 24*60*60))},
4540 want: `{"T"`,
4541 wantErr: EM(errors.New(`timezone hour outside of range [0,23]`)).withPos(`{"T":`, "/T").withType(0, timeTimeType),
4542 }, {
4543 name: jsontest.Name("Time/Format/ZoneHourOverflow"),
4544 in: struct{ T time.Time }{time.Date(2020, 1, 1, 0, 0, 0, 0, time.FixedZone("", 123*60*60))},
4545 want: `{"T"`,
4546 wantErr: EM(errors.New(`timezone hour outside of range [0,23]`)).withPos(`{"T":`, "/T").withType(0, timeTimeType),
4547 }, {
4548 name: jsontest.Name("Time/IgnoreInvalidFormat"),
4549 opts: []Options{invalidFormatOption},
4550 in: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
4551 want: `"2000-01-01T00:00:00Z"`,
4552 }}
4553
4554 for _, tt := range tests {
4555 t.Run(tt.name.Name, func(t *testing.T) {
4556 var got []byte
4557 var gotErr error
4558 if tt.useWriter {
4559 bb := new(struct{ bytes.Buffer }) // avoid optimizations with bytes.Buffer
4560 gotErr = MarshalWrite(bb, tt.in, tt.opts...)
4561 got = bb.Bytes()
4562 } else {
4563 got, gotErr = Marshal(tt.in, tt.opts...)
4564 }
4565 if tt.canonicalize {
4566 (*jsontext.Value)(&got).Canonicalize()
4567 }
4568 if string(got) != tt.want {
4569 t.Errorf("%s: Marshal output mismatch:\ngot %s\nwant %s", tt.name.Where, got, tt.want)
4570 }
4571 if !reflect.DeepEqual(gotErr, tt.wantErr) {
4572 t.Errorf("%s: Marshal error mismatch:\ngot %v\nwant %v", tt.name.Where, gotErr, tt.wantErr)
4573 }
4574 })
4575 }
4576 }
4577
4578 func TestUnmarshal(t *testing.T) {
4579 tests := []struct {
4580 name jsontest.CaseName
4581 opts []Options
4582 inBuf string
4583 inVal any
4584 want any
4585 wantErr error
4586 }{{
4587 name: jsontest.Name("Nil"),
4588 inBuf: `null`,
4589 wantErr: EU(internal.ErrNonNilReference),
4590 }, {
4591 name: jsontest.Name("NilPointer"),
4592 inBuf: `null`,
4593 inVal: (*string)(nil),
4594 want: (*string)(nil),
4595 wantErr: EU(internal.ErrNonNilReference).withType(0, T[*string]()),
4596 }, {
4597 name: jsontest.Name("NonPointer"),
4598 inBuf: `null`,
4599 inVal: "unchanged",
4600 want: "unchanged",
4601 wantErr: EU(internal.ErrNonNilReference).withType(0, T[string]()),
4602 }, {
4603 name: jsontest.Name("Bools/TrailingJunk"),
4604 inBuf: `falsetrue`,
4605 inVal: addr(true),
4606 want: addr(false),
4607 wantErr: newInvalidCharacterError("t", "after top-level value", len64(`false`), ""),
4608 }, {
4609 name: jsontest.Name("Bools/Null"),
4610 inBuf: `null`,
4611 inVal: addr(true),
4612 want: addr(false),
4613 }, {
4614 name: jsontest.Name("Bools"),
4615 inBuf: `[null,false,true]`,
4616 inVal: new([]bool),
4617 want: addr([]bool{false, false, true}),
4618 }, {
4619 name: jsontest.Name("Bools/Named"),
4620 inBuf: `[null,false,true]`,
4621 inVal: new([]namedBool),
4622 want: addr([]namedBool{false, false, true}),
4623 }, {
4624 name: jsontest.Name("Bools/Invalid/StringifiedFalse"),
4625 opts: []Options{StringifyNumbers(true)},
4626 inBuf: `"false"`,
4627 inVal: addr(true),
4628 want: addr(true),
4629 wantErr: EU(nil).withType('"', boolType),
4630 }, {
4631 name: jsontest.Name("Bools/Invalid/StringifiedTrue"),
4632 opts: []Options{StringifyNumbers(true)},
4633 inBuf: `"true"`,
4634 inVal: addr(true),
4635 want: addr(true),
4636 wantErr: EU(nil).withType('"', boolType),
4637 }, {
4638 name: jsontest.Name("Bools/StringifiedBool/True"),
4639 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4640 inBuf: `"true"`,
4641 inVal: addr(false),
4642 want: addr(true),
4643 }, {
4644 name: jsontest.Name("Bools/StringifiedBool/False"),
4645 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4646 inBuf: `"false"`,
4647 inVal: addr(true),
4648 want: addr(false),
4649 }, {
4650 name: jsontest.Name("Bools/StringifiedBool/InvalidWhitespace"),
4651 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4652 inBuf: `"false "`,
4653 inVal: addr(true),
4654 want: addr(true),
4655 wantErr: EU(strconv.ErrSyntax).withVal(`"false "`).withType('"', boolType),
4656 }, {
4657 name: jsontest.Name("Bools/StringifiedBool/InvalidBool"),
4658 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4659 inBuf: `false`,
4660 inVal: addr(true),
4661 want: addr(true),
4662 wantErr: EU(nil).withType('f', boolType),
4663 }, {
4664 name: jsontest.Name("Bools/Invalid/Number"),
4665 inBuf: `0`,
4666 inVal: addr(true),
4667 want: addr(true),
4668 wantErr: EU(nil).withType('0', boolType),
4669 }, {
4670 name: jsontest.Name("Bools/Invalid/String"),
4671 inBuf: `""`,
4672 inVal: addr(true),
4673 want: addr(true),
4674 wantErr: EU(nil).withType('"', boolType),
4675 }, {
4676 name: jsontest.Name("Bools/Invalid/Object"),
4677 inBuf: `{}`,
4678 inVal: addr(true),
4679 want: addr(true),
4680 wantErr: EU(nil).withType('{', boolType),
4681 }, {
4682 name: jsontest.Name("Bools/Invalid/Array"),
4683 inBuf: `[]`,
4684 inVal: addr(true),
4685 want: addr(true),
4686 wantErr: EU(nil).withType('[', boolType),
4687 }, {
4688 name: jsontest.Name("Bools/IgnoreInvalidFormat"),
4689 opts: []Options{invalidFormatOption},
4690 inBuf: `false`,
4691 inVal: addr(true),
4692 want: addr(false),
4693 }, {
4694 name: jsontest.Name("Strings/Null"),
4695 inBuf: `null`,
4696 inVal: addr("something"),
4697 want: addr(""),
4698 }, {
4699 name: jsontest.Name("Strings"),
4700 inBuf: `[null,"","hello","世界"]`,
4701 inVal: new([]string),
4702 want: addr([]string{"", "", "hello", "世界"}),
4703 }, {
4704 name: jsontest.Name("Strings/Escaped"),
4705 inBuf: `[null,"","\u0068\u0065\u006c\u006c\u006f","\u4e16\u754c"]`,
4706 inVal: new([]string),
4707 want: addr([]string{"", "", "hello", "世界"}),
4708 }, {
4709 name: jsontest.Name("Strings/Named"),
4710 inBuf: `[null,"","hello","世界"]`,
4711 inVal: new([]namedString),
4712 want: addr([]namedString{"", "", "hello", "世界"}),
4713 }, {
4714 name: jsontest.Name("Strings/Invalid/False"),
4715 inBuf: `false`,
4716 inVal: addr("nochange"),
4717 want: addr("nochange"),
4718 wantErr: EU(nil).withType('f', stringType),
4719 }, {
4720 name: jsontest.Name("Strings/Invalid/True"),
4721 inBuf: `true`,
4722 inVal: addr("nochange"),
4723 want: addr("nochange"),
4724 wantErr: EU(nil).withType('t', stringType),
4725 }, {
4726 name: jsontest.Name("Strings/Invalid/Object"),
4727 inBuf: `{}`,
4728 inVal: addr("nochange"),
4729 want: addr("nochange"),
4730 wantErr: EU(nil).withType('{', stringType),
4731 }, {
4732 name: jsontest.Name("Strings/Invalid/Array"),
4733 inBuf: `[]`,
4734 inVal: addr("nochange"),
4735 want: addr("nochange"),
4736 wantErr: EU(nil).withType('[', stringType),
4737 }, {
4738 name: jsontest.Name("Strings/IgnoreInvalidFormat"),
4739 opts: []Options{invalidFormatOption},
4740 inBuf: `"hello"`,
4741 inVal: addr("goodbye"),
4742 want: addr("hello"),
4743 }, {
4744 name: jsontest.Name("Strings/StringifiedString"),
4745 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4746 inBuf: `"\"foo\""`,
4747 inVal: new(string),
4748 want: addr("foo"),
4749 }, {
4750 name: jsontest.Name("Strings/StringifiedString/InvalidWhitespace"),
4751 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4752 inBuf: `"\"foo\" "`,
4753 inVal: new(string),
4754 want: new(string),
4755 wantErr: EU(newInvalidCharacterError(" ", "after string value", 0, "")).withType('"', stringType),
4756 }, {
4757 name: jsontest.Name("Strings/StringifiedString/InvalidString"),
4758 opts: []Options{jsonflags.StringifyBoolsAndStrings | 1},
4759 inBuf: `""`,
4760 inVal: new(string),
4761 want: new(string),
4762 wantErr: EU(&jsontext.SyntacticError{Err: io.ErrUnexpectedEOF}).withType('"', stringType),
4763 }, {
4764 name: jsontest.Name("Bytes/Null"),
4765 inBuf: `null`,
4766 inVal: addr([]byte("something")),
4767 want: addr([]byte(nil)),
4768 }, {
4769 name: jsontest.Name("Bytes"),
4770 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
4771 inVal: new([][]byte),
4772 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
4773 }, {
4774 name: jsontest.Name("Bytes/Large"),
4775 inBuf: `"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cgYW5kIGF0ZSB0aGUgaG9tZXdvcmsgdGhhdCBJIHNwZW50IHNvIG11Y2ggdGltZSBvbi4="`,
4776 inVal: new([]byte),
4777 want: addr([]byte("the quick brown fox jumped over the lazy dog and ate the homework that I spent so much time on.")),
4778 }, {
4779 name: jsontest.Name("Bytes/Reuse"),
4780 inBuf: `"AQID"`,
4781 inVal: addr([]byte("changed")),
4782 want: addr([]byte{1, 2, 3}),
4783 }, {
4784 name: jsontest.Name("Bytes/Escaped"),
4785 inBuf: `[null,"","\u0041\u0051\u003d\u003d","\u0041\u0051\u0049\u003d","\u0041\u0051\u0049\u0044"]`,
4786 inVal: new([][]byte),
4787 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
4788 }, {
4789 name: jsontest.Name("Bytes/Named"),
4790 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
4791 inVal: new([]namedBytes),
4792 want: addr([]namedBytes{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
4793 }, {
4794 name: jsontest.Name("Bytes/NotStringified"),
4795 opts: []Options{StringifyNumbers(true)},
4796 inBuf: `[null,"","AQ==","AQI=","AQID"]`,
4797 inVal: new([][]byte),
4798 want: addr([][]byte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
4799 }, {
4800 // NOTE: []namedByte is not assignable to []byte,
4801 // so the following should be treated as a slice of uints.
4802 name: jsontest.Name("Bytes/Invariant"),
4803 inBuf: `[null,[],[1],[1,2],[1,2,3]]`,
4804 inVal: new([][]namedByte),
4805 want: addr([][]namedByte{nil, {}, {1}, {1, 2}, {1, 2, 3}}),
4806 }, {
4807 // NOTE: This differs in behavior from v1,
4808 // but keeps the representation of slices and arrays more consistent.
4809 name: jsontest.Name("Bytes/ByteArray"),
4810 inBuf: `"aGVsbG8="`,
4811 inVal: new([5]byte),
4812 want: addr([5]byte{'h', 'e', 'l', 'l', 'o'}),
4813 }, {
4814 name: jsontest.Name("Bytes/ByteArray0/Valid"),
4815 inBuf: `""`,
4816 inVal: new([0]byte),
4817 want: addr([0]byte{}),
4818 }, {
4819 name: jsontest.Name("Bytes/ByteArray0/Invalid"),
4820 inBuf: `"A"`,
4821 inVal: new([0]byte),
4822 want: addr([0]byte{}),
4823 wantErr: EU(func() error {
4824 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("A"))
4825 return err
4826 }()).withType('"', T[[0]byte]()),
4827 }, {
4828 name: jsontest.Name("Bytes/ByteArray0/Overflow"),
4829 inBuf: `"AA=="`,
4830 inVal: new([0]byte),
4831 want: addr([0]byte{}),
4832 wantErr: EU(errors.New("decoded length of 1 mismatches array length of 0")).withType('"', T[[0]byte]()),
4833 }, {
4834 name: jsontest.Name("Bytes/ByteArray1/Valid"),
4835 inBuf: `"AQ=="`,
4836 inVal: new([1]byte),
4837 want: addr([1]byte{1}),
4838 }, {
4839 name: jsontest.Name("Bytes/ByteArray1/Invalid"),
4840 inBuf: `"$$=="`,
4841 inVal: new([1]byte),
4842 want: addr([1]byte{}),
4843 wantErr: EU(func() error {
4844 _, err := base64.StdEncoding.Decode(make([]byte, 1), []byte("$$=="))
4845 return err
4846 }()).withType('"', T[[1]byte]()),
4847 }, {
4848 name: jsontest.Name("Bytes/ByteArray1/Underflow"),
4849 inBuf: `""`,
4850 inVal: new([1]byte),
4851 want: addr([1]byte{}),
4852 wantErr: EU(errors.New("decoded length of 0 mismatches array length of 1")).withType('"', T[[1]byte]()),
4853 }, {
4854 name: jsontest.Name("Bytes/ByteArray1/Overflow"),
4855 inBuf: `"AQI="`,
4856 inVal: new([1]byte),
4857 want: addr([1]byte{1}),
4858 wantErr: EU(errors.New("decoded length of 2 mismatches array length of 1")).withType('"', T[[1]byte]()),
4859 }, {
4860 name: jsontest.Name("Bytes/ByteArray2/Valid"),
4861 inBuf: `"AQI="`,
4862 inVal: new([2]byte),
4863 want: addr([2]byte{1, 2}),
4864 }, {
4865 name: jsontest.Name("Bytes/ByteArray2/Invalid"),
4866 inBuf: `"$$$="`,
4867 inVal: new([2]byte),
4868 want: addr([2]byte{}),
4869 wantErr: EU(func() error {
4870 _, err := base64.StdEncoding.Decode(make([]byte, 2), []byte("$$$="))
4871 return err
4872 }()).withType('"', T[[2]byte]()),
4873 }, {
4874 name: jsontest.Name("Bytes/ByteArray2/Underflow"),
4875 inBuf: `"AQ=="`,
4876 inVal: new([2]byte),
4877 want: addr([2]byte{1, 0}),
4878 wantErr: EU(errors.New("decoded length of 1 mismatches array length of 2")).withType('"', T[[2]byte]()),
4879 }, {
4880 name: jsontest.Name("Bytes/ByteArray2/Underflow/Allowed"),
4881 opts: []Options{jsonflags.UnmarshalArrayFromAnyLength | 1},
4882 inBuf: `"AQ=="`,
4883 inVal: new([2]byte),
4884 want: addr([2]byte{1, 0}),
4885 }, {
4886 name: jsontest.Name("Bytes/ByteArray2/Overflow"),
4887 inBuf: `"AQID"`,
4888 inVal: new([2]byte),
4889 want: addr([2]byte{1, 2}),
4890 wantErr: EU(errors.New("decoded length of 3 mismatches array length of 2")).withType('"', T[[2]byte]()),
4891 }, {
4892 name: jsontest.Name("Bytes/ByteArray2/Overflow/Allowed"),
4893 opts: []Options{jsonflags.UnmarshalArrayFromAnyLength | 1},
4894 inBuf: `"AQID"`,
4895 inVal: new([2]byte),
4896 want: addr([2]byte{1, 2}),
4897 }, {
4898 name: jsontest.Name("Bytes/ByteArray3/Valid"),
4899 inBuf: `"AQID"`,
4900 inVal: new([3]byte),
4901 want: addr([3]byte{1, 2, 3}),
4902 }, {
4903 name: jsontest.Name("Bytes/ByteArray3/Invalid"),
4904 inBuf: `"$$$$"`,
4905 inVal: new([3]byte),
4906 want: addr([3]byte{}),
4907 wantErr: EU(func() error {
4908 _, err := base64.StdEncoding.Decode(make([]byte, 3), []byte("$$$$"))
4909 return err
4910 }()).withType('"', T[[3]byte]()),
4911 }, {
4912 name: jsontest.Name("Bytes/ByteArray3/Underflow"),
4913 inBuf: `"AQI="`,
4914 inVal: addr([3]byte{0xff, 0xff, 0xff}),
4915 want: addr([3]byte{1, 2, 0}),
4916 wantErr: EU(errors.New("decoded length of 2 mismatches array length of 3")).withType('"', T[[3]byte]()),
4917 }, {
4918 name: jsontest.Name("Bytes/ByteArray3/Overflow"),
4919 inBuf: `"AQIDAQ=="`,
4920 inVal: new([3]byte),
4921 want: addr([3]byte{1, 2, 3}),
4922 wantErr: EU(errors.New("decoded length of 4 mismatches array length of 3")).withType('"', T[[3]byte]()),
4923 }, {
4924 name: jsontest.Name("Bytes/ByteArray4/Valid"),
4925 inBuf: `"AQIDBA=="`,
4926 inVal: new([4]byte),
4927 want: addr([4]byte{1, 2, 3, 4}),
4928 }, {
4929 name: jsontest.Name("Bytes/ByteArray4/Invalid"),
4930 inBuf: `"$$$$$$=="`,
4931 inVal: new([4]byte),
4932 want: addr([4]byte{}),
4933 wantErr: EU(func() error {
4934 _, err := base64.StdEncoding.Decode(make([]byte, 4), []byte("$$$$$$=="))
4935 return err
4936 }()).withType('"', T[[4]byte]()),
4937 }, {
4938 name: jsontest.Name("Bytes/ByteArray4/Underflow"),
4939 inBuf: `"AQID"`,
4940 inVal: new([4]byte),
4941 want: addr([4]byte{1, 2, 3, 0}),
4942 wantErr: EU(errors.New("decoded length of 3 mismatches array length of 4")).withType('"', T[[4]byte]()),
4943 }, {
4944 name: jsontest.Name("Bytes/ByteArray4/Overflow"),
4945 inBuf: `"AQIDBAU="`,
4946 inVal: new([4]byte),
4947 want: addr([4]byte{1, 2, 3, 4}),
4948 wantErr: EU(errors.New("decoded length of 5 mismatches array length of 4")).withType('"', T[[4]byte]()),
4949 }, {
4950 // NOTE: []namedByte is not assignable to []byte,
4951 // so the following should be treated as a array of uints.
4952 name: jsontest.Name("Bytes/NamedByteArray"),
4953 inBuf: `[104,101,108,108,111]`,
4954 inVal: new([5]namedByte),
4955 want: addr([5]namedByte{'h', 'e', 'l', 'l', 'o'}),
4956 }, {
4957 name: jsontest.Name("Bytes/Valid/Denormalized"),
4958 inBuf: `"AR=="`,
4959 inVal: new([]byte),
4960 want: addr([]byte{1}),
4961 }, {
4962 name: jsontest.Name("Bytes/Invalid/Unpadded1"),
4963 inBuf: `"AQ="`,
4964 inVal: addr([]byte("nochange")),
4965 want: addr([]byte("nochange")),
4966 wantErr: EU(func() error {
4967 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("AQ="))
4968 return err
4969 }()).withType('"', bytesType),
4970 }, {
4971 name: jsontest.Name("Bytes/Invalid/Unpadded2"),
4972 inBuf: `"AQ"`,
4973 inVal: addr([]byte("nochange")),
4974 want: addr([]byte("nochange")),
4975 wantErr: EU(func() error {
4976 _, err := base64.StdEncoding.Decode(make([]byte, 0), []byte("AQ"))
4977 return err
4978 }()).withType('"', bytesType),
4979 }, {
4980 name: jsontest.Name("Bytes/Invalid/Character"),
4981 inBuf: `"@@@@"`,
4982 inVal: addr([]byte("nochange")),
4983 want: addr([]byte("nochange")),
4984 wantErr: EU(func() error {
4985 _, err := base64.StdEncoding.Decode(make([]byte, 3), []byte("@@@@"))
4986 return err
4987 }()).withType('"', bytesType),
4988 }, {
4989 name: jsontest.Name("Bytes/Invalid/Bool"),
4990 inBuf: `true`,
4991 inVal: addr([]byte("nochange")),
4992 want: addr([]byte("nochange")),
4993 wantErr: EU(nil).withType('t', bytesType),
4994 }, {
4995 name: jsontest.Name("Bytes/Invalid/Number"),
4996 inBuf: `0`,
4997 inVal: addr([]byte("nochange")),
4998 want: addr([]byte("nochange")),
4999 wantErr: EU(nil).withType('0', bytesType),
5000 }, {
5001 name: jsontest.Name("Bytes/Invalid/Object"),
5002 inBuf: `{}`,
5003 inVal: addr([]byte("nochange")),
5004 want: addr([]byte("nochange")),
5005 wantErr: EU(nil).withType('{', bytesType),
5006 }, {
5007 name: jsontest.Name("Bytes/Invalid/Array"),
5008 inBuf: `[]`,
5009 inVal: addr([]byte("nochange")),
5010 want: addr([]byte("nochange")),
5011 wantErr: EU(nil).withType('[', bytesType),
5012 }, {
5013 name: jsontest.Name("Bytes/IgnoreInvalidFormat"),
5014 opts: []Options{invalidFormatOption},
5015 inBuf: `"aGVsbG8="`,
5016 inVal: new([]byte),
5017 want: addr([]byte("hello")),
5018 }, {
5019 name: jsontest.Name("Ints/Null"),
5020 inBuf: `null`,
5021 inVal: addr(int(1)),
5022 want: addr(int(0)),
5023 }, {
5024 name: jsontest.Name("Ints/Int"),
5025 inBuf: `1`,
5026 inVal: addr(int(0)),
5027 want: addr(int(1)),
5028 }, {
5029 name: jsontest.Name("Ints/Int8/MinOverflow"),
5030 inBuf: `-129`,
5031 inVal: addr(int8(-1)),
5032 want: addr(int8(-1)),
5033 wantErr: EU(strconv.ErrRange).withVal(`-129`).withType('0', T[int8]()),
5034 }, {
5035 name: jsontest.Name("Ints/Int8/Min"),
5036 inBuf: `-128`,
5037 inVal: addr(int8(0)),
5038 want: addr(int8(-128)),
5039 }, {
5040 name: jsontest.Name("Ints/Int8/Max"),
5041 inBuf: `127`,
5042 inVal: addr(int8(0)),
5043 want: addr(int8(127)),
5044 }, {
5045 name: jsontest.Name("Ints/Int8/MaxOverflow"),
5046 inBuf: `128`,
5047 inVal: addr(int8(-1)),
5048 want: addr(int8(-1)),
5049 wantErr: EU(strconv.ErrRange).withVal(`128`).withType('0', T[int8]()),
5050 }, {
5051 name: jsontest.Name("Ints/Int16/MinOverflow"),
5052 inBuf: `-32769`,
5053 inVal: addr(int16(-1)),
5054 want: addr(int16(-1)),
5055 wantErr: EU(strconv.ErrRange).withVal(`-32769`).withType('0', T[int16]()),
5056 }, {
5057 name: jsontest.Name("Ints/Int16/Min"),
5058 inBuf: `-32768`,
5059 inVal: addr(int16(0)),
5060 want: addr(int16(-32768)),
5061 }, {
5062 name: jsontest.Name("Ints/Int16/Max"),
5063 inBuf: `32767`,
5064 inVal: addr(int16(0)),
5065 want: addr(int16(32767)),
5066 }, {
5067 name: jsontest.Name("Ints/Int16/MaxOverflow"),
5068 inBuf: `32768`,
5069 inVal: addr(int16(-1)),
5070 want: addr(int16(-1)),
5071 wantErr: EU(strconv.ErrRange).withVal(`32768`).withType('0', T[int16]()),
5072 }, {
5073 name: jsontest.Name("Ints/Int32/MinOverflow"),
5074 inBuf: `-2147483649`,
5075 inVal: addr(int32(-1)),
5076 want: addr(int32(-1)),
5077 wantErr: EU(strconv.ErrRange).withVal(`-2147483649`).withType('0', T[int32]()),
5078 }, {
5079 name: jsontest.Name("Ints/Int32/Min"),
5080 inBuf: `-2147483648`,
5081 inVal: addr(int32(0)),
5082 want: addr(int32(-2147483648)),
5083 }, {
5084 name: jsontest.Name("Ints/Int32/Max"),
5085 inBuf: `2147483647`,
5086 inVal: addr(int32(0)),
5087 want: addr(int32(2147483647)),
5088 }, {
5089 name: jsontest.Name("Ints/Int32/MaxOverflow"),
5090 inBuf: `2147483648`,
5091 inVal: addr(int32(-1)),
5092 want: addr(int32(-1)),
5093 wantErr: EU(strconv.ErrRange).withVal(`2147483648`).withType('0', T[int32]()),
5094 }, {
5095 name: jsontest.Name("Ints/Int64/MinOverflow"),
5096 inBuf: `-9223372036854775809`,
5097 inVal: addr(int64(-1)),
5098 want: addr(int64(-1)),
5099 wantErr: EU(strconv.ErrRange).withVal(`-9223372036854775809`).withType('0', T[int64]()),
5100 }, {
5101 name: jsontest.Name("Ints/Int64/Min"),
5102 inBuf: `-9223372036854775808`,
5103 inVal: addr(int64(0)),
5104 want: addr(int64(-9223372036854775808)),
5105 }, {
5106 name: jsontest.Name("Ints/Int64/Max"),
5107 inBuf: `9223372036854775807`,
5108 inVal: addr(int64(0)),
5109 want: addr(int64(9223372036854775807)),
5110 }, {
5111 name: jsontest.Name("Ints/Int64/MaxOverflow"),
5112 inBuf: `9223372036854775808`,
5113 inVal: addr(int64(-1)),
5114 want: addr(int64(-1)),
5115 wantErr: EU(strconv.ErrRange).withVal(`9223372036854775808`).withType('0', T[int64]()),
5116 }, {
5117 name: jsontest.Name("Ints/Named"),
5118 inBuf: `-6464`,
5119 inVal: addr(namedInt64(0)),
5120 want: addr(namedInt64(-6464)),
5121 }, {
5122 name: jsontest.Name("Ints/Stringified"),
5123 opts: []Options{StringifyNumbers(true)},
5124 inBuf: `"-6464"`,
5125 inVal: new(int),
5126 want: addr(int(-6464)),
5127 }, {
5128 name: jsontest.Name("Ints/Stringified/Invalid"),
5129 opts: []Options{StringifyNumbers(true)},
5130 inBuf: `-6464`,
5131 inVal: new(int),
5132 want: new(int),
5133 wantErr: EU(nil).withType('0', T[int]()),
5134 }, {
5135 name: jsontest.Name("Ints/Stringified/LeadingZero"),
5136 opts: []Options{StringifyNumbers(true)},
5137 inBuf: `"00"`,
5138 inVal: addr(int(-1)),
5139 want: addr(int(-1)),
5140 wantErr: EU(strconv.ErrSyntax).withVal(`"00"`).withType('"', T[int]()),
5141 }, {
5142 name: jsontest.Name("Ints/Escaped"),
5143 opts: []Options{StringifyNumbers(true)},
5144 inBuf: `"\u002d\u0036\u0034\u0036\u0034"`,
5145 inVal: new(int),
5146 want: addr(int(-6464)),
5147 }, {
5148 name: jsontest.Name("Ints/Valid/NegativeZero"),
5149 inBuf: `-0`,
5150 inVal: addr(int(1)),
5151 want: addr(int(0)),
5152 }, {
5153 name: jsontest.Name("Ints/Invalid/Fraction"),
5154 inBuf: `1.0`,
5155 inVal: addr(int(-1)),
5156 want: addr(int(-1)),
5157 wantErr: EU(strconv.ErrSyntax).withVal(`1.0`).withType('0', T[int]()),
5158 }, {
5159 name: jsontest.Name("Ints/Invalid/Exponent"),
5160 inBuf: `1e0`,
5161 inVal: addr(int(-1)),
5162 want: addr(int(-1)),
5163 wantErr: EU(strconv.ErrSyntax).withVal(`1e0`).withType('0', T[int]()),
5164 }, {
5165 name: jsontest.Name("Ints/Invalid/StringifiedFraction"),
5166 opts: []Options{StringifyNumbers(true)},
5167 inBuf: `"1.0"`,
5168 inVal: addr(int(-1)),
5169 want: addr(int(-1)),
5170 wantErr: EU(strconv.ErrSyntax).withVal(`"1.0"`).withType('"', T[int]()),
5171 }, {
5172 name: jsontest.Name("Ints/Invalid/StringifiedExponent"),
5173 opts: []Options{StringifyNumbers(true)},
5174 inBuf: `"1e0"`,
5175 inVal: addr(int(-1)),
5176 want: addr(int(-1)),
5177 wantErr: EU(strconv.ErrSyntax).withVal(`"1e0"`).withType('"', T[int]()),
5178 }, {
5179 name: jsontest.Name("Ints/Invalid/Overflow"),
5180 inBuf: `100000000000000000000000000000`,
5181 inVal: addr(int(-1)),
5182 want: addr(int(-1)),
5183 wantErr: EU(strconv.ErrRange).withVal(`100000000000000000000000000000`).withType('0', T[int]()),
5184 }, {
5185 name: jsontest.Name("Ints/Invalid/OverflowSyntax"),
5186 opts: []Options{StringifyNumbers(true)},
5187 inBuf: `"100000000000000000000000000000x"`,
5188 inVal: addr(int(-1)),
5189 want: addr(int(-1)),
5190 wantErr: EU(strconv.ErrSyntax).withVal(`"100000000000000000000000000000x"`).withType('"', T[int]()),
5191 }, {
5192 name: jsontest.Name("Ints/Invalid/Whitespace"),
5193 opts: []Options{StringifyNumbers(true)},
5194 inBuf: `"0 "`,
5195 inVal: addr(int(-1)),
5196 want: addr(int(-1)),
5197 wantErr: EU(strconv.ErrSyntax).withVal(`"0 "`).withType('"', T[int]()),
5198 }, {
5199 name: jsontest.Name("Ints/Invalid/Bool"),
5200 inBuf: `true`,
5201 inVal: addr(int(-1)),
5202 want: addr(int(-1)),
5203 wantErr: EU(nil).withType('t', T[int]()),
5204 }, {
5205 name: jsontest.Name("Ints/Invalid/String"),
5206 inBuf: `"0"`,
5207 inVal: addr(int(-1)),
5208 want: addr(int(-1)),
5209 wantErr: EU(nil).withType('"', T[int]()),
5210 }, {
5211 name: jsontest.Name("Ints/Invalid/Object"),
5212 inBuf: `{}`,
5213 inVal: addr(int(-1)),
5214 want: addr(int(-1)),
5215 wantErr: EU(nil).withType('{', T[int]()),
5216 }, {
5217 name: jsontest.Name("Ints/Invalid/Array"),
5218 inBuf: `[]`,
5219 inVal: addr(int(-1)),
5220 want: addr(int(-1)),
5221 wantErr: EU(nil).withType('[', T[int]()),
5222 }, {
5223 name: jsontest.Name("Ints/IgnoreInvalidFormat"),
5224 opts: []Options{invalidFormatOption},
5225 inBuf: `1`,
5226 inVal: addr(int(0)),
5227 want: addr(int(1)),
5228 }, {
5229 name: jsontest.Name("Uints/Null"),
5230 inBuf: `null`,
5231 inVal: addr(uint(1)),
5232 want: addr(uint(0)),
5233 }, {
5234 name: jsontest.Name("Uints/Uint"),
5235 inBuf: `1`,
5236 inVal: addr(uint(0)),
5237 want: addr(uint(1)),
5238 }, {
5239 name: jsontest.Name("Uints/Uint8/Min"),
5240 inBuf: `0`,
5241 inVal: addr(uint8(1)),
5242 want: addr(uint8(0)),
5243 }, {
5244 name: jsontest.Name("Uints/Uint8/Max"),
5245 inBuf: `255`,
5246 inVal: addr(uint8(0)),
5247 want: addr(uint8(255)),
5248 }, {
5249 name: jsontest.Name("Uints/Uint8/MaxOverflow"),
5250 inBuf: `256`,
5251 inVal: addr(uint8(1)),
5252 want: addr(uint8(1)),
5253 wantErr: EU(strconv.ErrRange).withVal(`256`).withType('0', T[uint8]()),
5254 }, {
5255 name: jsontest.Name("Uints/Uint16/Min"),
5256 inBuf: `0`,
5257 inVal: addr(uint16(1)),
5258 want: addr(uint16(0)),
5259 }, {
5260 name: jsontest.Name("Uints/Uint16/Max"),
5261 inBuf: `65535`,
5262 inVal: addr(uint16(0)),
5263 want: addr(uint16(65535)),
5264 }, {
5265 name: jsontest.Name("Uints/Uint16/MaxOverflow"),
5266 inBuf: `65536`,
5267 inVal: addr(uint16(1)),
5268 want: addr(uint16(1)),
5269 wantErr: EU(strconv.ErrRange).withVal(`65536`).withType('0', T[uint16]()),
5270 }, {
5271 name: jsontest.Name("Uints/Uint32/Min"),
5272 inBuf: `0`,
5273 inVal: addr(uint32(1)),
5274 want: addr(uint32(0)),
5275 }, {
5276 name: jsontest.Name("Uints/Uint32/Max"),
5277 inBuf: `4294967295`,
5278 inVal: addr(uint32(0)),
5279 want: addr(uint32(4294967295)),
5280 }, {
5281 name: jsontest.Name("Uints/Uint32/MaxOverflow"),
5282 inBuf: `4294967296`,
5283 inVal: addr(uint32(1)),
5284 want: addr(uint32(1)),
5285 wantErr: EU(strconv.ErrRange).withVal(`4294967296`).withType('0', T[uint32]()),
5286 }, {
5287 name: jsontest.Name("Uints/Uint64/Min"),
5288 inBuf: `0`,
5289 inVal: addr(uint64(1)),
5290 want: addr(uint64(0)),
5291 }, {
5292 name: jsontest.Name("Uints/Uint64/Max"),
5293 inBuf: `18446744073709551615`,
5294 inVal: addr(uint64(0)),
5295 want: addr(uint64(18446744073709551615)),
5296 }, {
5297 name: jsontest.Name("Uints/Uint64/MaxOverflow"),
5298 inBuf: `18446744073709551616`,
5299 inVal: addr(uint64(1)),
5300 want: addr(uint64(1)),
5301 wantErr: EU(strconv.ErrRange).withVal(`18446744073709551616`).withType('0', T[uint64]()),
5302 }, {
5303 name: jsontest.Name("Uints/Uintptr"),
5304 inBuf: `1`,
5305 inVal: addr(uintptr(0)),
5306 want: addr(uintptr(1)),
5307 }, {
5308 name: jsontest.Name("Uints/Named"),
5309 inBuf: `6464`,
5310 inVal: addr(namedUint64(0)),
5311 want: addr(namedUint64(6464)),
5312 }, {
5313 name: jsontest.Name("Uints/Stringified"),
5314 opts: []Options{StringifyNumbers(true)},
5315 inBuf: `"6464"`,
5316 inVal: new(uint),
5317 want: addr(uint(6464)),
5318 }, {
5319 name: jsontest.Name("Uints/Stringified/Invalid"),
5320 opts: []Options{StringifyNumbers(true)},
5321 inBuf: `6464`,
5322 inVal: new(uint),
5323 want: new(uint),
5324 wantErr: EU(nil).withType('0', T[uint]()),
5325 }, {
5326 name: jsontest.Name("Uints/Stringified/LeadingZero"),
5327 opts: []Options{StringifyNumbers(true)},
5328 inBuf: `"00"`,
5329 inVal: addr(uint(1)),
5330 want: addr(uint(1)),
5331 wantErr: EU(strconv.ErrSyntax).withVal(`"00"`).withType('"', T[uint]()),
5332 }, {
5333 name: jsontest.Name("Uints/Escaped"),
5334 opts: []Options{StringifyNumbers(true)},
5335 inBuf: `"\u0036\u0034\u0036\u0034"`,
5336 inVal: new(uint),
5337 want: addr(uint(6464)),
5338 }, {
5339 name: jsontest.Name("Uints/Invalid/NegativeOne"),
5340 inBuf: `-1`,
5341 inVal: addr(uint(1)),
5342 want: addr(uint(1)),
5343 wantErr: EU(strconv.ErrSyntax).withVal(`-1`).withType('0', T[uint]()),
5344 }, {
5345 name: jsontest.Name("Uints/Invalid/NegativeZero"),
5346 inBuf: `-0`,
5347 inVal: addr(uint(1)),
5348 want: addr(uint(1)),
5349 wantErr: EU(strconv.ErrSyntax).withVal(`-0`).withType('0', T[uint]()),
5350 }, {
5351 name: jsontest.Name("Uints/Invalid/Fraction"),
5352 inBuf: `1.0`,
5353 inVal: addr(uint(10)),
5354 want: addr(uint(10)),
5355 wantErr: EU(strconv.ErrSyntax).withVal(`1.0`).withType('0', T[uint]()),
5356 }, {
5357 name: jsontest.Name("Uints/Invalid/Exponent"),
5358 inBuf: `1e0`,
5359 inVal: addr(uint(10)),
5360 want: addr(uint(10)),
5361 wantErr: EU(strconv.ErrSyntax).withVal(`1e0`).withType('0', T[uint]()),
5362 }, {
5363 name: jsontest.Name("Uints/Invalid/StringifiedFraction"),
5364 opts: []Options{StringifyNumbers(true)},
5365 inBuf: `"1.0"`,
5366 inVal: addr(uint(10)),
5367 want: addr(uint(10)),
5368 wantErr: EU(strconv.ErrSyntax).withVal(`"1.0"`).withType('"', T[uint]()),
5369 }, {
5370 name: jsontest.Name("Uints/Invalid/StringifiedExponent"),
5371 opts: []Options{StringifyNumbers(true)},
5372 inBuf: `"1e0"`,
5373 inVal: addr(uint(10)),
5374 want: addr(uint(10)),
5375 wantErr: EU(strconv.ErrSyntax).withVal(`"1e0"`).withType('"', T[uint]()),
5376 }, {
5377 name: jsontest.Name("Uints/Invalid/Overflow"),
5378 inBuf: `100000000000000000000000000000`,
5379 inVal: addr(uint(1)),
5380 want: addr(uint(1)),
5381 wantErr: EU(strconv.ErrRange).withVal(`100000000000000000000000000000`).withType('0', T[uint]()),
5382 }, {
5383 name: jsontest.Name("Uints/Invalid/OverflowSyntax"),
5384 opts: []Options{StringifyNumbers(true)},
5385 inBuf: `"100000000000000000000000000000x"`,
5386 inVal: addr(uint(1)),
5387 want: addr(uint(1)),
5388 wantErr: EU(strconv.ErrSyntax).withVal(`"100000000000000000000000000000x"`).withType('"', T[uint]()),
5389 }, {
5390 name: jsontest.Name("Uints/Invalid/Whitespace"),
5391 opts: []Options{StringifyNumbers(true)},
5392 inBuf: `"0 "`,
5393 inVal: addr(uint(1)),
5394 want: addr(uint(1)),
5395 wantErr: EU(strconv.ErrSyntax).withVal(`"0 "`).withType('"', T[uint]()),
5396 }, {
5397 name: jsontest.Name("Uints/Invalid/Bool"),
5398 inBuf: `true`,
5399 inVal: addr(uint(1)),
5400 want: addr(uint(1)),
5401 wantErr: EU(nil).withType('t', T[uint]()),
5402 }, {
5403 name: jsontest.Name("Uints/Invalid/String"),
5404 inBuf: `"0"`,
5405 inVal: addr(uint(1)),
5406 want: addr(uint(1)),
5407 wantErr: EU(nil).withType('"', T[uint]()),
5408 }, {
5409 name: jsontest.Name("Uints/Invalid/Object"),
5410 inBuf: `{}`,
5411 inVal: addr(uint(1)),
5412 want: addr(uint(1)),
5413 wantErr: EU(nil).withType('{', T[uint]()),
5414 }, {
5415 name: jsontest.Name("Uints/Invalid/Array"),
5416 inBuf: `[]`,
5417 inVal: addr(uint(1)),
5418 want: addr(uint(1)),
5419 wantErr: EU(nil).withType('[', T[uint]()),
5420 }, {
5421 name: jsontest.Name("Uints/IgnoreInvalidFormat"),
5422 opts: []Options{invalidFormatOption},
5423 inBuf: `1`,
5424 inVal: addr(uint(0)),
5425 want: addr(uint(1)),
5426 }, {
5427 name: jsontest.Name("Floats/Null"),
5428 inBuf: `null`,
5429 inVal: addr(float64(64.64)),
5430 want: addr(float64(0)),
5431 }, {
5432 name: jsontest.Name("Floats/Float32/Pi"),
5433 inBuf: `3.14159265358979323846264338327950288419716939937510582097494459`,
5434 inVal: addr(float32(32.32)),
5435 want: addr(float32(math.Pi)),
5436 }, {
5437 name: jsontest.Name("Floats/Float32/Underflow"),
5438 inBuf: `1e-1000`,
5439 inVal: addr(float32(32.32)),
5440 want: addr(float32(0)),
5441 }, {
5442 name: jsontest.Name("Floats/Float32/Overflow"),
5443 inBuf: `-1e1000`,
5444 inVal: addr(float32(32.32)),
5445 want: addr(float32(-math.MaxFloat32)),
5446 wantErr: EU(strconv.ErrRange).withVal(`-1e1000`).withType('0', T[float32]()),
5447 }, {
5448 name: jsontest.Name("Floats/Float64/Pi"),
5449 inBuf: `3.14159265358979323846264338327950288419716939937510582097494459`,
5450 inVal: addr(float64(64.64)),
5451 want: addr(float64(math.Pi)),
5452 }, {
5453 name: jsontest.Name("Floats/Float64/Underflow"),
5454 inBuf: `1e-1000`,
5455 inVal: addr(float64(64.64)),
5456 want: addr(float64(0)),
5457 }, {
5458 name: jsontest.Name("Floats/Float64/Overflow"),
5459 inBuf: `-1e1000`,
5460 inVal: addr(float64(64.64)),
5461 want: addr(float64(-math.MaxFloat64)),
5462 wantErr: EU(strconv.ErrRange).withVal(`-1e1000`).withType('0', T[float64]()),
5463 }, {
5464 name: jsontest.Name("Floats/Any/Overflow"),
5465 inBuf: `1e1000`,
5466 inVal: new(any),
5467 want: addr(any(float64(math.MaxFloat64))),
5468 wantErr: EU(strconv.ErrRange).withVal(`1e1000`).withType('0', T[float64]()),
5469 }, {
5470 name: jsontest.Name("Floats/Named"),
5471 inBuf: `64.64`,
5472 inVal: addr(namedFloat64(0)),
5473 want: addr(namedFloat64(64.64)),
5474 }, {
5475 name: jsontest.Name("Floats/Stringified"),
5476 opts: []Options{StringifyNumbers(true)},
5477 inBuf: `"64.64"`,
5478 inVal: new(float64),
5479 want: addr(float64(64.64)),
5480 }, {
5481 name: jsontest.Name("Floats/Stringified/Invalid"),
5482 opts: []Options{StringifyNumbers(true)},
5483 inBuf: `64.64`,
5484 inVal: new(float64),
5485 want: new(float64),
5486 wantErr: EU(nil).withType('0', T[float64]()),
5487 }, {
5488 name: jsontest.Name("Floats/Escaped"),
5489 opts: []Options{StringifyNumbers(true)},
5490 inBuf: `"\u0036\u0034\u002e\u0036\u0034"`,
5491 inVal: new(float64),
5492 want: addr(float64(64.64)),
5493 }, {
5494 name: jsontest.Name("Floats/Invalid/NaN"),
5495 opts: []Options{StringifyNumbers(true)},
5496 inBuf: `"NaN"`,
5497 inVal: addr(float64(64.64)),
5498 want: addr(float64(64.64)),
5499 wantErr: EU(strconv.ErrSyntax).withVal(`"NaN"`).withType('"', float64Type),
5500 }, {
5501 name: jsontest.Name("Floats/Invalid/Infinity"),
5502 opts: []Options{StringifyNumbers(true)},
5503 inBuf: `"Infinity"`,
5504 inVal: addr(float64(64.64)),
5505 want: addr(float64(64.64)),
5506 wantErr: EU(strconv.ErrSyntax).withVal(`"Infinity"`).withType('"', float64Type),
5507 }, {
5508 name: jsontest.Name("Floats/Invalid/Whitespace"),
5509 opts: []Options{StringifyNumbers(true)},
5510 inBuf: `"1 "`,
5511 inVal: addr(float64(64.64)),
5512 want: addr(float64(64.64)),
5513 wantErr: EU(strconv.ErrSyntax).withVal(`"1 "`).withType('"', float64Type),
5514 }, {
5515 name: jsontest.Name("Floats/Invalid/GoSyntax"),
5516 opts: []Options{StringifyNumbers(true)},
5517 inBuf: `"1p-2"`,
5518 inVal: addr(float64(64.64)),
5519 want: addr(float64(64.64)),
5520 wantErr: EU(strconv.ErrSyntax).withVal(`"1p-2"`).withType('"', float64Type),
5521 }, {
5522 name: jsontest.Name("Floats/Invalid/Bool"),
5523 inBuf: `true`,
5524 inVal: addr(float64(64.64)),
5525 want: addr(float64(64.64)),
5526 wantErr: EU(nil).withType('t', float64Type),
5527 }, {
5528 name: jsontest.Name("Floats/Invalid/String"),
5529 inBuf: `"0"`,
5530 inVal: addr(float64(64.64)),
5531 want: addr(float64(64.64)),
5532 wantErr: EU(nil).withType('"', float64Type),
5533 }, {
5534 name: jsontest.Name("Floats/Invalid/Object"),
5535 inBuf: `{}`,
5536 inVal: addr(float64(64.64)),
5537 want: addr(float64(64.64)),
5538 wantErr: EU(nil).withType('{', float64Type),
5539 }, {
5540 name: jsontest.Name("Floats/Invalid/Array"),
5541 inBuf: `[]`,
5542 inVal: addr(float64(64.64)),
5543 want: addr(float64(64.64)),
5544 wantErr: EU(nil).withType('[', float64Type),
5545 }, {
5546 name: jsontest.Name("Floats/IgnoreInvalidFormat"),
5547 opts: []Options{invalidFormatOption},
5548 inBuf: `1`,
5549 inVal: addr(float64(0)),
5550 want: addr(float64(1)),
5551 }, {
5552 name: jsontest.Name("Maps/Null"),
5553 inBuf: `null`,
5554 inVal: addr(map[string]string{"key": "value"}),
5555 want: new(map[string]string),
5556 }, {
5557 name: jsontest.Name("Maps/InvalidKey/Bool"),
5558 inBuf: `{"true":"false"}`,
5559 inVal: new(map[bool]bool),
5560 want: addr(make(map[bool]bool)),
5561 wantErr: EU(nil).withPos(`{`, "/true").withType('"', boolType),
5562 }, {
5563 name: jsontest.Name("Maps/InvalidKey/NamedBool"),
5564 inBuf: `{"true":"false"}`,
5565 inVal: new(map[namedBool]bool),
5566 want: addr(make(map[namedBool]bool)),
5567 wantErr: EU(nil).withPos(`{`, "/true").withType('"', T[namedBool]()),
5568 }, {
5569 name: jsontest.Name("Maps/InvalidKey/Array"),
5570 inBuf: `{"key":"value"}`,
5571 inVal: new(map[[1]string]string),
5572 want: addr(make(map[[1]string]string)),
5573 wantErr: EU(nil).withPos(`{`, "/key").withType('"', T[[1]string]()),
5574 }, {
5575 name: jsontest.Name("Maps/InvalidKey/Channel"),
5576 inBuf: `{"key":"value"}`,
5577 inVal: new(map[chan string]string),
5578 want: addr(make(map[chan string]string)),
5579 wantErr: EU(nil).withPos(`{`, "").withType(0, T[chan string]()),
5580 }, {
5581 name: jsontest.Name("Maps/ValidKey/Int"),
5582 inBuf: `{"0":0,"-1":1,"2":2,"-3":3}`,
5583 inVal: new(map[int]int),
5584 want: addr(map[int]int{0: 0, -1: 1, 2: 2, -3: 3}),
5585 }, {
5586 name: jsontest.Name("Maps/ValidKey/NamedInt"),
5587 inBuf: `{"0":0,"-1":1,"2":2,"-3":3}`,
5588 inVal: new(map[namedInt64]int),
5589 want: addr(map[namedInt64]int{0: 0, -1: 1, 2: 2, -3: 3}),
5590 }, {
5591 name: jsontest.Name("Maps/ValidKey/Uint"),
5592 inBuf: `{"0":0,"1":1,"2":2,"3":3}`,
5593 inVal: new(map[uint]uint),
5594 want: addr(map[uint]uint{0: 0, 1: 1, 2: 2, 3: 3}),
5595 }, {
5596 name: jsontest.Name("Maps/ValidKey/NamedUint"),
5597 inBuf: `{"0":0,"1":1,"2":2,"3":3}`,
5598 inVal: new(map[namedUint64]uint),
5599 want: addr(map[namedUint64]uint{0: 0, 1: 1, 2: 2, 3: 3}),
5600 }, {
5601 name: jsontest.Name("Maps/ValidKey/Float"),
5602 inBuf: `{"1.234":1.234,"12.34":12.34,"123.4":123.4}`,
5603 inVal: new(map[float64]float64),
5604 want: addr(map[float64]float64{1.234: 1.234, 12.34: 12.34, 123.4: 123.4}),
5605 }, {
5606 name: jsontest.Name("Maps/DuplicateName/Int"),
5607 inBuf: `{"0":1,"-0":-1}`,
5608 inVal: new(map[int]int),
5609 want: addr(map[int]int{0: 1}),
5610 wantErr: newDuplicateNameError("", []byte(`"-0"`), len64(`{"0":1,`)),
5611 }, {
5612 name: jsontest.Name("Maps/DuplicateName/Int/MergeWithLegacySemantics"),
5613 opts: []Options{jsonflags.MergeWithLegacySemantics | 1},
5614 inBuf: `{"0":1,"-0":-1}`,
5615 inVal: new(map[int]int),
5616 want: addr(map[int]int{0: 1}),
5617 wantErr: newDuplicateNameError("", []byte(`"-0"`), len64(`{"0":1,`)),
5618 }, {
5619 name: jsontest.Name("Maps/DuplicateName/Int/AllowDuplicateNames"),
5620 opts: []Options{jsontext.AllowDuplicateNames(true)},
5621 inBuf: `{"0":1,"-0":-1}`,
5622 inVal: new(map[int]int),
5623 want: addr(map[int]int{0: -1}), // latter takes precedence
5624 }, {
5625 name: jsontest.Name("Maps/DuplicateName/Int/OverwriteExisting"),
5626 inBuf: `{"-0":-1}`,
5627 inVal: addr(map[int]int{0: 1}),
5628 want: addr(map[int]int{0: -1}),
5629 }, {
5630 name: jsontest.Name("Maps/DuplicateName/Float"),
5631 inBuf: `{"1.0":"1.0","1":"1","1e0":"1e0"}`,
5632 inVal: new(map[float64]string),
5633 want: addr(map[float64]string{1: "1.0"}),
5634 wantErr: newDuplicateNameError("", []byte(`"1"`), len64(`{"1.0":"1.0",`)),
5635 }, {
5636 name: jsontest.Name("Maps/DuplicateName/Float/AllowDuplicateNames"),
5637 opts: []Options{jsontext.AllowDuplicateNames(true)},
5638 inBuf: `{"1.0":"1.0","1":"1","1e0":"1e0"}`,
5639 inVal: new(map[float64]string),
5640 want: addr(map[float64]string{1: "1e0"}), // latter takes precedence
5641 }, {
5642 name: jsontest.Name("Maps/DuplicateName/Float/OverwriteExisting"),
5643 inBuf: `{"1.0":"1.0"}`,
5644 inVal: addr(map[float64]string{1: "1"}),
5645 want: addr(map[float64]string{1: "1.0"}),
5646 }, {
5647 name: jsontest.Name("Maps/DuplicateName/NoCaseString"),
5648 inBuf: `{"hello":"hello","HELLO":"HELLO"}`,
5649 inVal: new(map[nocaseString]string),
5650 want: addr(map[nocaseString]string{"hello": "hello"}),
5651 wantErr: newDuplicateNameError("", []byte(`"HELLO"`), len64(`{"hello":"hello",`)),
5652 }, {
5653 name: jsontest.Name("Maps/DuplicateName/NoCaseString/AllowDuplicateNames"),
5654 opts: []Options{jsontext.AllowDuplicateNames(true)},
5655 inBuf: `{"hello":"hello","HELLO":"HELLO"}`,
5656 inVal: new(map[nocaseString]string),
5657 want: addr(map[nocaseString]string{"hello": "HELLO"}), // latter takes precedence
5658 }, {
5659 name: jsontest.Name("Maps/DuplicateName/NoCaseString/OverwriteExisting"),
5660 opts: []Options{jsontext.AllowDuplicateNames(true)},
5661 inBuf: `{"HELLO":"HELLO"}`,
5662 inVal: addr(map[nocaseString]string{"hello": "hello"}),
5663 want: addr(map[nocaseString]string{"hello": "HELLO"}),
5664 }, {
5665 name: jsontest.Name("Maps/ValidKey/Interface"),
5666 inBuf: `{"false":"false","true":"true","string":"string","0":"0","[]":"[]","{}":"{}"}`,
5667 inVal: new(map[any]string),
5668 want: addr(map[any]string{
5669 "false": "false",
5670 "true": "true",
5671 "string": "string",
5672 "0": "0",
5673 "[]": "[]",
5674 "{}": "{}",
5675 }),
5676 }, {
5677 name: jsontest.Name("Maps/InvalidValue/Channel"),
5678 inBuf: `{"key":"value"}`,
5679 inVal: new(map[string]chan string),
5680 want: addr(map[string]chan string{
5681 "key": nil,
5682 }),
5683 wantErr: EU(nil).withPos(`{"key":`, "/key").withType(0, T[chan string]()),
5684 }, {
5685 name: jsontest.Name("Maps/RecursiveMap"),
5686 inBuf: `{"buzz":{},"fizz":{"bar":{},"foo":{}}}`,
5687 inVal: new(recursiveMap),
5688 want: addr(recursiveMap{
5689 "fizz": {
5690 "foo": {},
5691 "bar": {},
5692 },
5693 "buzz": {},
5694 }),
5695 }, {
5696 // NOTE: The semantics differs from v1,
5697 // where existing map entries were not merged into.
5698 // See https://go.dev/issue/31924.
5699 name: jsontest.Name("Maps/Merge"),
5700 opts: []Options{jsontext.AllowDuplicateNames(true)},
5701 inBuf: `{"k1":{"k2":"v2"},"k2":{"k1":"v1"},"k2":{"k2":"v2"}}`,
5702 inVal: addr(map[string]map[string]string{
5703 "k1": {"k1": "v1"},
5704 }),
5705 want: addr(map[string]map[string]string{
5706 "k1": {"k1": "v1", "k2": "v2"},
5707 "k2": {"k1": "v1", "k2": "v2"},
5708 }),
5709 }, {
5710 name: jsontest.Name("Maps/Invalid/Bool"),
5711 inBuf: `true`,
5712 inVal: addr(map[string]string{"key": "value"}),
5713 want: addr(map[string]string{"key": "value"}),
5714 wantErr: EU(nil).withType('t', T[map[string]string]()),
5715 }, {
5716 name: jsontest.Name("Maps/Invalid/String"),
5717 inBuf: `""`,
5718 inVal: addr(map[string]string{"key": "value"}),
5719 want: addr(map[string]string{"key": "value"}),
5720 wantErr: EU(nil).withType('"', T[map[string]string]()),
5721 }, {
5722 name: jsontest.Name("Maps/Invalid/Number"),
5723 inBuf: `0`,
5724 inVal: addr(map[string]string{"key": "value"}),
5725 want: addr(map[string]string{"key": "value"}),
5726 wantErr: EU(nil).withType('0', T[map[string]string]()),
5727 }, {
5728 name: jsontest.Name("Maps/Invalid/Array"),
5729 inBuf: `[]`,
5730 inVal: addr(map[string]string{"key": "value"}),
5731 want: addr(map[string]string{"key": "value"}),
5732 wantErr: EU(nil).withType('[', T[map[string]string]()),
5733 }, {
5734 name: jsontest.Name("Maps/IgnoreInvalidFormat"),
5735 opts: []Options{invalidFormatOption},
5736 inBuf: `{"hello":"goodbye"}`,
5737 inVal: addr(map[string]string{}),
5738 want: addr(map[string]string{"hello": "goodbye"}),
5739 }, {
5740 name: jsontest.Name("Structs/Null"),
5741 inBuf: `null`,
5742 inVal: addr(structAll{String: "something"}),
5743 want: addr(structAll{}),
5744 }, {
5745 name: jsontest.Name("Structs/Empty"),
5746 inBuf: `{}`,
5747 inVal: addr(structAll{
5748 String: "hello",
5749 Map: map[string]string{},
5750 Slice: []string{},
5751 }),
5752 want: addr(structAll{
5753 String: "hello",
5754 Map: map[string]string{},
5755 Slice: []string{},
5756 }),
5757 }, {
5758 name: jsontest.Name("Structs/Normal"),
5759 inBuf: `{
5760 "Bool": true,
5761 "String": "hello",
5762 "Bytes": "AQID",
5763 "Int": -64,
5764 "Uint": 64,
5765 "Float": 3.14159,
5766 "Map": {"key": "value"},
5767 "StructScalars": {
5768 "Bool": true,
5769 "String": "hello",
5770 "Bytes": "AQID",
5771 "Int": -64,
5772 "Uint": 64,
5773 "Float": 3.14159
5774 },
5775 "StructMaps": {
5776 "MapBool": {"": true},
5777 "MapString": {"": "hello"},
5778 "MapBytes": {"": "AQID"},
5779 "MapInt": {"": -64},
5780 "MapUint": {"": 64},
5781 "MapFloat": {"": 3.14159}
5782 },
5783 "StructSlices": {
5784 "SliceBool": [true],
5785 "SliceString": ["hello"],
5786 "SliceBytes": ["AQID"],
5787 "SliceInt": [-64],
5788 "SliceUint": [64],
5789 "SliceFloat": [3.14159]
5790 },
5791 "Slice": ["fizz","buzz"],
5792 "Array": ["goodbye"],
5793 "Pointer": {},
5794 "Interface": null
5795 }`,
5796 inVal: new(structAll),
5797 want: addr(structAll{
5798 Bool: true,
5799 String: "hello",
5800 Bytes: []byte{1, 2, 3},
5801 Int: -64,
5802 Uint: +64,
5803 Float: 3.14159,
5804 Map: map[string]string{"key": "value"},
5805 StructScalars: structScalars{
5806 Bool: true,
5807 String: "hello",
5808 Bytes: []byte{1, 2, 3},
5809 Int: -64,
5810 Uint: +64,
5811 Float: 3.14159,
5812 },
5813 StructMaps: structMaps{
5814 MapBool: map[string]bool{"": true},
5815 MapString: map[string]string{"": "hello"},
5816 MapBytes: map[string][]byte{"": {1, 2, 3}},
5817 MapInt: map[string]int64{"": -64},
5818 MapUint: map[string]uint64{"": +64},
5819 MapFloat: map[string]float64{"": 3.14159},
5820 },
5821 StructSlices: structSlices{
5822 SliceBool: []bool{true},
5823 SliceString: []string{"hello"},
5824 SliceBytes: [][]byte{{1, 2, 3}},
5825 SliceInt: []int64{-64},
5826 SliceUint: []uint64{+64},
5827 SliceFloat: []float64{3.14159},
5828 },
5829 Slice: []string{"fizz", "buzz"},
5830 Array: [1]string{"goodbye"},
5831 Pointer: new(structAll),
5832 }),
5833 }, {
5834 name: jsontest.Name("Structs/Merge"),
5835 inBuf: `{
5836 "Bool": false,
5837 "String": "goodbye",
5838 "Int": -64,
5839 "Float": 3.14159,
5840 "Map": {"k2": "v2"},
5841 "StructScalars": {
5842 "Bool": true,
5843 "String": "hello",
5844 "Bytes": "AQID",
5845 "Int": -64
5846 },
5847 "StructMaps": {
5848 "MapBool": {"": true},
5849 "MapString": {"": "hello"},
5850 "MapBytes": {"": "AQID"},
5851 "MapInt": {"": -64},
5852 "MapUint": {"": 64},
5853 "MapFloat": {"": 3.14159}
5854 },
5855 "StructSlices": {
5856 "SliceString": ["hello"],
5857 "SliceBytes": ["AQID"],
5858 "SliceInt": [-64],
5859 "SliceUint": [64]
5860 },
5861 "Slice": ["fizz","buzz"],
5862 "Array": ["goodbye"],
5863 "Pointer": {},
5864 "Interface": {"k2":"v2"}
5865 }`,
5866 inVal: addr(structAll{
5867 Bool: true,
5868 String: "hello",
5869 Bytes: []byte{1, 2, 3},
5870 Uint: +64,
5871 Float: math.NaN(),
5872 Map: map[string]string{"k1": "v1"},
5873 StructScalars: structScalars{
5874 String: "hello",
5875 Bytes: make([]byte, 2, 4),
5876 Uint: +64,
5877 Float: 3.14159,
5878 },
5879 StructMaps: structMaps{
5880 MapBool: map[string]bool{"": false},
5881 MapBytes: map[string][]byte{"": {}},
5882 MapInt: map[string]int64{"": 123},
5883 MapFloat: map[string]float64{"": math.Inf(+1)},
5884 },
5885 StructSlices: structSlices{
5886 SliceBool: []bool{true},
5887 SliceBytes: [][]byte{nil, nil},
5888 SliceInt: []int64{-123},
5889 SliceUint: []uint64{+123},
5890 SliceFloat: []float64{3.14159},
5891 },
5892 Slice: []string{"buzz", "fizz", "gizz"},
5893 Array: [1]string{"hello"},
5894 Pointer: new(structAll),
5895 Interface: map[string]string{"k1": "v1"},
5896 }),
5897 want: addr(structAll{
5898 Bool: false,
5899 String: "goodbye",
5900 Bytes: []byte{1, 2, 3},
5901 Int: -64,
5902 Uint: +64,
5903 Float: 3.14159,
5904 Map: map[string]string{"k1": "v1", "k2": "v2"},
5905 StructScalars: structScalars{
5906 Bool: true,
5907 String: "hello",
5908 Bytes: []byte{1, 2, 3},
5909 Int: -64,
5910 Uint: +64,
5911 Float: 3.14159,
5912 },
5913 StructMaps: structMaps{
5914 MapBool: map[string]bool{"": true},
5915 MapString: map[string]string{"": "hello"},
5916 MapBytes: map[string][]byte{"": {1, 2, 3}},
5917 MapInt: map[string]int64{"": -64},
5918 MapUint: map[string]uint64{"": +64},
5919 MapFloat: map[string]float64{"": 3.14159},
5920 },
5921 StructSlices: structSlices{
5922 SliceBool: []bool{true},
5923 SliceString: []string{"hello"},
5924 SliceBytes: [][]byte{{1, 2, 3}},
5925 SliceInt: []int64{-64},
5926 SliceUint: []uint64{+64},
5927 SliceFloat: []float64{3.14159},
5928 },
5929 Slice: []string{"fizz", "buzz"},
5930 Array: [1]string{"goodbye"},
5931 Pointer: new(structAll),
5932 Interface: map[string]string{"k1": "v1", "k2": "v2"},
5933 }),
5934 }, {
5935 name: jsontest.Name("Structs/Stringified/Normal"),
5936 inBuf: `{
5937 "Bool": true,
5938 "String": "hello",
5939 "Bytes": "AQID",
5940 "Int": "-64",
5941 "Uint": "64",
5942 "Float": "3.14159",
5943 "Map": {"key": "value"},
5944 "StructScalars": {
5945 "Bool": true,
5946 "String": "hello",
5947 "Bytes": "AQID",
5948 "Int": "-64",
5949 "Uint": "64",
5950 "Float": "3.14159"
5951 },
5952 "StructMaps": {
5953 "MapBool": {"": true},
5954 "MapString": {"": "hello"},
5955 "MapBytes": {"": "AQID"},
5956 "MapInt": {"": "-64"},
5957 "MapUint": {"": "64"},
5958 "MapFloat": {"": "3.14159"}
5959 },
5960 "StructSlices": {
5961 "SliceBool": [true],
5962 "SliceString": ["hello"],
5963 "SliceBytes": ["AQID"],
5964 "SliceInt": ["-64"],
5965 "SliceUint": ["64"],
5966 "SliceFloat": ["3.14159"]
5967 },
5968 "Slice": ["fizz","buzz"],
5969 "Array": ["goodbye"],
5970 "Pointer": {},
5971 "Interface": null
5972 }`,
5973 inVal: new(structStringifiedAll),
5974 want: addr(structStringifiedAll{
5975 Bool: true,
5976 String: "hello",
5977 Bytes: []byte{1, 2, 3},
5978 Int: -64, // may be stringified
5979 Uint: +64, // may be stringified
5980 Float: 3.14159, // may be stringified
5981 Map: map[string]string{"key": "value"},
5982 StructScalars: structScalars{
5983 Bool: true,
5984 String: "hello",
5985 Bytes: []byte{1, 2, 3},
5986 Int: -64, // may be stringified
5987 Uint: +64, // may be stringified
5988 Float: 3.14159, // may be stringified
5989 },
5990 StructMaps: structMaps{
5991 MapBool: map[string]bool{"": true},
5992 MapString: map[string]string{"": "hello"},
5993 MapBytes: map[string][]byte{"": {1, 2, 3}},
5994 MapInt: map[string]int64{"": -64}, // may be stringified
5995 MapUint: map[string]uint64{"": +64}, // may be stringified
5996 MapFloat: map[string]float64{"": 3.14159}, // may be stringified
5997 },
5998 StructSlices: structSlices{
5999 SliceBool: []bool{true},
6000 SliceString: []string{"hello"},
6001 SliceBytes: [][]byte{{1, 2, 3}},
6002 SliceInt: []int64{-64}, // may be stringified
6003 SliceUint: []uint64{+64}, // may be stringified
6004 SliceFloat: []float64{3.14159}, // may be stringified
6005 },
6006 Slice: []string{"fizz", "buzz"},
6007 Array: [1]string{"goodbye"},
6008 Pointer: new(structStringifiedAll), // may be stringified
6009 }),
6010 }, {
6011 name: jsontest.Name("Structs/Stringified/String"),
6012 inBuf: `{
6013 "Bool": true,
6014 "String": "hello",
6015 "Bytes": "AQID",
6016 "Int": "-64",
6017 "Uint": "64",
6018 "Float": "3.14159",
6019 "Map": {"key": "value"},
6020 "StructScalars": {
6021 "Bool": true,
6022 "String": "hello",
6023 "Bytes": "AQID",
6024 "Int": "-64",
6025 "Uint": "64",
6026 "Float": "3.14159"
6027 },
6028 "StructMaps": {
6029 "MapBool": {"": true},
6030 "MapString": {"": "hello"},
6031 "MapBytes": {"": "AQID"},
6032 "MapInt": {"": "-64"},
6033 "MapUint": {"": "64"},
6034 "MapFloat": {"": "3.14159"}
6035 },
6036 "StructSlices": {
6037 "SliceBool": [true],
6038 "SliceString": ["hello"],
6039 "SliceBytes": ["AQID"],
6040 "SliceInt": ["-64"],
6041 "SliceUint": ["64"],
6042 "SliceFloat": ["3.14159"]
6043 },
6044 "Slice": ["fizz","buzz"],
6045 "Array": ["goodbye"],
6046 "Pointer": {},
6047 "Interface": null
6048 }`,
6049 inVal: new(structStringifiedAll),
6050 want: addr(structStringifiedAll{
6051 Bool: true,
6052 String: "hello",
6053 Bytes: []byte{1, 2, 3},
6054 Int: -64, // may be stringified
6055 Uint: +64, // may be stringified
6056 Float: 3.14159, // may be stringified
6057 Map: map[string]string{"key": "value"},
6058 StructScalars: structScalars{
6059 Bool: true,
6060 String: "hello",
6061 Bytes: []byte{1, 2, 3},
6062 Int: -64, // may be stringified
6063 Uint: +64, // may be stringified
6064 Float: 3.14159, // may be stringified
6065 },
6066 StructMaps: structMaps{
6067 MapBool: map[string]bool{"": true},
6068 MapString: map[string]string{"": "hello"},
6069 MapBytes: map[string][]byte{"": {1, 2, 3}},
6070 MapInt: map[string]int64{"": -64}, // may be stringified
6071 MapUint: map[string]uint64{"": +64}, // may be stringified
6072 MapFloat: map[string]float64{"": 3.14159}, // may be stringified
6073 },
6074 StructSlices: structSlices{
6075 SliceBool: []bool{true},
6076 SliceString: []string{"hello"},
6077 SliceBytes: [][]byte{{1, 2, 3}},
6078 SliceInt: []int64{-64}, // may be stringified
6079 SliceUint: []uint64{+64}, // may be stringified
6080 SliceFloat: []float64{3.14159}, // may be stringified
6081 },
6082 Slice: []string{"fizz", "buzz"},
6083 Array: [1]string{"goodbye"},
6084 Pointer: new(structStringifiedAll), // may be stringified
6085 }),
6086 }, {
6087 name: jsontest.Name("Structs/Stringified/InvalidEmpty"),
6088 inBuf: `{"Int":""}`,
6089 inVal: new(structStringifiedAll),
6090 want: new(structStringifiedAll),
6091 wantErr: EU(strconv.ErrSyntax).withVal(`""`).withPos(`{"Int":`, "/Int").withType('"', T[int64]()),
6092 }, {
6093 name: jsontest.Name("Structs/LegacyStringified"),
6094 opts: []Options{jsonflags.StringifyWithLegacySemantics | 1},
6095 inBuf: `{
6096 "Bool": "true",
6097 "String": "\"hello\"",
6098 "Bytes": "AQID",
6099 "Int": "-64",
6100 "Uint": "64",
6101 "Float": "3.14159",
6102 "Map": {"key": "value"},
6103 "StructScalars": {
6104 "Bool": true,
6105 "String": "hello",
6106 "Bytes": "AQID",
6107 "Int": -64,
6108 "Uint": 64,
6109 "Float": 3.14159
6110 },
6111 "StructMaps": {
6112 "MapBool": {"": true},
6113 "MapString": {"": "hello"},
6114 "MapBytes": {"": "AQID"},
6115 "MapInt": {"": -64},
6116 "MapUint": {"": 64},
6117 "MapFloat": {"": 3.14159}
6118 },
6119 "StructSlices": {
6120 "SliceBool": [true],
6121 "SliceString": ["hello"],
6122 "SliceBytes": ["AQID"],
6123 "SliceInt": [-64],
6124 "SliceUint": [64],
6125 "SliceFloat": [3.14159]
6126 },
6127 "Slice": ["fizz", "buzz"],
6128 "Array": ["goodbye"]
6129 }`,
6130 inVal: new(structStringifiedAll),
6131 want: addr(structStringifiedAll{
6132 Bool: true,
6133 String: "hello",
6134 Bytes: []byte{1, 2, 3},
6135 Int: -64,
6136 Uint: +64,
6137 Float: 3.14159,
6138 Map: map[string]string{"key": "value"},
6139 StructScalars: structScalars{
6140 Bool: true,
6141 String: "hello",
6142 Bytes: []byte{1, 2, 3},
6143 Int: -64,
6144 Uint: +64,
6145 Float: 3.14159,
6146 },
6147 StructMaps: structMaps{
6148 MapBool: map[string]bool{"": true},
6149 MapString: map[string]string{"": "hello"},
6150 MapBytes: map[string][]byte{"": {1, 2, 3}},
6151 MapInt: map[string]int64{"": -64},
6152 MapUint: map[string]uint64{"": +64},
6153 MapFloat: map[string]float64{"": 3.14159},
6154 },
6155 StructSlices: structSlices{
6156 SliceBool: []bool{true},
6157 SliceString: []string{"hello"},
6158 SliceBytes: [][]byte{{1, 2, 3}},
6159 SliceInt: []int64{-64},
6160 SliceUint: []uint64{+64},
6161 SliceFloat: []float64{3.14159},
6162 },
6163 Slice: []string{"fizz", "buzz"},
6164 Array: [1]string{"goodbye"},
6165 }),
6166 }, {
6167 name: jsontest.Name("Structs/LegacyStringified/InvalidBool"),
6168 opts: []Options{jsonflags.StringifyWithLegacySemantics | 1},
6169 inBuf: `{"Bool": true}`,
6170 inVal: new(structStringifiedAll),
6171 wantErr: EU(nil).withPos(`{"Bool": `, "/Bool").withType('t', T[bool]()),
6172 }, {
6173 name: jsontest.Name("Structs/LegacyStringified/InvalidString"),
6174 opts: []Options{jsonflags.StringifyWithLegacySemantics | 1},
6175 inBuf: `{"String": "string"}`,
6176 inVal: new(structStringifiedAll),
6177 wantErr: EU(newInvalidCharacterError("s", "at start of string (expecting '\"')", 0, "")).
6178 withPos(`{"String": `, "/String").withType('"', T[string]()),
6179 }, {
6180 name: jsontest.Name("Structs/Format/Bytes"),
6181 inBuf: `{
6182 "Base16": "0123456789abcdef",
6183 "Base32": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
6184 "Base32Hex": "0123456789ABCDEFGHIJKLMNOPQRSTUV",
6185 "Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
6186 "Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
6187 "Array": [1, 2, 3, 4]
6188 }`,
6189 inVal: new(structFormatBytes),
6190 want: addr(structFormatBytes{
6191 Base16: []byte("\x01\x23\x45\x67\x89\xab\xcd\xef"),
6192 Base32: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
6193 Base32Hex: []byte("\x00D2\x14\xc7BT\xb65τe:V\xd7\xc6u\xbew\xdf"),
6194 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߿"),
6195 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߿"),
6196 Array: []byte{1, 2, 3, 4},
6197 }),
6198 }, {
6199 name: jsontest.Name("Structs/Format/ArrayBytes"),
6200 inBuf: `{
6201 "Base16": "01020304",
6202 "Base32": "AEBAGBA=",
6203 "Base32Hex": "0410610=",
6204 "Base64": "AQIDBA==",
6205 "Base64URL": "AQIDBA==",
6206 "Array": [1, 2, 3, 4],
6207 "Default": "AQIDBA=="
6208 }`,
6209 inVal: new(structFormatArrayBytes),
6210 want: addr(structFormatArrayBytes{
6211 Base16: [4]byte{1, 2, 3, 4},
6212 Base32: [4]byte{1, 2, 3, 4},
6213 Base32Hex: [4]byte{1, 2, 3, 4},
6214 Base64: [4]byte{1, 2, 3, 4},
6215 Base64URL: [4]byte{1, 2, 3, 4},
6216 Array: [4]byte{1, 2, 3, 4},
6217 Default: [4]byte{1, 2, 3, 4},
6218 }),
6219 }, {
6220 name: jsontest.Name("Structs/Format/ArrayBytes/Legacy"),
6221 opts: []Options{jsonflags.FormatBytesWithLegacySemantics | 1},
6222 inBuf: `{
6223 "Base16": "01020304",
6224 "Base32": "AEBAGBA=",
6225 "Base32Hex": "0410610=",
6226 "Base64": "AQIDBA==",
6227 "Base64URL": "AQIDBA==",
6228 "Array": [1, 2, 3, 4],
6229 "Default": [1, 2, 3, 4]
6230 }`,
6231 inVal: new(structFormatArrayBytes),
6232 want: addr(structFormatArrayBytes{
6233 Base16: [4]byte{1, 2, 3, 4},
6234 Base32: [4]byte{1, 2, 3, 4},
6235 Base32Hex: [4]byte{1, 2, 3, 4},
6236 Base64: [4]byte{1, 2, 3, 4},
6237 Base64URL: [4]byte{1, 2, 3, 4},
6238 Array: [4]byte{1, 2, 3, 4},
6239 Default: [4]byte{1, 2, 3, 4},
6240 }),
6241 }, {
6242 name: jsontest.Name("Structs/Format/Bytes/Array"),
6243 opts: []Options{
6244 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *byte) error {
6245 if string(b) == "true" {
6246 *v = 1
6247 } else {
6248 *v = 0
6249 }
6250 return nil
6251 })),
6252 },
6253 inBuf: `{"Array":[false,true,false,true,false,true]}`,
6254 inVal: new(struct {
6255 Array []byte `json:",format:array"`
6256 }),
6257 want: addr(struct {
6258 Array []byte `json:",format:array"`
6259 }{
6260 Array: []byte{0, 1, 0, 1, 0, 1},
6261 }),
6262 }, {
6263 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/WrongKind"),
6264 inBuf: `{"Base16": [1,2,3,4]}`,
6265 inVal: new(structFormatBytes),
6266 wantErr: EU(nil).withPos(`{"Base16": `, "/Base16").withType('[', T[[]byte]()),
6267 }, {
6268 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/AllPadding"),
6269 inBuf: `{"Base16": "===="}`,
6270 inVal: new(structFormatBytes),
6271 wantErr: EU(func() error {
6272 _, err := hex.Decode(make([]byte, 2), []byte("====="))
6273 return err
6274 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6275 }, {
6276 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/EvenPadding"),
6277 inBuf: `{"Base16": "0123456789abcdef="}`,
6278 inVal: new(structFormatBytes),
6279 wantErr: EU(func() error {
6280 _, err := hex.Decode(make([]byte, 8), []byte("0123456789abcdef="))
6281 return err
6282 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6283 }, {
6284 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/OddPadding"),
6285 inBuf: `{"Base16": "0123456789abcdef0="}`,
6286 inVal: new(structFormatBytes),
6287 wantErr: EU(func() error {
6288 _, err := hex.Decode(make([]byte, 9), []byte("0123456789abcdef0="))
6289 return err
6290 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6291 }, {
6292 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/LineFeed"),
6293 inBuf: `{"Base16": "aa\naa"}`,
6294 inVal: new(structFormatBytes),
6295 wantErr: EU(func() error {
6296 _, err := hex.Decode(make([]byte, 9), []byte("aa\naa"))
6297 return err
6298 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6299 }, {
6300 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/CarriageReturn"),
6301 inBuf: `{"Base16": "aa\raa"}`,
6302 inVal: new(structFormatBytes),
6303 wantErr: EU(func() error {
6304 _, err := hex.Decode(make([]byte, 9), []byte("aa\raa"))
6305 return err
6306 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6307 }, {
6308 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base16/NonAlphabet/Space"),
6309 inBuf: `{"Base16": "aa aa"}`,
6310 inVal: new(structFormatBytes),
6311 wantErr: EU(func() error {
6312 _, err := hex.Decode(make([]byte, 9), []byte("aa aa"))
6313 return err
6314 }()).withPos(`{"Base16": `, "/Base16").withType('"', T[[]byte]()),
6315 }, {
6316 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/Padding"),
6317 inBuf: `[
6318 {"Base32": "NA======"},
6319 {"Base32": "NBSQ===="},
6320 {"Base32": "NBSWY==="},
6321 {"Base32": "NBSWY3A="},
6322 {"Base32": "NBSWY3DP"}
6323 ]`,
6324 inVal: new([]structFormatBytes),
6325 want: addr([]structFormatBytes{
6326 {Base32: []byte("h")},
6327 {Base32: []byte("he")},
6328 {Base32: []byte("hel")},
6329 {Base32: []byte("hell")},
6330 {Base32: []byte("hello")},
6331 }),
6332 }, {
6333 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/Invalid/NoPadding"),
6334 inBuf: `[
6335 {"Base32": "NA"},
6336 {"Base32": "NBSQ"},
6337 {"Base32": "NBSWY"},
6338 {"Base32": "NBSWY3A"},
6339 {"Base32": "NBSWY3DP"}
6340 ]`,
6341 inVal: new([]structFormatBytes),
6342 wantErr: EU(func() error {
6343 _, err := base32.StdEncoding.Decode(make([]byte, 1), []byte("NA"))
6344 return err
6345 }()).withPos(`[`+"\n\t\t\t\t"+`{"Base32": `, "/0/Base32").withType('"', T[[]byte]()),
6346 }, {
6347 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/WrongAlphabet"),
6348 inBuf: `{"Base32": "0123456789ABCDEFGHIJKLMNOPQRSTUV"}`,
6349 inVal: new(structFormatBytes),
6350 wantErr: EU(func() error {
6351 _, err := base32.StdEncoding.Decode(make([]byte, 20), []byte("0123456789ABCDEFGHIJKLMNOPQRSTUV"))
6352 return err
6353 }()).withPos(`{"Base32": `, "/Base32").withType('"', T[[]byte]()),
6354 }, {
6355 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32Hex/WrongAlphabet"),
6356 inBuf: `{"Base32Hex": "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"}`,
6357 inVal: new(structFormatBytes),
6358 wantErr: EU(func() error {
6359 _, err := base32.HexEncoding.Decode(make([]byte, 20), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"))
6360 return err
6361 }()).withPos(`{"Base32Hex": `, "/Base32Hex").withType('"', T[[]byte]()),
6362 }, {
6363 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/LineFeed"),
6364 inBuf: `{"Base32": "AAAA\nAAAA"}`,
6365 inVal: new(structFormatBytes),
6366 wantErr: EU(errors.New("illegal character '\\n' at offset 4")).withPos(`{"Base32": `, "/Base32").withType('"', T[[]byte]()),
6367 }, {
6368 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/CarriageReturn"),
6369 inBuf: `{"Base32": "AAAA\rAAAA"}`,
6370 inVal: new(structFormatBytes),
6371 wantErr: EU(errors.New("illegal character '\\r' at offset 4")).withPos(`{"Base32": `, "/Base32").withType('"', T[[]byte]()),
6372 }, {
6373 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base32/NonAlphabet/Space"),
6374 inBuf: `{"Base32": "AAAA AAAA"}`,
6375 inVal: new(structFormatBytes),
6376 wantErr: EU(base32.CorruptInputError(4)).withPos(`{"Base32": `, "/Base32").withType('"', T[[]byte]()),
6377 }, {
6378 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base64/WrongAlphabet"),
6379 inBuf: `{"Base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}`,
6380 inVal: new(structFormatBytes),
6381 wantErr: EU(func() error {
6382 _, err := base64.StdEncoding.Decode(make([]byte, 48), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"))
6383 return err
6384 }()).withPos(`{"Base64": `, "/Base64").withType('"', T[[]byte]()),
6385 }, {
6386 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base64URL/WrongAlphabet"),
6387 inBuf: `{"Base64URL": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}`,
6388 inVal: new(structFormatBytes),
6389 wantErr: EU(func() error {
6390 _, err := base64.URLEncoding.Decode(make([]byte, 48), []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"))
6391 return err
6392 }()).withPos(`{"Base64URL": `, "/Base64URL").withType('"', T[[]byte]()),
6393 }, {
6394 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/LineFeed"),
6395 inBuf: `{"Base64": "aa=\n="}`,
6396 inVal: new(structFormatBytes),
6397 wantErr: EU(errors.New("illegal character '\\n' at offset 3")).withPos(`{"Base64": `, "/Base64").withType('"', T[[]byte]()),
6398 }, {
6399 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/CarriageReturn"),
6400 inBuf: `{"Base64": "aa=\r="}`,
6401 inVal: new(structFormatBytes),
6402 wantErr: EU(errors.New("illegal character '\\r' at offset 3")).withPos(`{"Base64": `, "/Base64").withType('"', T[[]byte]()),
6403 }, {
6404 name: jsontest.Name("Structs/Format/Bytes/Base64/NonAlphabet/Ignored"),
6405 opts: []Options{jsonflags.ParseBytesWithLooseRFC4648 | 1},
6406 inBuf: `{"Base64": "aa=\r\n="}`,
6407 inVal: new(structFormatBytes),
6408 want: &structFormatBytes{Base64: []byte{105}},
6409 }, {
6410 name: jsontest.Name("Structs/Format/Bytes/Invalid/Base64/NonAlphabet/Space"),
6411 inBuf: `{"Base64": "aa= ="}`,
6412 inVal: new(structFormatBytes),
6413 wantErr: EU(base64.CorruptInputError(2)).withPos(`{"Base64": `, "/Base64").withType('"', T[[]byte]()),
6414 }, {
6415 name: jsontest.Name("Structs/Format/Floats"),
6416 inBuf: `[
6417 {"NonFinite": 3.141592653589793, "PointerNonFinite": 3.141592653589793},
6418 {"NonFinite": "-Infinity", "PointerNonFinite": "-Infinity"},
6419 {"NonFinite": "Infinity", "PointerNonFinite": "Infinity"}
6420 ]`,
6421 inVal: new([]structFormatFloats),
6422 want: addr([]structFormatFloats{
6423 {NonFinite: math.Pi, PointerNonFinite: addr(math.Pi)},
6424 {NonFinite: math.Inf(-1), PointerNonFinite: addr(math.Inf(-1))},
6425 {NonFinite: math.Inf(+1), PointerNonFinite: addr(math.Inf(+1))},
6426 }),
6427 }, {
6428 name: jsontest.Name("Structs/Format/Floats/NaN"),
6429 inBuf: `{"NonFinite": "NaN"}`,
6430 inVal: new(structFormatFloats),
6431 // Avoid checking want since reflect.DeepEqual fails for NaNs.
6432 }, {
6433 name: jsontest.Name("Structs/Format/Floats/Invalid/NaN"),
6434 inBuf: `{"NonFinite": "nan"}`,
6435 inVal: new(structFormatFloats),
6436 wantErr: EU(nil).withPos(`{"NonFinite": `, "/NonFinite").withType('"', T[float64]()),
6437 }, {
6438 name: jsontest.Name("Structs/Format/Floats/Invalid/PositiveInfinity"),
6439 inBuf: `{"NonFinite": "+Infinity"}`,
6440 inVal: new(structFormatFloats),
6441 wantErr: EU(nil).withPos(`{"NonFinite": `, "/NonFinite").withType('"', T[float64]()),
6442 }, {
6443 name: jsontest.Name("Structs/Format/Floats/Invalid/NegativeInfinitySpace"),
6444 inBuf: `{"NonFinite": "-Infinity "}`,
6445 inVal: new(structFormatFloats),
6446 wantErr: EU(nil).withPos(`{"NonFinite": `, "/NonFinite").withType('"', T[float64]()),
6447 }, {
6448 name: jsontest.Name("Structs/Format/Maps"),
6449 inBuf: `[
6450 {"EmitNull": null, "PointerEmitNull": null, "EmitEmpty": null, "PointerEmitEmpty": null, "EmitDefault": null, "PointerEmitDefault": null},
6451 {"EmitNull": {}, "PointerEmitNull": {}, "EmitEmpty": {}, "PointerEmitEmpty": {}, "EmitDefault": {}, "PointerEmitDefault": {}},
6452 {"EmitNull": {"k": "v"}, "PointerEmitNull": {"k": "v"}, "EmitEmpty": {"k": "v"}, "PointerEmitEmpty": {"k": "v"}, "EmitDefault": {"k": "v"}, "PointerEmitDefault": {"k": "v"}}
6453 ]`,
6454 inVal: new([]structFormatMaps),
6455 want: addr([]structFormatMaps{{
6456 EmitNull: map[string]string(nil), PointerEmitNull: (*map[string]string)(nil),
6457 EmitEmpty: map[string]string(nil), PointerEmitEmpty: (*map[string]string)(nil),
6458 EmitDefault: map[string]string(nil), PointerEmitDefault: (*map[string]string)(nil),
6459 }, {
6460 EmitNull: map[string]string{}, PointerEmitNull: addr(map[string]string{}),
6461 EmitEmpty: map[string]string{}, PointerEmitEmpty: addr(map[string]string{}),
6462 EmitDefault: map[string]string{}, PointerEmitDefault: addr(map[string]string{}),
6463 }, {
6464 EmitNull: map[string]string{"k": "v"}, PointerEmitNull: addr(map[string]string{"k": "v"}),
6465 EmitEmpty: map[string]string{"k": "v"}, PointerEmitEmpty: addr(map[string]string{"k": "v"}),
6466 EmitDefault: map[string]string{"k": "v"}, PointerEmitDefault: addr(map[string]string{"k": "v"}),
6467 }}),
6468 }, {
6469 name: jsontest.Name("Structs/Format/Slices"),
6470 inBuf: `[
6471 {"EmitNull": null, "PointerEmitNull": null, "EmitEmpty": null, "PointerEmitEmpty": null, "EmitDefault": null, "PointerEmitDefault": null},
6472 {"EmitNull": [], "PointerEmitNull": [], "EmitEmpty": [], "PointerEmitEmpty": [], "EmitDefault": [], "PointerEmitDefault": []},
6473 {"EmitNull": ["v"], "PointerEmitNull": ["v"], "EmitEmpty": ["v"], "PointerEmitEmpty": ["v"], "EmitDefault": ["v"], "PointerEmitDefault": ["v"]}
6474 ]`,
6475 inVal: new([]structFormatSlices),
6476 want: addr([]structFormatSlices{{
6477 EmitNull: []string(nil), PointerEmitNull: (*[]string)(nil),
6478 EmitEmpty: []string(nil), PointerEmitEmpty: (*[]string)(nil),
6479 EmitDefault: []string(nil), PointerEmitDefault: (*[]string)(nil),
6480 }, {
6481 EmitNull: []string{}, PointerEmitNull: addr([]string{}),
6482 EmitEmpty: []string{}, PointerEmitEmpty: addr([]string{}),
6483 EmitDefault: []string{}, PointerEmitDefault: addr([]string{}),
6484 }, {
6485 EmitNull: []string{"v"}, PointerEmitNull: addr([]string{"v"}),
6486 EmitEmpty: []string{"v"}, PointerEmitEmpty: addr([]string{"v"}),
6487 EmitDefault: []string{"v"}, PointerEmitDefault: addr([]string{"v"}),
6488 }}),
6489 }, {
6490 name: jsontest.Name("Structs/Format/Invalid/Bool"),
6491 inBuf: `{"Bool":true}`,
6492 inVal: new(structFormatInvalid),
6493 wantErr: EU(errInvalidFormatFlag).withPos(`{"Bool":`, "/Bool").withType(0, T[bool]()),
6494 }, {
6495 name: jsontest.Name("Structs/Format/Invalid/String"),
6496 inBuf: `{"String": "string"}`,
6497 inVal: new(structFormatInvalid),
6498 wantErr: EU(errInvalidFormatFlag).withPos(`{"String": `, "/String").withType(0, T[string]()),
6499 }, {
6500 name: jsontest.Name("Structs/Format/Invalid/Bytes"),
6501 inBuf: `{"Bytes": "bytes"}`,
6502 inVal: new(structFormatInvalid),
6503 wantErr: EU(errInvalidFormatFlag).withPos(`{"Bytes": `, "/Bytes").withType(0, T[[]byte]()),
6504 }, {
6505 name: jsontest.Name("Structs/Format/Invalid/Int"),
6506 inBuf: `{"Int": 1}`,
6507 inVal: new(structFormatInvalid),
6508 wantErr: EU(errInvalidFormatFlag).withPos(`{"Int": `, "/Int").withType(0, T[int64]()),
6509 }, {
6510 name: jsontest.Name("Structs/Format/Invalid/Uint"),
6511 inBuf: `{"Uint": 1}`,
6512 inVal: new(structFormatInvalid),
6513 wantErr: EU(errInvalidFormatFlag).withPos(`{"Uint": `, "/Uint").withType(0, T[uint64]()),
6514 }, {
6515 name: jsontest.Name("Structs/Format/Invalid/Float"),
6516 inBuf: `{"Float" : 1}`,
6517 inVal: new(structFormatInvalid),
6518 wantErr: EU(errInvalidFormatFlag).withPos(`{"Float" : `, "/Float").withType(0, T[float64]()),
6519 }, {
6520 name: jsontest.Name("Structs/Format/Invalid/Map"),
6521 inBuf: `{"Map":{}}`,
6522 inVal: new(structFormatInvalid),
6523 wantErr: EU(errInvalidFormatFlag).withPos(`{"Map":`, "/Map").withType(0, T[map[string]string]()),
6524 }, {
6525 name: jsontest.Name("Structs/Format/Invalid/Struct"),
6526 inBuf: `{"Struct": {}}`,
6527 inVal: new(structFormatInvalid),
6528 wantErr: EU(errInvalidFormatFlag).withPos(`{"Struct": `, "/Struct").withType(0, T[structAll]()),
6529 }, {
6530 name: jsontest.Name("Structs/Format/Invalid/Slice"),
6531 inBuf: `{"Slice": {}}`,
6532 inVal: new(structFormatInvalid),
6533 wantErr: EU(errInvalidFormatFlag).withPos(`{"Slice": `, "/Slice").withType(0, T[[]string]()),
6534 }, {
6535 name: jsontest.Name("Structs/Format/Invalid/Array"),
6536 inBuf: `{"Array": []}`,
6537 inVal: new(structFormatInvalid),
6538 wantErr: EU(errInvalidFormatFlag).withPos(`{"Array": `, "/Array").withType(0, T[[1]string]()),
6539 }, {
6540 name: jsontest.Name("Structs/Format/Invalid/Interface"),
6541 inBuf: `{"Interface": "anything"}`,
6542 inVal: new(structFormatInvalid),
6543 wantErr: EU(errInvalidFormatFlag).withPos(`{"Interface": `, "/Interface").withType(0, T[any]()),
6544 }, {
6545 name: jsontest.Name("Structs/Inline/Zero"),
6546 inBuf: `{"D":""}`,
6547 inVal: new(structInlined),
6548 want: new(structInlined),
6549 }, {
6550 name: jsontest.Name("Structs/Inline/Alloc"),
6551 inBuf: `{"E":"","F":"","G":"","A":"","B":"","D":""}`,
6552 inVal: new(structInlined),
6553 want: addr(structInlined{
6554 X: structInlinedL1{
6555 X: &structInlinedL2{},
6556 StructEmbed1: StructEmbed1{},
6557 },
6558 StructEmbed2: &StructEmbed2{},
6559 }),
6560 }, {
6561 name: jsontest.Name("Structs/Inline/NonZero"),
6562 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
6563 inVal: new(structInlined),
6564 want: addr(structInlined{
6565 X: structInlinedL1{
6566 X: &structInlinedL2{A: "A1", B: "B1" /* C: "C1" */},
6567 StructEmbed1: StructEmbed1{ /* C: "C2" */ D: "D2" /* E: "E2" */},
6568 },
6569 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
6570 }),
6571 }, {
6572 name: jsontest.Name("Structs/Inline/Merge"),
6573 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
6574 inVal: addr(structInlined{
6575 X: structInlinedL1{
6576 X: &structInlinedL2{B: "##", C: "C1"},
6577 StructEmbed1: StructEmbed1{C: "C2", E: "E2"},
6578 },
6579 StructEmbed2: &StructEmbed2{E: "##", G: "G3"},
6580 }),
6581 want: addr(structInlined{
6582 X: structInlinedL1{
6583 X: &structInlinedL2{A: "A1", B: "B1", C: "C1"},
6584 StructEmbed1: StructEmbed1{C: "C2", D: "D2", E: "E2"},
6585 },
6586 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
6587 }),
6588 }, {
6589 name: jsontest.Name("Structs/InlinedFallback/TextValue/Noop"),
6590 inBuf: `{"A":1,"B":2}`,
6591 inVal: new(structInlineTextValue),
6592 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(nil), B: 2}),
6593 }, {
6594 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN1/Nil"),
6595 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6596 inVal: new(structInlineTextValue),
6597 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":"buzz"}`), B: 2}),
6598 }, {
6599 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN1/Empty"),
6600 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6601 inVal: addr(structInlineTextValue{X: jsontext.Value{}}),
6602 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":"buzz"}`), B: 2}),
6603 }, {
6604 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN1/Whitespace"),
6605 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6606 inVal: addr(structInlineTextValue{X: jsontext.Value("\n\r\t ")}),
6607 want: addr(structInlineTextValue{A: 1, X: jsontext.Value("")}),
6608 wantErr: EU(errRawInlinedNotObject).withPos(`{"A":1,`, "/fizz").withType('"', T[jsontext.Value]()),
6609 }, {
6610 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN1/Null"),
6611 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6612 inVal: addr(structInlineTextValue{X: jsontext.Value("null")}),
6613 want: addr(structInlineTextValue{A: 1, X: jsontext.Value("null")}),
6614 wantErr: EU(errRawInlinedNotObject).withPos(`{"A":1,`, "/fizz").withType('"', T[jsontext.Value]()),
6615 }, {
6616 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN1/ObjectN0"),
6617 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6618 inVal: addr(structInlineTextValue{X: jsontext.Value(` { } `)}),
6619 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(` {"fizz":"buzz"}`), B: 2}),
6620 }, {
6621 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeN2/ObjectN1"),
6622 inBuf: `{"A":1,"fizz":"buzz","B":2,"foo": [ 1 , 2 , 3 ]}`,
6623 inVal: addr(structInlineTextValue{X: jsontext.Value(` { "fizz" : "buzz" } `)}),
6624 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(` { "fizz" : "buzz","fizz":"buzz","foo":[ 1 , 2 , 3 ]}`), B: 2}),
6625 }, {
6626 name: jsontest.Name("Structs/InlinedFallback/TextValue/Merge/EndObject"),
6627 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6628 inVal: addr(structInlineTextValue{X: jsontext.Value(` } `)}),
6629 // NOTE: This produces invalid output,
6630 // but the value being merged into is already invalid.
6631 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`,"fizz":"buzz"}`), B: 2}),
6632 }, {
6633 name: jsontest.Name("Structs/InlinedFallback/TextValue/MergeInvalidValue"),
6634 inBuf: `{"A":1,"fizz":nil,"B":2}`,
6635 inVal: new(structInlineTextValue),
6636 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":`)}),
6637 wantErr: newInvalidCharacterError("i", "in literal null (expecting 'u')", len64(`{"A":1,"fizz":n`), "/fizz"),
6638 }, {
6639 name: jsontest.Name("Structs/InlinedFallback/TextValue/CaseSensitive"),
6640 inBuf: `{"A":1,"fizz":"buzz","B":2,"a":3}`,
6641 inVal: new(structInlineTextValue),
6642 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":"buzz","a":3}`), B: 2}),
6643 }, {
6644 name: jsontest.Name("Structs/InlinedFallback/TextValue/RejectDuplicateNames"),
6645 opts: []Options{jsontext.AllowDuplicateNames(false)},
6646 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
6647 inVal: new(structInlineTextValue),
6648 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":"buzz"}`), B: 2}),
6649 wantErr: newDuplicateNameError("", []byte(`"fizz"`), len64(`{"A":1,"fizz":"buzz","B":2,`)),
6650 }, {
6651 name: jsontest.Name("Structs/InlinedFallback/TextValue/AllowDuplicateNames"),
6652 opts: []Options{jsontext.AllowDuplicateNames(true)},
6653 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
6654 inVal: new(structInlineTextValue),
6655 want: addr(structInlineTextValue{A: 1, X: jsontext.Value(`{"fizz":"buzz","fizz":"buzz"}`), B: 2}),
6656 }, {
6657 name: jsontest.Name("Structs/InlinedFallback/TextValue/Nested/Noop"),
6658 inBuf: `{}`,
6659 inVal: new(structInlinePointerInlineTextValue),
6660 want: new(structInlinePointerInlineTextValue),
6661 }, {
6662 name: jsontest.Name("Structs/InlinedFallback/TextValue/Nested/Alloc"),
6663 inBuf: `{"A":1,"fizz":"buzz"}`,
6664 inVal: new(structInlinePointerInlineTextValue),
6665 want: addr(structInlinePointerInlineTextValue{
6666 X: &struct {
6667 A int
6668 X jsontext.Value `json:",inline"`
6669 }{A: 1, X: jsontext.Value(`{"fizz":"buzz"}`)},
6670 }),
6671 }, {
6672 name: jsontest.Name("Structs/InlinedFallback/TextValue/Nested/Merge"),
6673 inBuf: `{"fizz":"buzz"}`,
6674 inVal: addr(structInlinePointerInlineTextValue{
6675 X: &struct {
6676 A int
6677 X jsontext.Value `json:",inline"`
6678 }{A: 1},
6679 }),
6680 want: addr(structInlinePointerInlineTextValue{
6681 X: &struct {
6682 A int
6683 X jsontext.Value `json:",inline"`
6684 }{A: 1, X: jsontext.Value(`{"fizz":"buzz"}`)},
6685 }),
6686 }, {
6687 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Noop"),
6688 inBuf: `{"A":1,"B":2}`,
6689 inVal: new(structInlinePointerTextValue),
6690 want: addr(structInlinePointerTextValue{A: 1, X: nil, B: 2}),
6691 }, {
6692 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Alloc"),
6693 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6694 inVal: new(structInlinePointerTextValue),
6695 want: addr(structInlinePointerTextValue{A: 1, X: addr(jsontext.Value(`{"fizz":"buzz"}`)), B: 2}),
6696 }, {
6697 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Merge"),
6698 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6699 inVal: addr(structInlinePointerTextValue{X: addr(jsontext.Value(`{"fizz":"buzz"}`))}),
6700 want: addr(structInlinePointerTextValue{A: 1, X: addr(jsontext.Value(`{"fizz":"buzz","fizz":"buzz"}`)), B: 2}),
6701 }, {
6702 name: jsontest.Name("Structs/InlinedFallback/PointerTextValue/Nested/Nil"),
6703 inBuf: `{"fizz":"buzz"}`,
6704 inVal: new(structInlineInlinePointerTextValue),
6705 want: addr(structInlineInlinePointerTextValue{
6706 X: struct {
6707 X *jsontext.Value `json:",inline"`
6708 }{X: addr(jsontext.Value(`{"fizz":"buzz"}`))},
6709 }),
6710 }, {
6711 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Noop"),
6712 inBuf: `{"A":1,"B":2}`,
6713 inVal: new(structInlineMapStringAny),
6714 want: addr(structInlineMapStringAny{A: 1, X: nil, B: 2}),
6715 }, {
6716 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeN1/Nil"),
6717 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6718 inVal: new(structInlineMapStringAny),
6719 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
6720 }, {
6721 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeN1/Empty"),
6722 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6723 inVal: addr(structInlineMapStringAny{X: jsonObject{}}),
6724 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
6725 }, {
6726 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeN1/ObjectN1"),
6727 inBuf: `{"A":1,"fizz":{"charlie":"DELTA","echo":"foxtrot"},"B":2}`,
6728 inVal: addr(structInlineMapStringAny{X: jsonObject{"fizz": jsonObject{
6729 "alpha": "bravo",
6730 "charlie": "delta",
6731 }}}),
6732 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": jsonObject{
6733 "alpha": "bravo",
6734 "charlie": "DELTA",
6735 "echo": "foxtrot",
6736 }}, B: 2}),
6737 }, {
6738 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeN2/ObjectN1"),
6739 inBuf: `{"A":1,"fizz":"buzz","B":2,"foo": [ 1 , 2 , 3 ]}`,
6740 inVal: addr(structInlineMapStringAny{X: jsonObject{"fizz": "wuzz"}}),
6741 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz", "foo": jsonArray{1.0, 2.0, 3.0}}, B: 2}),
6742 }, {
6743 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeInvalidValue"),
6744 inBuf: `{"A":1,"fizz":nil,"B":2}`,
6745 inVal: new(structInlineMapStringAny),
6746 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": nil}}),
6747 wantErr: newInvalidCharacterError("i", "in literal null (expecting 'u')", len64(`{"A":1,"fizz":n`), "/fizz"),
6748 }, {
6749 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/MergeInvalidValue/Existing"),
6750 inBuf: `{"A":1,"fizz":nil,"B":2}`,
6751 inVal: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": true}}),
6752 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": true}}),
6753 wantErr: newInvalidCharacterError("i", "in literal null (expecting 'u')", len64(`{"A":1,"fizz":n`), "/fizz"),
6754 }, {
6755 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/CaseSensitive"),
6756 inBuf: `{"A":1,"fizz":"buzz","B":2,"a":3}`,
6757 inVal: new(structInlineMapStringAny),
6758 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz", "a": 3.0}, B: 2}),
6759 }, {
6760 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/RejectDuplicateNames"),
6761 opts: []Options{jsontext.AllowDuplicateNames(false)},
6762 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
6763 inVal: new(structInlineMapStringAny),
6764 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": "buzz"}, B: 2}),
6765 wantErr: newDuplicateNameError("", []byte(`"fizz"`), len64(`{"A":1,"fizz":"buzz","B":2,`)),
6766 }, {
6767 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/AllowDuplicateNames"),
6768 opts: []Options{jsontext.AllowDuplicateNames(true)},
6769 inBuf: `{"A":1,"fizz":{"one":1,"two":-2},"B":2,"fizz":{"two":2,"three":3}}`,
6770 inVal: new(structInlineMapStringAny),
6771 want: addr(structInlineMapStringAny{A: 1, X: jsonObject{"fizz": jsonObject{"one": 1.0, "two": 2.0, "three": 3.0}}, B: 2}),
6772 }, {
6773 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Nested/Noop"),
6774 inBuf: `{}`,
6775 inVal: new(structInlinePointerInlineMapStringAny),
6776 want: new(structInlinePointerInlineMapStringAny),
6777 }, {
6778 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Nested/Alloc"),
6779 inBuf: `{"A":1,"fizz":"buzz"}`,
6780 inVal: new(structInlinePointerInlineMapStringAny),
6781 want: addr(structInlinePointerInlineMapStringAny{
6782 X: &struct {
6783 A int
6784 X jsonObject `json:",inline"`
6785 }{A: 1, X: jsonObject{"fizz": "buzz"}},
6786 }),
6787 }, {
6788 name: jsontest.Name("Structs/InlinedFallback/MapStringAny/Nested/Merge"),
6789 inBuf: `{"fizz":"buzz"}`,
6790 inVal: addr(structInlinePointerInlineMapStringAny{
6791 X: &struct {
6792 A int
6793 X jsonObject `json:",inline"`
6794 }{A: 1},
6795 }),
6796 want: addr(structInlinePointerInlineMapStringAny{
6797 X: &struct {
6798 A int
6799 X jsonObject `json:",inline"`
6800 }{A: 1, X: jsonObject{"fizz": "buzz"}},
6801 }),
6802 }, {
6803 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/UnmarshalFunc"),
6804 opts: []Options{
6805 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *any) error {
6806 var err error
6807 *v, err = strconv.ParseFloat(string(bytes.Trim(b, `"`)), 64)
6808 return err
6809 })),
6810 },
6811 inBuf: `{"D":"1.1","E":"2.2","F":"3.3"}`,
6812 inVal: new(structInlineMapStringAny),
6813 want: addr(structInlineMapStringAny{X: jsonObject{"D": 1.1, "E": 2.2, "F": 3.3}}),
6814 }, {
6815 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Noop"),
6816 inBuf: `{"A":1,"B":2}`,
6817 inVal: new(structInlinePointerMapStringAny),
6818 want: addr(structInlinePointerMapStringAny{A: 1, X: nil, B: 2}),
6819 }, {
6820 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Alloc"),
6821 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6822 inVal: new(structInlinePointerMapStringAny),
6823 want: addr(structInlinePointerMapStringAny{A: 1, X: addr(jsonObject{"fizz": "buzz"}), B: 2}),
6824 }, {
6825 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Merge"),
6826 inBuf: `{"A":1,"fizz":"wuzz","B":2}`,
6827 inVal: addr(structInlinePointerMapStringAny{X: addr(jsonObject{"fizz": "buzz"})}),
6828 want: addr(structInlinePointerMapStringAny{A: 1, X: addr(jsonObject{"fizz": "wuzz"}), B: 2}),
6829 }, {
6830 name: jsontest.Name("Structs/InlinedFallback/PointerMapStringAny/Nested/Nil"),
6831 inBuf: `{"fizz":"buzz"}`,
6832 inVal: new(structInlineInlinePointerMapStringAny),
6833 want: addr(structInlineInlinePointerMapStringAny{
6834 X: struct {
6835 X *jsonObject `json:",inline"`
6836 }{X: addr(jsonObject{"fizz": "buzz"})},
6837 }),
6838 }, {
6839 name: jsontest.Name("Structs/InlinedFallback/MapStringInt"),
6840 inBuf: `{"zero": 0, "one": 1, "two": 2}`,
6841 inVal: new(structInlineMapStringInt),
6842 want: addr(structInlineMapStringInt{
6843 X: map[string]int{"zero": 0, "one": 1, "two": 2},
6844 }),
6845 }, {
6846 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/Null"),
6847 inBuf: `{"zero": 0, "one": null, "two": 2}`,
6848 inVal: new(structInlineMapStringInt),
6849 want: addr(structInlineMapStringInt{
6850 X: map[string]int{"zero": 0, "one": 0, "two": 2},
6851 }),
6852 }, {
6853 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/Invalid"),
6854 inBuf: `{"zero": 0, "one": {}, "two": 2}`,
6855 inVal: new(structInlineMapStringInt),
6856 want: addr(structInlineMapStringInt{
6857 X: map[string]int{"zero": 0, "one": 0},
6858 }),
6859 wantErr: EU(nil).withPos(`{"zero": 0, "one": `, "/one").withType('{', T[int]()),
6860 }, {
6861 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/StringifiedNumbers"),
6862 opts: []Options{StringifyNumbers(true)},
6863 inBuf: `{"zero": "0", "one": "1", "two": "2"}`,
6864 inVal: new(structInlineMapStringInt),
6865 want: addr(structInlineMapStringInt{
6866 X: map[string]int{"zero": 0, "one": 1, "two": 2},
6867 }),
6868 }, {
6869 name: jsontest.Name("Structs/InlinedFallback/MapStringInt/UnmarshalFunc"),
6870 opts: []Options{
6871 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *int) error {
6872 i, err := strconv.ParseInt(string(bytes.Trim(b, `"`)), 10, 64)
6873 if err != nil {
6874 return err
6875 }
6876 *v = int(i)
6877 return nil
6878 })),
6879 },
6880 inBuf: `{"zero": "0", "one": "1", "two": "2"}`,
6881 inVal: new(structInlineMapStringInt),
6882 want: addr(structInlineMapStringInt{
6883 X: map[string]int{"zero": 0, "one": 1, "two": 2},
6884 }),
6885 }, {
6886 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt"),
6887 inBuf: `{"zero": 0, "one": 1, "two": 2}`,
6888 inVal: new(structInlineMapNamedStringInt),
6889 want: addr(structInlineMapNamedStringInt{
6890 X: map[namedString]int{"zero": 0, "one": 1, "two": 2},
6891 }),
6892 }, {
6893 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt/Null"),
6894 inBuf: `{"zero": 0, "one": null, "two": 2}`,
6895 inVal: new(structInlineMapNamedStringInt),
6896 want: addr(structInlineMapNamedStringInt{
6897 X: map[namedString]int{"zero": 0, "one": 0, "two": 2},
6898 }),
6899 }, {
6900 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt/Invalid"),
6901 inBuf: `{"zero": 0, "one": {}, "two": 2}`,
6902 inVal: new(structInlineMapNamedStringInt),
6903 want: addr(structInlineMapNamedStringInt{
6904 X: map[namedString]int{"zero": 0, "one": 0},
6905 }),
6906 wantErr: EU(nil).withPos(`{"zero": 0, "one": `, "/one").withType('{', T[int]()),
6907 }, {
6908 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt/StringifiedNumbers"),
6909 opts: []Options{StringifyNumbers(true)},
6910 inBuf: `{"zero": "0", "one": 1, "two": "2"}`,
6911 inVal: new(structInlineMapNamedStringInt),
6912 want: addr(structInlineMapNamedStringInt{
6913 X: map[namedString]int{"zero": 0, "one": 0},
6914 }),
6915 wantErr: EU(nil).withPos(`{"zero": "0", "one": `, "/one").withType('0', T[int]()),
6916 }, {
6917 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringInt/UnmarshalFunc"),
6918 opts: []Options{
6919 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *int) error {
6920 i, err := strconv.ParseInt(string(bytes.Trim(b, `"`)), 10, 64)
6921 if err != nil {
6922 return err
6923 }
6924 *v = int(i)
6925 return nil
6926 })),
6927 },
6928 inBuf: `{"zero": "0", "one": "1", "two": "2"}`,
6929 inVal: new(structInlineMapNamedStringInt),
6930 want: addr(structInlineMapNamedStringInt{
6931 X: map[namedString]int{"zero": 0, "one": 1, "two": 2},
6932 }),
6933 }, {
6934 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/Noop"),
6935 inBuf: `{"A":1,"B":2}`,
6936 inVal: new(structInlineMapNamedStringAny),
6937 want: addr(structInlineMapNamedStringAny{A: 1, X: nil, B: 2}),
6938 }, {
6939 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeN1/Nil"),
6940 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6941 inVal: new(structInlineMapNamedStringAny),
6942 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": "buzz"}, B: 2}),
6943 }, {
6944 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeN1/Empty"),
6945 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6946 inVal: addr(structInlineMapNamedStringAny{X: map[namedString]any{}}),
6947 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": "buzz"}, B: 2}),
6948 }, {
6949 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeN1/ObjectN1"),
6950 inBuf: `{"A":1,"fizz":{"charlie":"DELTA","echo":"foxtrot"},"B":2}`,
6951 inVal: addr(structInlineMapNamedStringAny{X: map[namedString]any{"fizz": jsonObject{
6952 "alpha": "bravo",
6953 "charlie": "delta",
6954 }}}),
6955 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": jsonObject{
6956 "alpha": "bravo",
6957 "charlie": "DELTA",
6958 "echo": "foxtrot",
6959 }}, B: 2}),
6960 }, {
6961 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeN2/ObjectN1"),
6962 inBuf: `{"A":1,"fizz":"buzz","B":2,"foo": [ 1 , 2 , 3 ]}`,
6963 inVal: addr(structInlineMapNamedStringAny{X: map[namedString]any{"fizz": "wuzz"}}),
6964 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": "buzz", "foo": jsonArray{1.0, 2.0, 3.0}}, B: 2}),
6965 }, {
6966 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeInvalidValue"),
6967 inBuf: `{"A":1,"fizz":nil,"B":2}`,
6968 inVal: new(structInlineMapNamedStringAny),
6969 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": nil}}),
6970 wantErr: newInvalidCharacterError("i", "in literal null (expecting 'u')", len64(`{"A":1,"fizz":n`), "/fizz"),
6971 }, {
6972 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/MergeInvalidValue/Existing"),
6973 inBuf: `{"A":1,"fizz":nil,"B":2}`,
6974 inVal: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": true}}),
6975 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": true}}),
6976 wantErr: newInvalidCharacterError("i", "in literal null (expecting 'u')", len64(`{"A":1,"fizz":n`), "/fizz"),
6977 }, {
6978 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/CaseSensitive"),
6979 inBuf: `{"A":1,"fizz":"buzz","B":2,"a":3}`,
6980 inVal: new(structInlineMapNamedStringAny),
6981 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": "buzz", "a": 3.0}, B: 2}),
6982 }, {
6983 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/RejectDuplicateNames"),
6984 opts: []Options{jsontext.AllowDuplicateNames(false)},
6985 inBuf: `{"A":1,"fizz":"buzz","B":2,"fizz":"buzz"}`,
6986 inVal: new(structInlineMapNamedStringAny),
6987 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": "buzz"}, B: 2}),
6988 wantErr: newDuplicateNameError("", []byte(`"fizz"`), len64(`{"A":1,"fizz":"buzz","B":2,`)),
6989 }, {
6990 name: jsontest.Name("Structs/InlinedFallback/MapNamedStringAny/AllowDuplicateNames"),
6991 opts: []Options{jsontext.AllowDuplicateNames(true)},
6992 inBuf: `{"A":1,"fizz":{"one":1,"two":-2},"B":2,"fizz":{"two":2,"three":3}}`,
6993 inVal: new(structInlineMapNamedStringAny),
6994 want: addr(structInlineMapNamedStringAny{A: 1, X: map[namedString]any{"fizz": map[string]any{"one": 1.0, "two": 2.0, "three": 3.0}}, B: 2}),
6995 }, {
6996 name: jsontest.Name("Structs/InlinedFallback/RejectUnknownMembers"),
6997 opts: []Options{RejectUnknownMembers(true)},
6998 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
6999 inVal: new(structInlineTextValue),
7000 // NOTE: DiscardUnknownMembers has no effect since this is "inline".
7001 want: addr(structInlineTextValue{
7002 A: 1,
7003 X: jsontext.Value(`{"fizz":"buzz"}`),
7004 B: 2,
7005 }),
7006 }, {
7007 name: jsontest.Name("Structs/UnknownFallback/RejectUnknownMembers"),
7008 opts: []Options{RejectUnknownMembers(true)},
7009 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
7010 inVal: new(structUnknownTextValue),
7011 want: addr(structUnknownTextValue{A: 1}),
7012 wantErr: EU(ErrUnknownName).withPos(`{"A":1,`, "/fizz").withType('"', T[structUnknownTextValue]()),
7013 }, {
7014 name: jsontest.Name("Structs/UnknownFallback"),
7015 inBuf: `{"A":1,"fizz":"buzz","B":2}`,
7016 inVal: new(structUnknownTextValue),
7017 want: addr(structUnknownTextValue{
7018 A: 1,
7019 X: jsontext.Value(`{"fizz":"buzz"}`),
7020 B: 2,
7021 }),
7022 }, {
7023 name: jsontest.Name("Structs/UnknownIgnored"),
7024 opts: []Options{RejectUnknownMembers(false)},
7025 inBuf: `{"unknown":"fizzbuzz"}`,
7026 inVal: new(structAll),
7027 want: new(structAll),
7028 }, {
7029 name: jsontest.Name("Structs/RejectUnknownMembers"),
7030 opts: []Options{RejectUnknownMembers(true)},
7031 inBuf: `{"unknown":"fizzbuzz"}`,
7032 inVal: new(structAll),
7033 want: new(structAll),
7034 wantErr: EU(ErrUnknownName).withPos(`{`, "/unknown").withType('"', T[structAll]()),
7035 }, {
7036 name: jsontest.Name("Structs/UnexportedIgnored"),
7037 inBuf: `{"ignored":"unused"}`,
7038 inVal: new(structUnexportedIgnored),
7039 want: new(structUnexportedIgnored),
7040 }, {
7041 name: jsontest.Name("Structs/IgnoredUnexportedEmbedded"),
7042 inBuf: `{"namedString":"unused"}`,
7043 inVal: new(structIgnoredUnexportedEmbedded),
7044 want: new(structIgnoredUnexportedEmbedded),
7045 }, {
7046 name: jsontest.Name("Structs/WeirdNames"),
7047 inBuf: `{"":"empty",",":"comma","\"":"quote"}`,
7048 inVal: new(structWeirdNames),
7049 want: addr(structWeirdNames{Empty: "empty", Comma: "comma", Quote: "quote"}),
7050 }, {
7051 name: jsontest.Name("Structs/NoCase/Exact"),
7052 inBuf: `{"Aaa":"Aaa","AA_A":"AA_A","AaA":"AaA","AAa":"AAa","AAA":"AAA"}`,
7053 inVal: new(structNoCase),
7054 want: addr(structNoCase{AaA: "AaA", AAa: "AAa", Aaa: "Aaa", AAA: "AAA", AA_A: "AA_A"}),
7055 }, {
7056 name: jsontest.Name("Structs/NoCase/CaseInsensitiveDefault"),
7057 inBuf: `{"aa_a":"aa_a"}`,
7058 inVal: new(structNoCase),
7059 want: addr(structNoCase{AaA: "aa_a"}),
7060 }, {
7061 name: jsontest.Name("Structs/NoCase/MatchCaseSensitiveDelimiter"),
7062 opts: []Options{jsonflags.MatchCaseSensitiveDelimiter | 1},
7063 inBuf: `{"aa_a":"aa_a"}`,
7064 inVal: new(structNoCase),
7065 want: addr(structNoCase{}),
7066 }, {
7067 name: jsontest.Name("Structs/NoCase/MatchCaseInsensitiveNames+MatchCaseSensitiveDelimiter"),
7068 opts: []Options{MatchCaseInsensitiveNames(true), jsonflags.MatchCaseSensitiveDelimiter | 1},
7069 inBuf: `{"aa_a":"aa_a"}`,
7070 inVal: new(structNoCase),
7071 want: addr(structNoCase{AA_A: "aa_a"}),
7072 }, {
7073 name: jsontest.Name("Structs/NoCase/Merge/AllowDuplicateNames"),
7074 opts: []Options{jsontext.AllowDuplicateNames(true)},
7075 inBuf: `{"AaA":"AaA","aaa":"aaa","aAa":"aAa"}`,
7076 inVal: new(structNoCase),
7077 want: addr(structNoCase{AaA: "aAa"}),
7078 }, {
7079 name: jsontest.Name("Structs/NoCase/Merge/RejectDuplicateNames"),
7080 opts: []Options{jsontext.AllowDuplicateNames(false)},
7081 inBuf: `{"AaA":"AaA","aaa":"aaa"}`,
7082 inVal: new(structNoCase),
7083 want: addr(structNoCase{AaA: "AaA"}),
7084 wantErr: newDuplicateNameError("", []byte(`"aaa"`), len64(`{"AaA":"AaA",`)),
7085 }, {
7086 name: jsontest.Name("Structs/CaseSensitive"),
7087 inBuf: `{"BOOL": true, "STRING": "hello", "BYTES": "AQID", "INT": -64, "UINT": 64, "FLOAT": 3.14159}`,
7088 inVal: new(structScalars),
7089 want: addr(structScalars{}),
7090 }, {
7091 name: jsontest.Name("Structs/DuplicateName/NoCase/ExactDifferent"),
7092 inBuf: `{"AAA":"AAA","AaA":"AaA","AAa":"AAa","Aaa":"Aaa"}`,
7093 inVal: addr(structNoCaseInlineTextValue{}),
7094 want: addr(structNoCaseInlineTextValue{AAA: "AAA", AaA: "AaA", AAa: "AAa", Aaa: "Aaa"}),
7095 }, {
7096 name: jsontest.Name("Structs/DuplicateName/NoCase/ExactConflict"),
7097 inBuf: `{"AAA":"AAA","AAA":"AAA"}`,
7098 inVal: addr(structNoCaseInlineTextValue{}),
7099 want: addr(structNoCaseInlineTextValue{AAA: "AAA"}),
7100 wantErr: newDuplicateNameError("", []byte(`"AAA"`), len64(`{"AAA":"AAA",`)),
7101 }, {
7102 name: jsontest.Name("Structs/DuplicateName/NoCase/OverwriteExact"),
7103 inBuf: `{"AAA":"after"}`,
7104 inVal: addr(structNoCaseInlineTextValue{AAA: "before"}),
7105 want: addr(structNoCaseInlineTextValue{AAA: "after"}),
7106 }, {
7107 name: jsontest.Name("Structs/DuplicateName/NoCase/NoCaseConflict"),
7108 inBuf: `{"aaa":"aaa","aaA":"aaA"}`,
7109 inVal: addr(structNoCaseInlineTextValue{}),
7110 want: addr(structNoCaseInlineTextValue{AaA: "aaa"}),
7111 wantErr: newDuplicateNameError("", []byte(`"aaA"`), len64(`{"aaa":"aaa",`)),
7112 }, {
7113 name: jsontest.Name("Structs/DuplicateName/NoCase/OverwriteNoCase"),
7114 inBuf: `{"aaa":"aaa","aaA":"aaA"}`,
7115 inVal: addr(structNoCaseInlineTextValue{}),
7116 want: addr(structNoCaseInlineTextValue{AaA: "aaa"}),
7117 wantErr: newDuplicateNameError("", []byte(`"aaA"`), len64(`{"aaa":"aaa",`)),
7118 }, {
7119 name: jsontest.Name("Structs/DuplicateName/Inline/Unknown"),
7120 inBuf: `{"unknown":""}`,
7121 inVal: addr(structNoCaseInlineTextValue{}),
7122 want: addr(structNoCaseInlineTextValue{X: jsontext.Value(`{"unknown":""}`)}),
7123 }, {
7124 name: jsontest.Name("Structs/DuplicateName/Inline/UnknownMerge"),
7125 inBuf: `{"unknown":""}`,
7126 inVal: addr(structNoCaseInlineTextValue{X: jsontext.Value(`{"unknown":""}`)}),
7127 want: addr(structNoCaseInlineTextValue{X: jsontext.Value(`{"unknown":"","unknown":""}`)}),
7128 }, {
7129 name: jsontest.Name("Structs/DuplicateName/Inline/NoCaseOkay"),
7130 inBuf: `{"b":"","B":""}`,
7131 inVal: addr(structNoCaseInlineTextValue{}),
7132 want: addr(structNoCaseInlineTextValue{X: jsontext.Value(`{"b":"","B":""}`)}),
7133 }, {
7134 name: jsontest.Name("Structs/DuplicateName/Inline/ExactConflict"),
7135 inBuf: `{"b":"","b":""}`,
7136 inVal: addr(structNoCaseInlineTextValue{}),
7137 want: addr(structNoCaseInlineTextValue{X: jsontext.Value(`{"b":""}`)}),
7138 wantErr: newDuplicateNameError("", []byte(`"b"`), len64(`{"b":"",`)),
7139 }, {
7140 name: jsontest.Name("Structs/Invalid/ErrUnexpectedEOF"),
7141 inBuf: ``,
7142 inVal: addr(structAll{}),
7143 want: addr(structAll{}),
7144 wantErr: &jsontext.SyntacticError{Err: io.ErrUnexpectedEOF},
7145 }, {
7146 name: jsontest.Name("Structs/Invalid/ErrUnexpectedEOF"),
7147 inBuf: " \n\r\t",
7148 inVal: addr(structAll{}),
7149 want: addr(structAll{}),
7150 wantErr: &jsontext.SyntacticError{Err: io.ErrUnexpectedEOF, ByteOffset: len64(" \n\r\t")},
7151 }, {
7152 name: jsontest.Name("Structs/Invalid/NestedErrUnexpectedEOF"),
7153 inBuf: `{"Pointer":`,
7154 inVal: addr(structAll{}),
7155 want: addr(structAll{Pointer: new(structAll)}),
7156 wantErr: &jsontext.SyntacticError{ByteOffset: len64(`{"Pointer":`), JSONPointer: "/Pointer", Err: io.ErrUnexpectedEOF},
7157 }, {
7158 name: jsontest.Name("Structs/Invalid/Conflicting"),
7159 inBuf: `{}`,
7160 inVal: addr(structConflicting{}),
7161 want: addr(structConflicting{}),
7162 wantErr: EU(errors.New(`Go struct fields A and B conflict over JSON object name "conflict"`)).withType('{', T[structConflicting]()),
7163 }, {
7164 name: jsontest.Name("Structs/Invalid/NoneExported"),
7165 inBuf: ` {}`,
7166 inVal: addr(structNoneExported{}),
7167 want: addr(structNoneExported{}),
7168 wantErr: EU(errNoExportedFields).withPos(` `, "").withType('{', T[structNoneExported]()),
7169 }, {
7170 name: jsontest.Name("Structs/Invalid/MalformedTag"),
7171 inBuf: `{}`,
7172 inVal: addr(structMalformedTag{}),
7173 want: addr(structMalformedTag{}),
7174 wantErr: EU(errors.New("Go struct field Malformed has malformed `json` tag: invalid character '\"' at start of option (expecting Unicode letter or single quote)")).withType('{', T[structMalformedTag]()),
7175 }, {
7176 name: jsontest.Name("Structs/Invalid/UnexportedTag"),
7177 inBuf: `{}`,
7178 inVal: addr(structUnexportedTag{}),
7179 want: addr(structUnexportedTag{}),
7180 wantErr: EU(errors.New("unexported Go struct field unexported cannot have non-ignored `json:\"name\"` tag")).withType('{', T[structUnexportedTag]()),
7181 }, {
7182 name: jsontest.Name("Structs/Invalid/ExportedEmbedded"),
7183 inBuf: `{"NamedString":"hello"}`,
7184 inVal: addr(structExportedEmbedded{}),
7185 want: addr(structExportedEmbedded{}),
7186 wantErr: EU(errors.New("embedded Go struct field NamedString of non-struct type must be explicitly given a JSON name")).withType('{', T[structExportedEmbedded]()),
7187 }, {
7188 name: jsontest.Name("Structs/Valid/ExportedEmbedded"),
7189 opts: []Options{jsonflags.ReportErrorsWithLegacySemantics | 1},
7190 inBuf: `{"NamedString":"hello"}`,
7191 inVal: addr(structExportedEmbedded{}),
7192 want: addr(structExportedEmbedded{"hello"}),
7193 }, {
7194 name: jsontest.Name("Structs/Valid/ExportedEmbeddedTag"),
7195 inBuf: `{"name":"hello"}`,
7196 inVal: addr(structExportedEmbeddedTag{}),
7197 want: addr(structExportedEmbeddedTag{"hello"}),
7198 }, {
7199 name: jsontest.Name("Structs/Invalid/UnexportedEmbedded"),
7200 inBuf: `{}`,
7201 inVal: addr(structUnexportedEmbedded{}),
7202 want: addr(structUnexportedEmbedded{}),
7203 wantErr: EU(errors.New("embedded Go struct field namedString of non-struct type must be explicitly given a JSON name")).withType('{', T[structUnexportedEmbedded]()),
7204 }, {
7205 name: jsontest.Name("Structs/UnexportedEmbeddedStruct"),
7206 inBuf: `{"Bool":true,"FizzBuzz":5,"Addr":"192.168.0.1"}`,
7207 inVal: addr(structUnexportedEmbeddedStruct{}),
7208 want: addr(structUnexportedEmbeddedStruct{structOmitZeroAll{Bool: true}, 5, structNestedAddr{netip.AddrFrom4([4]byte{192, 168, 0, 1})}}),
7209 }, {
7210 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/Nil"),
7211 inBuf: `{"Bool":true,"FizzBuzz":5}`,
7212 inVal: addr(structUnexportedEmbeddedStructPointer{}),
7213 wantErr: EU(errNilField).withPos(`{"Bool":`, "/Bool").withType(0, T[structUnexportedEmbeddedStructPointer]()),
7214 }, {
7215 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/Nil"),
7216 inBuf: `{"FizzBuzz":5,"Addr":"192.168.0.1"}`,
7217 inVal: addr(structUnexportedEmbeddedStructPointer{}),
7218 wantErr: EU(errNilField).withPos(`{"FizzBuzz":5,"Addr":`, "/Addr").withType(0, T[structUnexportedEmbeddedStructPointer]()),
7219 }, {
7220 name: jsontest.Name("Structs/UnexportedEmbeddedStructPointer/Nil"),
7221 inBuf: `{"Bool":true,"FizzBuzz":10,"Addr":"192.168.0.1"}`,
7222 inVal: addr(structUnexportedEmbeddedStructPointer{&structOmitZeroAll{Int: 5}, 5, &structNestedAddr{netip.AddrFrom4([4]byte{127, 0, 0, 1})}}),
7223 want: addr(structUnexportedEmbeddedStructPointer{&structOmitZeroAll{Bool: true, Int: 5}, 10, &structNestedAddr{netip.AddrFrom4([4]byte{192, 168, 0, 1})}}),
7224 }, {
7225 name: jsontest.Name("Structs/Unknown"),
7226 inBuf: `{
7227 "object0": {},
7228 "object1": {"key1": "value"},
7229 "object2": {"key1": "value", "key2": "value"},
7230 "objects": {"":{"":{"":{}}}},
7231 "array0": [],
7232 "array1": ["value1"],
7233 "array2": ["value1", "value2"],
7234 "array": [[[]]],
7235 "scalars": [null, false, true, "string", 12.345]
7236 }`,
7237 inVal: addr(struct{}{}),
7238 want: addr(struct{}{}),
7239 }, {
7240 name: jsontest.Name("Structs/IgnoreInvalidFormat"),
7241 opts: []Options{invalidFormatOption},
7242 inBuf: `{"Field":"Value"}`,
7243 inVal: addr(struct{ Field string }{}),
7244 want: addr(struct{ Field string }{"Value"}),
7245 }, {
7246 name: jsontest.Name("Slices/Null"),
7247 inBuf: `null`,
7248 inVal: addr([]string{"something"}),
7249 want: addr([]string(nil)),
7250 }, {
7251 name: jsontest.Name("Slices/Bool"),
7252 inBuf: `[true,false]`,
7253 inVal: new([]bool),
7254 want: addr([]bool{true, false}),
7255 }, {
7256 name: jsontest.Name("Slices/String"),
7257 inBuf: `["hello","goodbye"]`,
7258 inVal: new([]string),
7259 want: addr([]string{"hello", "goodbye"}),
7260 }, {
7261 name: jsontest.Name("Slices/Bytes"),
7262 inBuf: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
7263 inVal: new([][]byte),
7264 want: addr([][]byte{[]byte("hello"), []byte("goodbye")}),
7265 }, {
7266 name: jsontest.Name("Slices/Int"),
7267 inBuf: `[-2,-1,0,1,2]`,
7268 inVal: new([]int),
7269 want: addr([]int{-2, -1, 0, 1, 2}),
7270 }, {
7271 name: jsontest.Name("Slices/Uint"),
7272 inBuf: `[0,1,2,3,4]`,
7273 inVal: new([]uint),
7274 want: addr([]uint{0, 1, 2, 3, 4}),
7275 }, {
7276 name: jsontest.Name("Slices/Float"),
7277 inBuf: `[3.14159,12.34]`,
7278 inVal: new([]float64),
7279 want: addr([]float64{3.14159, 12.34}),
7280 }, {
7281 // NOTE: The semantics differs from v1, where the slice length is reset
7282 // and new elements are appended to the end.
7283 // See https://go.dev/issue/21092.
7284 name: jsontest.Name("Slices/Merge"),
7285 inBuf: `[{"k3":"v3"},{"k4":"v4"}]`,
7286 inVal: addr([]map[string]string{{"k1": "v1"}, {"k2": "v2"}}[:1]),
7287 want: addr([]map[string]string{{"k3": "v3"}, {"k4": "v4"}}),
7288 }, {
7289 name: jsontest.Name("Slices/Invalid/Channel"),
7290 inBuf: `["hello"]`,
7291 inVal: new([]chan string),
7292 want: addr([]chan string{nil}),
7293 wantErr: EU(nil).withPos(`[`, "/0").withType(0, T[chan string]()),
7294 }, {
7295 name: jsontest.Name("Slices/RecursiveSlice"),
7296 inBuf: `[[],[],[[]],[[],[]]]`,
7297 inVal: new(recursiveSlice),
7298 want: addr(recursiveSlice{
7299 {},
7300 {},
7301 {{}},
7302 {{}, {}},
7303 }),
7304 }, {
7305 name: jsontest.Name("Slices/Invalid/Bool"),
7306 inBuf: `true`,
7307 inVal: addr([]string{"nochange"}),
7308 want: addr([]string{"nochange"}),
7309 wantErr: EU(nil).withType('t', T[[]string]()),
7310 }, {
7311 name: jsontest.Name("Slices/Invalid/String"),
7312 inBuf: `""`,
7313 inVal: addr([]string{"nochange"}),
7314 want: addr([]string{"nochange"}),
7315 wantErr: EU(nil).withType('"', T[[]string]()),
7316 }, {
7317 name: jsontest.Name("Slices/Invalid/Number"),
7318 inBuf: `0`,
7319 inVal: addr([]string{"nochange"}),
7320 want: addr([]string{"nochange"}),
7321 wantErr: EU(nil).withType('0', T[[]string]()),
7322 }, {
7323 name: jsontest.Name("Slices/Invalid/Object"),
7324 inBuf: `{}`,
7325 inVal: addr([]string{"nochange"}),
7326 want: addr([]string{"nochange"}),
7327 wantErr: EU(nil).withType('{', T[[]string]()),
7328 }, {
7329 name: jsontest.Name("Slices/IgnoreInvalidFormat"),
7330 opts: []Options{invalidFormatOption},
7331 inBuf: `[false,true]`,
7332 inVal: addr([]bool{true, false}),
7333 want: addr([]bool{false, true}),
7334 }, {
7335 name: jsontest.Name("Arrays/Null"),
7336 inBuf: `null`,
7337 inVal: addr([1]string{"something"}),
7338 want: addr([1]string{}),
7339 }, {
7340 name: jsontest.Name("Arrays/Bool"),
7341 inBuf: `[true,false]`,
7342 inVal: new([2]bool),
7343 want: addr([2]bool{true, false}),
7344 }, {
7345 name: jsontest.Name("Arrays/String"),
7346 inBuf: `["hello","goodbye"]`,
7347 inVal: new([2]string),
7348 want: addr([2]string{"hello", "goodbye"}),
7349 }, {
7350 name: jsontest.Name("Arrays/Bytes"),
7351 inBuf: `["aGVsbG8=","Z29vZGJ5ZQ=="]`,
7352 inVal: new([2][]byte),
7353 want: addr([2][]byte{[]byte("hello"), []byte("goodbye")}),
7354 }, {
7355 name: jsontest.Name("Arrays/Int"),
7356 inBuf: `[-2,-1,0,1,2]`,
7357 inVal: new([5]int),
7358 want: addr([5]int{-2, -1, 0, 1, 2}),
7359 }, {
7360 name: jsontest.Name("Arrays/Uint"),
7361 inBuf: `[0,1,2,3,4]`,
7362 inVal: new([5]uint),
7363 want: addr([5]uint{0, 1, 2, 3, 4}),
7364 }, {
7365 name: jsontest.Name("Arrays/Float"),
7366 inBuf: `[3.14159,12.34]`,
7367 inVal: new([2]float64),
7368 want: addr([2]float64{3.14159, 12.34}),
7369 }, {
7370 // NOTE: The semantics differs from v1, where elements are not merged.
7371 // This is to maintain consistent merge semantics with slices.
7372 name: jsontest.Name("Arrays/Merge"),
7373 inBuf: `[{"k3":"v3"},{"k4":"v4"}]`,
7374 inVal: addr([2]map[string]string{{"k1": "v1"}, {"k2": "v2"}}),
7375 want: addr([2]map[string]string{{"k3": "v3"}, {"k4": "v4"}}),
7376 }, {
7377 name: jsontest.Name("Arrays/Invalid/Channel"),
7378 inBuf: `["hello"]`,
7379 inVal: new([1]chan string),
7380 want: new([1]chan string),
7381 wantErr: EU(nil).withPos(`[`, "/0").withType(0, T[chan string]()),
7382 }, {
7383 name: jsontest.Name("Arrays/Invalid/Underflow"),
7384 inBuf: `{"F":[ ]}`,
7385 inVal: new(struct{ F [1]string }),
7386 want: addr(struct{ F [1]string }{}),
7387 wantErr: EU(errArrayUnderflow).withPos(`{"F":[ `, "/F").withType(']', T[[1]string]()),
7388 }, {
7389 name: jsontest.Name("Arrays/Invalid/Underflow/UnmarshalArrayFromAnyLength"),
7390 opts: []Options{jsonflags.UnmarshalArrayFromAnyLength | 1},
7391 inBuf: `[-1,-2]`,
7392 inVal: addr([4]int{1, 2, 3, 4}),
7393 want: addr([4]int{-1, -2, 0, 0}),
7394 }, {
7395 name: jsontest.Name("Arrays/Invalid/Overflow"),
7396 inBuf: `["1","2"]`,
7397 inVal: new([1]string),
7398 want: addr([1]string{"1"}),
7399 wantErr: EU(errArrayOverflow).withPos(`["1","2"`, "").withType(']', T[[1]string]()),
7400 }, {
7401 name: jsontest.Name("Arrays/Invalid/Overflow/UnmarshalArrayFromAnyLength"),
7402 opts: []Options{jsonflags.UnmarshalArrayFromAnyLength | 1},
7403 inBuf: `[-1,-2,-3,-4,-5,-6]`,
7404 inVal: addr([4]int{1, 2, 3, 4}),
7405 want: addr([4]int{-1, -2, -3, -4}),
7406 }, {
7407 name: jsontest.Name("Arrays/Invalid/Bool"),
7408 inBuf: `true`,
7409 inVal: addr([1]string{"nochange"}),
7410 want: addr([1]string{"nochange"}),
7411 wantErr: EU(nil).withType('t', T[[1]string]()),
7412 }, {
7413 name: jsontest.Name("Arrays/Invalid/String"),
7414 inBuf: `""`,
7415 inVal: addr([1]string{"nochange"}),
7416 want: addr([1]string{"nochange"}),
7417 wantErr: EU(nil).withType('"', T[[1]string]()),
7418 }, {
7419 name: jsontest.Name("Arrays/Invalid/Number"),
7420 inBuf: `0`,
7421 inVal: addr([1]string{"nochange"}),
7422 want: addr([1]string{"nochange"}),
7423 wantErr: EU(nil).withType('0', T[[1]string]()),
7424 }, {
7425 name: jsontest.Name("Arrays/Invalid/Object"),
7426 inBuf: `{}`,
7427 inVal: addr([1]string{"nochange"}),
7428 want: addr([1]string{"nochange"}),
7429 wantErr: EU(nil).withType('{', T[[1]string]()),
7430 }, {
7431 name: jsontest.Name("Arrays/IgnoreInvalidFormat"),
7432 opts: []Options{invalidFormatOption},
7433 inBuf: `[false,true]`,
7434 inVal: addr([2]bool{true, false}),
7435 want: addr([2]bool{false, true}),
7436 }, {
7437 name: jsontest.Name("Pointers/NullL0"),
7438 inBuf: `null`,
7439 inVal: new(*string),
7440 want: addr((*string)(nil)),
7441 }, {
7442 name: jsontest.Name("Pointers/NullL1"),
7443 inBuf: `null`,
7444 inVal: addr(new(*string)),
7445 want: addr((**string)(nil)),
7446 }, {
7447 name: jsontest.Name("Pointers/Bool"),
7448 inBuf: `true`,
7449 inVal: addr(new(bool)),
7450 want: addr(addr(true)),
7451 }, {
7452 name: jsontest.Name("Pointers/String"),
7453 inBuf: `"hello"`,
7454 inVal: addr(new(string)),
7455 want: addr(addr("hello")),
7456 }, {
7457 name: jsontest.Name("Pointers/Bytes"),
7458 inBuf: `"aGVsbG8="`,
7459 inVal: addr(new([]byte)),
7460 want: addr(addr([]byte("hello"))),
7461 }, {
7462 name: jsontest.Name("Pointers/Int"),
7463 inBuf: `-123`,
7464 inVal: addr(new(int)),
7465 want: addr(addr(int(-123))),
7466 }, {
7467 name: jsontest.Name("Pointers/Uint"),
7468 inBuf: `123`,
7469 inVal: addr(new(int)),
7470 want: addr(addr(int(123))),
7471 }, {
7472 name: jsontest.Name("Pointers/Float"),
7473 inBuf: `123.456`,
7474 inVal: addr(new(float64)),
7475 want: addr(addr(float64(123.456))),
7476 }, {
7477 name: jsontest.Name("Pointers/Allocate"),
7478 inBuf: `"hello"`,
7479 inVal: addr((*string)(nil)),
7480 want: addr(addr("hello")),
7481 }, {
7482 name: jsontest.Name("Points/IgnoreInvalidFormat"),
7483 opts: []Options{invalidFormatOption},
7484 inBuf: `true`,
7485 inVal: addr(new(bool)),
7486 want: addr(addr(true)),
7487 }, {
7488 name: jsontest.Name("Interfaces/Empty/Null"),
7489 inBuf: `null`,
7490 inVal: new(any),
7491 want: new(any),
7492 }, {
7493 name: jsontest.Name("Interfaces/NonEmpty/Null"),
7494 inBuf: `null`,
7495 inVal: new(io.Reader),
7496 want: new(io.Reader),
7497 }, {
7498 name: jsontest.Name("Interfaces/NonEmpty/Invalid"),
7499 inBuf: `"hello"`,
7500 inVal: new(io.Reader),
7501 want: new(io.Reader),
7502 wantErr: EU(internal.ErrNilInterface).withType(0, T[io.Reader]()),
7503 }, {
7504 name: jsontest.Name("Interfaces/Empty/False"),
7505 inBuf: `false`,
7506 inVal: new(any),
7507 want: func() any {
7508 var vi any = false
7509 return &vi
7510 }(),
7511 }, {
7512 name: jsontest.Name("Interfaces/Empty/True"),
7513 inBuf: `true`,
7514 inVal: new(any),
7515 want: func() any {
7516 var vi any = true
7517 return &vi
7518 }(),
7519 }, {
7520 name: jsontest.Name("Interfaces/Empty/String"),
7521 inBuf: `"string"`,
7522 inVal: new(any),
7523 want: func() any {
7524 var vi any = "string"
7525 return &vi
7526 }(),
7527 }, {
7528 name: jsontest.Name("Interfaces/Empty/Number"),
7529 inBuf: `3.14159`,
7530 inVal: new(any),
7531 want: func() any {
7532 var vi any = 3.14159
7533 return &vi
7534 }(),
7535 }, {
7536 name: jsontest.Name("Interfaces/Empty/Object"),
7537 inBuf: `{"k":"v"}`,
7538 inVal: new(any),
7539 want: func() any {
7540 var vi any = map[string]any{"k": "v"}
7541 return &vi
7542 }(),
7543 }, {
7544 name: jsontest.Name("Interfaces/Empty/Array"),
7545 inBuf: `["v"]`,
7546 inVal: new(any),
7547 want: func() any {
7548 var vi any = []any{"v"}
7549 return &vi
7550 }(),
7551 }, {
7552 name: jsontest.Name("Interfaces/NamedAny/String"),
7553 inBuf: `"string"`,
7554 inVal: new(namedAny),
7555 want: func() namedAny {
7556 var vi namedAny = "string"
7557 return &vi
7558 }(),
7559 }, {
7560 name: jsontest.Name("Interfaces/Invalid"),
7561 inBuf: `]`,
7562 inVal: new(any),
7563 want: new(any),
7564 wantErr: newInvalidCharacterError("]", "at start of value", 0, ""),
7565 }, {
7566 // NOTE: The semantics differs from v1,
7567 // where existing map entries were not merged into.
7568 // See https://go.dev/issue/26946.
7569 // See https://go.dev/issue/33993.
7570 name: jsontest.Name("Interfaces/Merge/Map"),
7571 inBuf: `{"k2":"v2"}`,
7572 inVal: func() any {
7573 var vi any = map[string]string{"k1": "v1"}
7574 return &vi
7575 }(),
7576 want: func() any {
7577 var vi any = map[string]string{"k1": "v1", "k2": "v2"}
7578 return &vi
7579 }(),
7580 }, {
7581 name: jsontest.Name("Interfaces/Merge/Struct"),
7582 inBuf: `{"Array":["goodbye"]}`,
7583 inVal: func() any {
7584 var vi any = structAll{String: "hello"}
7585 return &vi
7586 }(),
7587 want: func() any {
7588 var vi any = structAll{String: "hello", Array: [1]string{"goodbye"}}
7589 return &vi
7590 }(),
7591 }, {
7592 name: jsontest.Name("Interfaces/Merge/NamedInt"),
7593 inBuf: `64`,
7594 inVal: func() any {
7595 var vi any = namedInt64(-64)
7596 return &vi
7597 }(),
7598 want: func() any {
7599 var vi any = namedInt64(+64)
7600 return &vi
7601 }(),
7602 }, {
7603 name: jsontest.Name("Interfaces/IgnoreInvalidFormat"),
7604 opts: []Options{invalidFormatOption},
7605 inBuf: `true`,
7606 inVal: new(any),
7607 want: func() any {
7608 var vi any = true
7609 return &vi
7610 }(),
7611 }, {
7612 name: jsontest.Name("Interfaces/Any"),
7613 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7614 inVal: new(struct{ X any }),
7615 want: addr(struct{ X any }{[]any{nil, false, true, "", 0.0, map[string]any{}, []any{}}}),
7616 }, {
7617 name: jsontest.Name("Interfaces/Any/Named"),
7618 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7619 inVal: new(struct{ X namedAny }),
7620 want: addr(struct{ X namedAny }{[]any{nil, false, true, "", 0.0, map[string]any{}, []any{}}}),
7621 }, {
7622 name: jsontest.Name("Interfaces/Any/Stringified"),
7623 opts: []Options{StringifyNumbers(true)},
7624 inBuf: `{"X":"0"}`,
7625 inVal: new(struct{ X any }),
7626 want: addr(struct{ X any }{"0"}),
7627 }, {
7628 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/Any"),
7629 opts: []Options{
7630 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *any) error {
7631 *v = "called"
7632 return nil
7633 })),
7634 },
7635 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7636 inVal: new(struct{ X any }),
7637 want: addr(struct{ X any }{"called"}),
7638 }, {
7639 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/Bool"),
7640 opts: []Options{
7641 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *bool) error {
7642 *v = string(b) != "true"
7643 return nil
7644 })),
7645 },
7646 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7647 inVal: new(struct{ X any }),
7648 want: addr(struct{ X any }{[]any{nil, true, false, "", 0.0, map[string]any{}, []any{}}}),
7649 }, {
7650 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/String"),
7651 opts: []Options{
7652 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *string) error {
7653 *v = "called"
7654 return nil
7655 })),
7656 },
7657 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7658 inVal: new(struct{ X any }),
7659 want: addr(struct{ X any }{[]any{nil, false, true, "called", 0.0, map[string]any{}, []any{}}}),
7660 }, {
7661 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/Float64"),
7662 opts: []Options{
7663 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *float64) error {
7664 *v = 3.14159
7665 return nil
7666 })),
7667 },
7668 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7669 inVal: new(struct{ X any }),
7670 want: addr(struct{ X any }{[]any{nil, false, true, "", 3.14159, map[string]any{}, []any{}}}),
7671 }, {
7672 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/MapStringAny"),
7673 opts: []Options{
7674 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *map[string]any) error {
7675 *v = map[string]any{"called": nil}
7676 return nil
7677 })),
7678 },
7679 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7680 inVal: new(struct{ X any }),
7681 want: addr(struct{ X any }{[]any{nil, false, true, "", 0.0, map[string]any{"called": nil}, []any{}}}),
7682 }, {
7683 name: jsontest.Name("Interfaces/Any/UnmarshalFunc/SliceAny"),
7684 opts: []Options{
7685 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *[]any) error {
7686 *v = []any{"called"}
7687 return nil
7688 })),
7689 },
7690 inBuf: `{"X":[null,false,true,"",0,{},[]]}`,
7691 inVal: new(struct{ X any }),
7692 want: addr(struct{ X any }{[]any{"called"}}),
7693 }, {
7694 name: jsontest.Name("Interfaces/Any/Maps/NonEmpty"),
7695 inBuf: `{"X":{"fizz":"buzz"}}`,
7696 inVal: new(struct{ X any }),
7697 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
7698 }, {
7699 name: jsontest.Name("Interfaces/Any/Maps/RejectDuplicateNames"),
7700 inBuf: `{"X":{"fizz":"buzz","fizz":true}}`,
7701 inVal: new(struct{ X any }),
7702 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
7703 wantErr: newDuplicateNameError("/X", []byte(`"fizz"`), len64(`{"X":{"fizz":"buzz",`)),
7704 }, {
7705 name: jsontest.Name("Interfaces/Any/Maps/AllowDuplicateNames"),
7706 opts: []Options{jsontext.AllowDuplicateNames(true)},
7707 inBuf: `{"X":{"fizz":"buzz","fizz":true}}`,
7708 inVal: new(struct{ X any }),
7709 want: addr(struct{ X any }{map[string]any{"fizz": "buzz"}}),
7710 wantErr: EU(nil).withPos(`{"X":{"fizz":"buzz","fizz":`, "/X/fizz").withType('t', T[string]()),
7711 }, {
7712 name: jsontest.Name("Interfaces/Any/Slices/NonEmpty"),
7713 inBuf: `{"X":["fizz","buzz"]}`,
7714 inVal: new(struct{ X any }),
7715 want: addr(struct{ X any }{[]any{"fizz", "buzz"}}),
7716 }, {
7717 name: jsontest.Name("Methods/NilPointer/Null"),
7718 inBuf: `{"X":null}`,
7719 inVal: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}),
7720 want: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}), // method should not be called
7721 }, {
7722 name: jsontest.Name("Methods/NilPointer/Value"),
7723 inBuf: `{"X":"value"}`,
7724 inVal: addr(struct{ X *allMethods }{X: (*allMethods)(nil)}),
7725 want: addr(struct{ X *allMethods }{X: &allMethods{method: "UnmarshalJSONFrom", value: []byte(`"value"`)}}),
7726 }, {
7727 name: jsontest.Name("Methods/NilInterface/Null"),
7728 inBuf: `{"X":null}`,
7729 inVal: addr(struct{ X MarshalerTo }{X: (*allMethods)(nil)}),
7730 want: addr(struct{ X MarshalerTo }{X: nil}), // interface value itself is nil'd out
7731 }, {
7732 name: jsontest.Name("Methods/NilInterface/Value"),
7733 inBuf: `{"X":"value"}`,
7734 inVal: addr(struct{ X MarshalerTo }{X: (*allMethods)(nil)}),
7735 want: addr(struct{ X MarshalerTo }{X: &allMethods{method: "UnmarshalJSONFrom", value: []byte(`"value"`)}}),
7736 }, {
7737 name: jsontest.Name("Methods/AllMethods"),
7738 inBuf: `{"X":"hello"}`,
7739 inVal: new(struct{ X *allMethods }),
7740 want: addr(struct{ X *allMethods }{X: &allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}}),
7741 }, {
7742 name: jsontest.Name("Methods/AllMethodsExceptJSONv2"),
7743 inBuf: `{"X":"hello"}`,
7744 inVal: new(struct{ X *allMethodsExceptJSONv2 }),
7745 want: addr(struct{ X *allMethodsExceptJSONv2 }{X: &allMethodsExceptJSONv2{allMethods: allMethods{method: "UnmarshalJSON", value: []byte(`"hello"`)}}}),
7746 }, {
7747 name: jsontest.Name("Methods/AllMethodsExceptJSONv1"),
7748 inBuf: `{"X":"hello"}`,
7749 inVal: new(struct{ X *allMethodsExceptJSONv1 }),
7750 want: addr(struct{ X *allMethodsExceptJSONv1 }{X: &allMethodsExceptJSONv1{allMethods: allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}}}),
7751 }, {
7752 name: jsontest.Name("Methods/AllMethodsExceptText"),
7753 inBuf: `{"X":"hello"}`,
7754 inVal: new(struct{ X *allMethodsExceptText }),
7755 want: addr(struct{ X *allMethodsExceptText }{X: &allMethodsExceptText{allMethods: allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}}}),
7756 }, {
7757 name: jsontest.Name("Methods/OnlyMethodJSONv2"),
7758 inBuf: `{"X":"hello"}`,
7759 inVal: new(struct{ X *onlyMethodJSONv2 }),
7760 want: addr(struct{ X *onlyMethodJSONv2 }{X: &onlyMethodJSONv2{allMethods: allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}}}),
7761 }, {
7762 name: jsontest.Name("Methods/OnlyMethodJSONv1"),
7763 inBuf: `{"X":"hello"}`,
7764 inVal: new(struct{ X *onlyMethodJSONv1 }),
7765 want: addr(struct{ X *onlyMethodJSONv1 }{X: &onlyMethodJSONv1{allMethods: allMethods{method: "UnmarshalJSON", value: []byte(`"hello"`)}}}),
7766 }, {
7767 name: jsontest.Name("Methods/OnlyMethodText"),
7768 inBuf: `{"X":"hello"}`,
7769 inVal: new(struct{ X *onlyMethodText }),
7770 want: addr(struct{ X *onlyMethodText }{X: &onlyMethodText{allMethods: allMethods{method: "UnmarshalText", value: []byte(`hello`)}}}),
7771 }, {
7772 name: jsontest.Name("Methods/Text/Null"),
7773 inBuf: `{"X":null}`,
7774 inVal: addr(struct{ X unmarshalTextFunc }{unmarshalTextFunc(func(b []byte) error {
7775 return errMustNotCall
7776 })}),
7777 want: addr(struct{ X unmarshalTextFunc }{nil}),
7778 }, {
7779 name: jsontest.Name("Methods/IP"),
7780 inBuf: `"192.168.0.100"`,
7781 inVal: new(net.IP),
7782 want: addr(net.IPv4(192, 168, 0, 100)),
7783 }, {
7784 // NOTE: Fixes https://go.dev/issue/46516.
7785 name: jsontest.Name("Methods/Anonymous"),
7786 inBuf: `{"X":"hello"}`,
7787 inVal: new(struct{ X struct{ allMethods } }),
7788 want: addr(struct{ X struct{ allMethods } }{X: struct{ allMethods }{allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}}}),
7789 }, {
7790 // NOTE: Fixes https://go.dev/issue/22967.
7791 name: jsontest.Name("Methods/Addressable"),
7792 inBuf: `{"V":"hello","M":{"K":"hello"},"I":"hello"}`,
7793 inVal: addr(struct {
7794 V allMethods
7795 M map[string]allMethods
7796 I any
7797 }{
7798 I: allMethods{}, // need to initialize with concrete value
7799 }),
7800 want: addr(struct {
7801 V allMethods
7802 M map[string]allMethods
7803 I any
7804 }{
7805 V: allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)},
7806 M: map[string]allMethods{"K": {method: "UnmarshalJSONFrom", value: []byte(`"hello"`)}},
7807 I: allMethods{method: "UnmarshalJSONFrom", value: []byte(`"hello"`)},
7808 }),
7809 }, {
7810 // NOTE: Fixes https://go.dev/issue/29732.
7811 name: jsontest.Name("Methods/MapKey/JSONv2"),
7812 inBuf: `{"k1":"v1b","k2":"v2"}`,
7813 inVal: addr(map[structMethodJSONv2]string{{"k1"}: "v1a", {"k3"}: "v3"}),
7814 want: addr(map[structMethodJSONv2]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
7815 }, {
7816 // NOTE: Fixes https://go.dev/issue/29732.
7817 name: jsontest.Name("Methods/MapKey/JSONv1"),
7818 inBuf: `{"k1":"v1b","k2":"v2"}`,
7819 inVal: addr(map[structMethodJSONv1]string{{"k1"}: "v1a", {"k3"}: "v3"}),
7820 want: addr(map[structMethodJSONv1]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
7821 }, {
7822 name: jsontest.Name("Methods/MapKey/Text"),
7823 inBuf: `{"k1":"v1b","k2":"v2"}`,
7824 inVal: addr(map[structMethodText]string{{"k1"}: "v1a", {"k3"}: "v3"}),
7825 want: addr(map[structMethodText]string{{"k1"}: "v1b", {"k2"}: "v2", {"k3"}: "v3"}),
7826 }, {
7827 name: jsontest.Name("Methods/Invalid/JSONv2/Error"),
7828 inBuf: `{}`,
7829 inVal: addr(unmarshalJSONv2Func(func(*jsontext.Decoder) error {
7830 return errSomeError
7831 })),
7832 wantErr: EU(errSomeError).withType(0, T[unmarshalJSONv2Func]()),
7833 }, {
7834 name: jsontest.Name("Methods/Invalid/JSONv2/TooFew"),
7835 inVal: addr(unmarshalJSONv2Func(func(*jsontext.Decoder) error {
7836 return nil // do nothing
7837 })),
7838 wantErr: EU(errNonSingularValue).withType(0, T[unmarshalJSONv2Func]()),
7839 }, {
7840 name: jsontest.Name("Methods/Invalid/JSONv2/TooMany"),
7841 inBuf: `{}{}`,
7842 inVal: addr(unmarshalJSONv2Func(func(dec *jsontext.Decoder) error {
7843 dec.ReadValue()
7844 dec.ReadValue()
7845 return nil
7846 })),
7847 wantErr: EU(errNonSingularValue).withPos(`{}`, "").withType(0, T[unmarshalJSONv2Func]()),
7848 }, {
7849 name: jsontest.Name("Methods/Invalid/JSONv2/SkipFunc"),
7850 inBuf: `{}`,
7851 inVal: addr(unmarshalJSONv2Func(func(*jsontext.Decoder) error {
7852 return SkipFunc
7853 })),
7854 wantErr: EU(wrapSkipFunc(SkipFunc, "unmarshal method")).withType(0, T[unmarshalJSONv2Func]()),
7855 }, {
7856 name: jsontest.Name("Methods/Invalid/JSONv1/Error"),
7857 inBuf: `{}`,
7858 inVal: addr(unmarshalJSONv1Func(func([]byte) error {
7859 return errSomeError
7860 })),
7861 wantErr: EU(errSomeError).withType('{', T[unmarshalJSONv1Func]()),
7862 }, {
7863 name: jsontest.Name("Methods/Invalid/JSONv1/SkipFunc"),
7864 inBuf: `{}`,
7865 inVal: addr(unmarshalJSONv1Func(func([]byte) error {
7866 return SkipFunc
7867 })),
7868 wantErr: EU(wrapSkipFunc(SkipFunc, "unmarshal method")).withType('{', T[unmarshalJSONv1Func]()),
7869 }, {
7870 name: jsontest.Name("Methods/Invalid/Text/Error"),
7871 inBuf: `"value"`,
7872 inVal: addr(unmarshalTextFunc(func([]byte) error {
7873 return errSomeError
7874 })),
7875 wantErr: EU(errSomeError).withType('"', T[unmarshalTextFunc]()),
7876 }, {
7877 name: jsontest.Name("Methods/Invalid/Text/Syntax"),
7878 inBuf: `{}`,
7879 inVal: addr(unmarshalTextFunc(func([]byte) error {
7880 panic("should not be called")
7881 })),
7882 wantErr: EU(errNonStringValue).withType('{', T[unmarshalTextFunc]()),
7883 }, {
7884 name: jsontest.Name("Methods/Invalid/Text/SkipFunc"),
7885 inBuf: `"value"`,
7886 inVal: addr(unmarshalTextFunc(func([]byte) error {
7887 return SkipFunc
7888 })),
7889 wantErr: EU(wrapSkipFunc(SkipFunc, "unmarshal method")).withType('"', T[unmarshalTextFunc]()),
7890 }, {
7891 name: jsontest.Name("Functions/String/V1"),
7892 opts: []Options{
7893 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *string) error {
7894 if string(b) != `""` {
7895 return fmt.Errorf("got %s, want %s", b, `""`)
7896 }
7897 *v = "called"
7898 return nil
7899 })),
7900 },
7901 inBuf: `""`,
7902 inVal: addr(""),
7903 want: addr("called"),
7904 }, {
7905 name: jsontest.Name("Functions/String/Empty"),
7906 opts: []Options{WithUnmarshalers(nil)},
7907 inBuf: `"hello"`,
7908 inVal: addr(""),
7909 want: addr("hello"),
7910 }, {
7911 name: jsontest.Name("Functions/NamedString/V1/NoMatch"),
7912 opts: []Options{
7913 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *namedString) error {
7914 panic("should not be called")
7915 })),
7916 },
7917 inBuf: `""`,
7918 inVal: addr(""),
7919 want: addr(""),
7920 }, {
7921 name: jsontest.Name("Functions/NamedString/V1/Match"),
7922 opts: []Options{
7923 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *namedString) error {
7924 if string(b) != `""` {
7925 return fmt.Errorf("got %s, want %s", b, `""`)
7926 }
7927 *v = "called"
7928 return nil
7929 })),
7930 },
7931 inBuf: `""`,
7932 inVal: addr(namedString("")),
7933 want: addr(namedString("called")),
7934 }, {
7935 name: jsontest.Name("Functions/String/V2"),
7936 opts: []Options{
7937 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
7938 switch b, err := dec.ReadValue(); {
7939 case err != nil:
7940 return err
7941 case string(b) != `""`:
7942 return fmt.Errorf("got %s, want %s", b, `""`)
7943 }
7944 *v = "called"
7945 return nil
7946 })),
7947 },
7948 inBuf: `""`,
7949 inVal: addr(""),
7950 want: addr("called"),
7951 }, {
7952 name: jsontest.Name("Functions/NamedString/V2/NoMatch"),
7953 opts: []Options{
7954 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *namedString) error {
7955 panic("should not be called")
7956 })),
7957 },
7958 inBuf: `""`,
7959 inVal: addr(""),
7960 want: addr(""),
7961 }, {
7962 name: jsontest.Name("Functions/NamedString/V2/Match"),
7963 opts: []Options{
7964 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *namedString) error {
7965 switch t, err := dec.ReadToken(); {
7966 case err != nil:
7967 return err
7968 case t.String() != ``:
7969 return fmt.Errorf("got %q, want %q", t, ``)
7970 }
7971 *v = "called"
7972 return nil
7973 })),
7974 },
7975 inBuf: `""`,
7976 inVal: addr(namedString("")),
7977 want: addr(namedString("called")),
7978 }, {
7979 name: jsontest.Name("Functions/String/Empty1/NoMatch"),
7980 opts: []Options{
7981 WithUnmarshalers(new(Unmarshalers)),
7982 },
7983 inBuf: `""`,
7984 inVal: addr(""),
7985 want: addr(""),
7986 }, {
7987 name: jsontest.Name("Functions/String/Empty2/NoMatch"),
7988 opts: []Options{
7989 WithUnmarshalers(JoinUnmarshalers()),
7990 },
7991 inBuf: `""`,
7992 inVal: addr(""),
7993 want: addr(""),
7994 }, {
7995 name: jsontest.Name("Functions/String/V1/DirectError"),
7996 opts: []Options{
7997 WithUnmarshalers(UnmarshalFunc(func([]byte, *string) error {
7998 return errSomeError
7999 })),
8000 },
8001 inBuf: `""`,
8002 inVal: addr(""),
8003 want: addr(""),
8004 wantErr: EU(errSomeError).withType('"', reflect.PointerTo(stringType)),
8005 }, {
8006 name: jsontest.Name("Functions/String/V1/SkipError"),
8007 opts: []Options{
8008 WithUnmarshalers(UnmarshalFunc(func([]byte, *string) error {
8009 return SkipFunc
8010 })),
8011 },
8012 inBuf: `""`,
8013 inVal: addr(""),
8014 want: addr(""),
8015 wantErr: EU(wrapSkipFunc(SkipFunc, "unmarshal function of type func([]byte, T) error")).withType('"', reflect.PointerTo(stringType)),
8016 }, {
8017 name: jsontest.Name("Functions/String/V2/DirectError"),
8018 opts: []Options{
8019 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8020 return errSomeError
8021 })),
8022 },
8023 inBuf: `""`,
8024 inVal: addr(""),
8025 want: addr(""),
8026 wantErr: EU(errSomeError).withType(0, reflect.PointerTo(stringType)),
8027 }, {
8028 name: jsontest.Name("Functions/String/V2/TooFew"),
8029 opts: []Options{
8030 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8031 return nil
8032 })),
8033 },
8034 inBuf: `""`,
8035 inVal: addr(""),
8036 want: addr(""),
8037 wantErr: EU(errNonSingularValue).withType(0, reflect.PointerTo(stringType)),
8038 }, {
8039 name: jsontest.Name("Functions/String/V2/TooMany"),
8040 opts: []Options{
8041 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8042 if _, err := dec.ReadValue(); err != nil {
8043 return err
8044 }
8045 if _, err := dec.ReadValue(); err != nil {
8046 return err
8047 }
8048 return nil
8049 })),
8050 },
8051 inBuf: `{"X":["",""]}`,
8052 inVal: addr(struct{ X []string }{}),
8053 want: addr(struct{ X []string }{[]string{""}}),
8054 wantErr: EU(errNonSingularValue).withPos(`{"X":["",`, "/X").withType(0, reflect.PointerTo(stringType)),
8055 }, {
8056 name: jsontest.Name("Functions/String/V2/Skipped"),
8057 opts: []Options{
8058 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8059 return SkipFunc
8060 })),
8061 },
8062 inBuf: `""`,
8063 inVal: addr(""),
8064 want: addr(""),
8065 }, {
8066 name: jsontest.Name("Functions/String/V2/ProcessBeforeSkip"),
8067 opts: []Options{
8068 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8069 if _, err := dec.ReadValue(); err != nil {
8070 return err
8071 }
8072 return SkipFunc
8073 })),
8074 },
8075 inBuf: `""`,
8076 inVal: addr(""),
8077 want: addr(""),
8078 wantErr: EU(errSkipMutation).withType(0, reflect.PointerTo(stringType)),
8079 }, {
8080 name: jsontest.Name("Functions/String/V2/WrappedSkipError"),
8081 opts: []Options{
8082 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8083 return fmt.Errorf("wrap: %w", SkipFunc)
8084 })),
8085 },
8086 inBuf: `""`,
8087 inVal: addr(""),
8088 want: addr(""),
8089 wantErr: EU(fmt.Errorf("wrap: %w", SkipFunc)).withType(0, reflect.PointerTo(stringType)),
8090 }, {
8091 name: jsontest.Name("Functions/Map/Key/NoCaseString/V1"),
8092 opts: []Options{
8093 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *nocaseString) error {
8094 if string(b) != `"hello"` {
8095 return fmt.Errorf("got %s, want %s", b, `"hello"`)
8096 }
8097 *v = "called"
8098 return nil
8099 })),
8100 },
8101 inBuf: `{"hello":"world"}`,
8102 inVal: addr(map[nocaseString]string{}),
8103 want: addr(map[nocaseString]string{"called": "world"}),
8104 }, {
8105 name: jsontest.Name("Functions/Map/Key/TextMarshaler/V1"),
8106 opts: []Options{
8107 WithUnmarshalers(UnmarshalFunc(func(b []byte, v encoding.TextMarshaler) error {
8108 if string(b) != `"hello"` {
8109 return fmt.Errorf("got %s, want %s", b, `"hello"`)
8110 }
8111 *v.(*nocaseString) = "called"
8112 return nil
8113 })),
8114 },
8115 inBuf: `{"hello":"world"}`,
8116 inVal: addr(map[nocaseString]string{}),
8117 want: addr(map[nocaseString]string{"called": "world"}),
8118 }, {
8119 name: jsontest.Name("Functions/Map/Key/NoCaseString/V2"),
8120 opts: []Options{
8121 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *nocaseString) error {
8122 switch t, err := dec.ReadToken(); {
8123 case err != nil:
8124 return err
8125 case t.String() != "hello":
8126 return fmt.Errorf("got %q, want %q", t, "hello")
8127 }
8128 *v = "called"
8129 return nil
8130 })),
8131 },
8132 inBuf: `{"hello":"world"}`,
8133 inVal: addr(map[nocaseString]string{}),
8134 want: addr(map[nocaseString]string{"called": "world"}),
8135 }, {
8136 name: jsontest.Name("Functions/Map/Key/TextMarshaler/V2"),
8137 opts: []Options{
8138 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v encoding.TextMarshaler) error {
8139 switch b, err := dec.ReadValue(); {
8140 case err != nil:
8141 return err
8142 case string(b) != `"hello"`:
8143 return fmt.Errorf("got %s, want %s", b, `"hello"`)
8144 }
8145 *v.(*nocaseString) = "called"
8146 return nil
8147 })),
8148 },
8149 inBuf: `{"hello":"world"}`,
8150 inVal: addr(map[nocaseString]string{}),
8151 want: addr(map[nocaseString]string{"called": "world"}),
8152 }, {
8153 name: jsontest.Name("Functions/Map/Key/String/V1/DuplicateName"),
8154 opts: []Options{
8155 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8156 if _, err := dec.ReadValue(); err != nil {
8157 return err
8158 }
8159 xd := export.Decoder(dec)
8160 *v = fmt.Sprintf("%d-%d", len(xd.Tokens.Stack), xd.Tokens.Last.Length())
8161 return nil
8162 })),
8163 },
8164 inBuf: `{"name":"value","name":"value"}`,
8165 inVal: addr(map[string]string{}),
8166 want: addr(map[string]string{"1-1": "1-2"}),
8167 wantErr: newDuplicateNameError("", []byte(`"name"`), len64(`{"name":"value",`)),
8168 }, {
8169 name: jsontest.Name("Functions/Map/Value/NoCaseString/V1"),
8170 opts: []Options{
8171 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *nocaseString) error {
8172 if string(b) != `"world"` {
8173 return fmt.Errorf("got %s, want %s", b, `"world"`)
8174 }
8175 *v = "called"
8176 return nil
8177 })),
8178 },
8179 inBuf: `{"hello":"world"}`,
8180 inVal: addr(map[string]nocaseString{}),
8181 want: addr(map[string]nocaseString{"hello": "called"}),
8182 }, {
8183 name: jsontest.Name("Functions/Map/Value/TextMarshaler/V1"),
8184 opts: []Options{
8185 WithUnmarshalers(UnmarshalFunc(func(b []byte, v encoding.TextMarshaler) error {
8186 if string(b) != `"world"` {
8187 return fmt.Errorf("got %s, want %s", b, `"world"`)
8188 }
8189 *v.(*nocaseString) = "called"
8190 return nil
8191 })),
8192 },
8193 inBuf: `{"hello":"world"}`,
8194 inVal: addr(map[string]nocaseString{}),
8195 want: addr(map[string]nocaseString{"hello": "called"}),
8196 }, {
8197 name: jsontest.Name("Functions/Map/Value/NoCaseString/V2"),
8198 opts: []Options{
8199 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *nocaseString) error {
8200 switch t, err := dec.ReadToken(); {
8201 case err != nil:
8202 return err
8203 case t.String() != "world":
8204 return fmt.Errorf("got %q, want %q", t, "world")
8205 }
8206 *v = "called"
8207 return nil
8208 })),
8209 },
8210 inBuf: `{"hello":"world"}`,
8211 inVal: addr(map[string]nocaseString{}),
8212 want: addr(map[string]nocaseString{"hello": "called"}),
8213 }, {
8214 name: jsontest.Name("Functions/Map/Value/TextMarshaler/V2"),
8215 opts: []Options{
8216 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v encoding.TextMarshaler) error {
8217 switch b, err := dec.ReadValue(); {
8218 case err != nil:
8219 return err
8220 case string(b) != `"world"`:
8221 return fmt.Errorf("got %s, want %s", b, `"world"`)
8222 }
8223 *v.(*nocaseString) = "called"
8224 return nil
8225 })),
8226 },
8227 inBuf: `{"hello":"world"}`,
8228 inVal: addr(map[string]nocaseString{}),
8229 want: addr(map[string]nocaseString{"hello": "called"}),
8230 }, {
8231 name: jsontest.Name("Funtions/Struct/Fields"),
8232 opts: []Options{
8233 WithUnmarshalers(JoinUnmarshalers(
8234 UnmarshalFunc(func(b []byte, v *bool) error {
8235 if string(b) != `"called1"` {
8236 return fmt.Errorf("got %s, want %s", b, `"called1"`)
8237 }
8238 *v = true
8239 return nil
8240 }),
8241 UnmarshalFunc(func(b []byte, v *string) error {
8242 if string(b) != `"called2"` {
8243 return fmt.Errorf("got %s, want %s", b, `"called2"`)
8244 }
8245 *v = "called2"
8246 return nil
8247 }),
8248 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *[]byte) error {
8249 switch t, err := dec.ReadToken(); {
8250 case err != nil:
8251 return err
8252 case t.String() != "called3":
8253 return fmt.Errorf("got %q, want %q", t, "called3")
8254 }
8255 *v = []byte("called3")
8256 return nil
8257 }),
8258 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *int64) error {
8259 switch b, err := dec.ReadValue(); {
8260 case err != nil:
8261 return err
8262 case string(b) != `"called4"`:
8263 return fmt.Errorf("got %s, want %s", b, `"called4"`)
8264 }
8265 *v = 123
8266 return nil
8267 }),
8268 )),
8269 },
8270 inBuf: `{"Bool":"called1","String":"called2","Bytes":"called3","Int":"called4","Uint":456,"Float":789}`,
8271 inVal: addr(structScalars{}),
8272 want: addr(structScalars{Bool: true, String: "called2", Bytes: []byte("called3"), Int: 123, Uint: 456, Float: 789}),
8273 }, {
8274 name: jsontest.Name("Functions/Struct/Inlined"),
8275 opts: []Options{
8276 WithUnmarshalers(JoinUnmarshalers(
8277 UnmarshalFunc(func([]byte, *structInlinedL1) error {
8278 panic("should not be called")
8279 }),
8280 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *StructEmbed2) error {
8281 panic("should not be called")
8282 }),
8283 )),
8284 },
8285 inBuf: `{"E":"E3","F":"F3","G":"G3","A":"A1","B":"B1","D":"D2"}`,
8286 inVal: new(structInlined),
8287 want: addr(structInlined{
8288 X: structInlinedL1{
8289 X: &structInlinedL2{A: "A1", B: "B1" /* C: "C1" */},
8290 StructEmbed1: StructEmbed1{ /* C: "C2" */ D: "D2" /* E: "E2" */},
8291 },
8292 StructEmbed2: &StructEmbed2{E: "E3", F: "F3", G: "G3"},
8293 }),
8294 }, {
8295 name: jsontest.Name("Functions/Slice/Elem"),
8296 opts: []Options{
8297 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *string) error {
8298 *v = strings.Trim(strings.ToUpper(string(b)), `"`)
8299 return nil
8300 })),
8301 },
8302 inBuf: `["hello","World"]`,
8303 inVal: addr([]string{}),
8304 want: addr([]string{"HELLO", "WORLD"}),
8305 }, {
8306 name: jsontest.Name("Functions/Array/Elem"),
8307 opts: []Options{
8308 WithUnmarshalers(UnmarshalFunc(func(b []byte, v *string) error {
8309 *v = strings.Trim(strings.ToUpper(string(b)), `"`)
8310 return nil
8311 })),
8312 },
8313 inBuf: `["hello","World"]`,
8314 inVal: addr([2]string{}),
8315 want: addr([2]string{"HELLO", "WORLD"}),
8316 }, {
8317 name: jsontest.Name("Functions/Pointer/Nil"),
8318 opts: []Options{
8319 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8320 t, err := dec.ReadToken()
8321 *v = strings.ToUpper(t.String())
8322 return err
8323 })),
8324 },
8325 inBuf: `{"X":"hello"}`,
8326 inVal: addr(struct{ X *string }{nil}),
8327 want: addr(struct{ X *string }{addr("HELLO")}),
8328 }, {
8329 name: jsontest.Name("Functions/Pointer/NonNil"),
8330 opts: []Options{
8331 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8332 t, err := dec.ReadToken()
8333 *v = strings.ToUpper(t.String())
8334 return err
8335 })),
8336 },
8337 inBuf: `{"X":"hello"}`,
8338 inVal: addr(struct{ X *string }{addr("")}),
8339 want: addr(struct{ X *string }{addr("HELLO")}),
8340 }, {
8341 name: jsontest.Name("Functions/Interface/Nil"),
8342 opts: []Options{
8343 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v fmt.Stringer) error {
8344 panic("should not be called")
8345 })),
8346 },
8347 inBuf: `{"X":"hello"}`,
8348 inVal: addr(struct{ X fmt.Stringer }{nil}),
8349 want: addr(struct{ X fmt.Stringer }{nil}),
8350 wantErr: EU(internal.ErrNilInterface).withPos(`{"X":`, "/X").withType(0, T[fmt.Stringer]()),
8351 }, {
8352 name: jsontest.Name("Functions/Interface/NetIP"),
8353 opts: []Options{
8354 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *fmt.Stringer) error {
8355 *v = net.IP{}
8356 return SkipFunc
8357 })),
8358 },
8359 inBuf: `{"X":"1.1.1.1"}`,
8360 inVal: addr(struct{ X fmt.Stringer }{nil}),
8361 want: addr(struct{ X fmt.Stringer }{net.IPv4(1, 1, 1, 1)}),
8362 }, {
8363 name: jsontest.Name("Functions/Interface/NewPointerNetIP"),
8364 opts: []Options{
8365 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *fmt.Stringer) error {
8366 *v = new(net.IP)
8367 return SkipFunc
8368 })),
8369 },
8370 inBuf: `{"X":"1.1.1.1"}`,
8371 inVal: addr(struct{ X fmt.Stringer }{nil}),
8372 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(1, 1, 1, 1))}),
8373 }, {
8374 name: jsontest.Name("Functions/Interface/NilPointerNetIP"),
8375 opts: []Options{
8376 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, v *fmt.Stringer) error {
8377 *v = (*net.IP)(nil)
8378 return SkipFunc
8379 })),
8380 },
8381 inBuf: `{"X":"1.1.1.1"}`,
8382 inVal: addr(struct{ X fmt.Stringer }{nil}),
8383 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(1, 1, 1, 1))}),
8384 }, {
8385 name: jsontest.Name("Functions/Interface/NilPointerNetIP/Override"),
8386 opts: []Options{
8387 WithUnmarshalers(JoinUnmarshalers(
8388 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *fmt.Stringer) error {
8389 *v = (*net.IP)(nil)
8390 return SkipFunc
8391 }),
8392 UnmarshalFunc(func(b []byte, v *net.IP) error {
8393 b = bytes.ReplaceAll(b, []byte(`1`), []byte(`8`))
8394 return v.UnmarshalText(bytes.Trim(b, `"`))
8395 }),
8396 )),
8397 },
8398 inBuf: `{"X":"1.1.1.1"}`,
8399 inVal: addr(struct{ X fmt.Stringer }{nil}),
8400 want: addr(struct{ X fmt.Stringer }{addr(net.IPv4(8, 8, 8, 8))}),
8401 }, {
8402 name: jsontest.Name("Functions/Interface/Any"),
8403 inBuf: `[null,{},{},{},{},{},{},{},{},{},{},{},{},"LAST"]`,
8404 inVal: addr([...]any{
8405 nil, // nil
8406 valueStringer{}, // T
8407 (*valueStringer)(nil), // *T
8408 addr(valueStringer{}), // *T
8409 (**valueStringer)(nil), // **T
8410 addr((*valueStringer)(nil)), // **T
8411 addr(addr(valueStringer{})), // **T
8412 pointerStringer{}, // T
8413 (*pointerStringer)(nil), // *T
8414 addr(pointerStringer{}), // *T
8415 (**pointerStringer)(nil), // **T
8416 addr((*pointerStringer)(nil)), // **T
8417 addr(addr(pointerStringer{})), // **T
8418 "LAST",
8419 }),
8420 opts: []Options{
8421 WithUnmarshalers(func() *Unmarshalers {
8422 type P struct {
8423 D int
8424 N int64
8425 }
8426 type PV struct {
8427 P P
8428 V any
8429 }
8430
8431 var lastChecks []func() error
8432 checkLast := func() error {
8433 for _, fn := range lastChecks {
8434 if err := fn(); err != nil {
8435 return err
8436 }
8437 }
8438 return SkipFunc
8439 }
8440 makeValueChecker := func(name string, want []PV) func(d *jsontext.Decoder, v any) error {
8441 checkNext := func(d *jsontext.Decoder, v any) error {
8442 xd := export.Decoder(d)
8443 p := P{len(xd.Tokens.Stack), xd.Tokens.Last.Length()}
8444 rv := reflect.ValueOf(v)
8445 pv := PV{p, v}
8446 switch {
8447 case len(want) == 0:
8448 return fmt.Errorf("%s: %v: got more values than expected", name, p)
8449 case !rv.IsValid() || rv.Kind() != reflect.Pointer || rv.IsNil():
8450 return fmt.Errorf("%s: %v: got %#v, want non-nil pointer type", name, p, v)
8451 case !reflect.DeepEqual(pv, want[0]):
8452 return fmt.Errorf("%s:\n\tgot %#v\n\twant %#v", name, pv, want[0])
8453 default:
8454 want = want[1:]
8455 return SkipFunc
8456 }
8457 }
8458 lastChecks = append(lastChecks, func() error {
8459 if len(want) > 0 {
8460 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
8461 }
8462 return nil
8463 })
8464 return checkNext
8465 }
8466 makePositionChecker := func(name string, want []P) func(d *jsontext.Decoder, v any) error {
8467 checkNext := func(d *jsontext.Decoder, v any) error {
8468 xd := export.Decoder(d)
8469 p := P{len(xd.Tokens.Stack), xd.Tokens.Last.Length()}
8470 switch {
8471 case len(want) == 0:
8472 return fmt.Errorf("%s: %v: got more values than wanted", name, p)
8473 case p != want[0]:
8474 return fmt.Errorf("%s: got %v, want %v", name, p, want[0])
8475 default:
8476 want = want[1:]
8477 return SkipFunc
8478 }
8479 }
8480 lastChecks = append(lastChecks, func() error {
8481 if len(want) > 0 {
8482 return fmt.Errorf("%s: did not get enough values, want %d more", name, len(want))
8483 }
8484 return nil
8485 })
8486 return checkNext
8487 }
8488
8489 // In contrast to marshal, unmarshal automatically allocates for
8490 // nil pointers, which causes unmarshal to visit more values.
8491 wantAny := []PV{
8492 {P{1, 0}, addr(any(nil))},
8493 {P{1, 1}, addr(any(valueStringer{}))},
8494 {P{1, 1}, addr(valueStringer{})},
8495 {P{1, 2}, addr(any((*valueStringer)(nil)))},
8496 {P{1, 2}, addr((*valueStringer)(nil))},
8497 {P{1, 2}, addr(valueStringer{})},
8498 {P{1, 3}, addr(any(addr(valueStringer{})))},
8499 {P{1, 3}, addr(addr(valueStringer{}))},
8500 {P{1, 3}, addr(valueStringer{})},
8501 {P{1, 4}, addr(any((**valueStringer)(nil)))},
8502 {P{1, 4}, addr((**valueStringer)(nil))},
8503 {P{1, 4}, addr((*valueStringer)(nil))},
8504 {P{1, 4}, addr(valueStringer{})},
8505 {P{1, 5}, addr(any(addr((*valueStringer)(nil))))},
8506 {P{1, 5}, addr(addr((*valueStringer)(nil)))},
8507 {P{1, 5}, addr((*valueStringer)(nil))},
8508 {P{1, 5}, addr(valueStringer{})},
8509 {P{1, 6}, addr(any(addr(addr(valueStringer{}))))},
8510 {P{1, 6}, addr(addr(addr(valueStringer{})))},
8511 {P{1, 6}, addr(addr(valueStringer{}))},
8512 {P{1, 6}, addr(valueStringer{})},
8513 {P{1, 7}, addr(any(pointerStringer{}))},
8514 {P{1, 7}, addr(pointerStringer{})},
8515 {P{1, 8}, addr(any((*pointerStringer)(nil)))},
8516 {P{1, 8}, addr((*pointerStringer)(nil))},
8517 {P{1, 8}, addr(pointerStringer{})},
8518 {P{1, 9}, addr(any(addr(pointerStringer{})))},
8519 {P{1, 9}, addr(addr(pointerStringer{}))},
8520 {P{1, 9}, addr(pointerStringer{})},
8521 {P{1, 10}, addr(any((**pointerStringer)(nil)))},
8522 {P{1, 10}, addr((**pointerStringer)(nil))},
8523 {P{1, 10}, addr((*pointerStringer)(nil))},
8524 {P{1, 10}, addr(pointerStringer{})},
8525 {P{1, 11}, addr(any(addr((*pointerStringer)(nil))))},
8526 {P{1, 11}, addr(addr((*pointerStringer)(nil)))},
8527 {P{1, 11}, addr((*pointerStringer)(nil))},
8528 {P{1, 11}, addr(pointerStringer{})},
8529 {P{1, 12}, addr(any(addr(addr(pointerStringer{}))))},
8530 {P{1, 12}, addr(addr(addr(pointerStringer{})))},
8531 {P{1, 12}, addr(addr(pointerStringer{}))},
8532 {P{1, 12}, addr(pointerStringer{})},
8533 {P{1, 13}, addr(any("LAST"))},
8534 {P{1, 13}, addr("LAST")},
8535 }
8536 checkAny := makeValueChecker("any", wantAny)
8537 anyUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v any) error {
8538 return checkAny(dec, v)
8539 })
8540
8541 var wantPointerAny []PV
8542 for _, v := range wantAny {
8543 if _, ok := v.V.(*any); ok {
8544 wantPointerAny = append(wantPointerAny, v)
8545 }
8546 }
8547 checkPointerAny := makeValueChecker("*any", wantPointerAny)
8548 pointerAnyUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *any) error {
8549 return checkPointerAny(dec, v)
8550 })
8551
8552 checkNamedAny := makeValueChecker("namedAny", wantAny)
8553 namedAnyUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v namedAny) error {
8554 return checkNamedAny(dec, v)
8555 })
8556
8557 checkPointerNamedAny := makeValueChecker("*namedAny", nil)
8558 pointerNamedAnyUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *namedAny) error {
8559 return checkPointerNamedAny(dec, v)
8560 })
8561
8562 type stringer = fmt.Stringer
8563 var wantStringer []PV
8564 for _, v := range wantAny {
8565 if _, ok := v.V.(stringer); ok {
8566 wantStringer = append(wantStringer, v)
8567 }
8568 }
8569 checkStringer := makeValueChecker("stringer", wantStringer)
8570 stringerUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v stringer) error {
8571 return checkStringer(dec, v)
8572 })
8573
8574 checkPointerStringer := makeValueChecker("*stringer", nil)
8575 pointerStringerUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *stringer) error {
8576 return checkPointerStringer(dec, v)
8577 })
8578
8579 wantValueStringer := []P{{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}}
8580 checkPointerValueStringer := makePositionChecker("*valueStringer", wantValueStringer)
8581 pointerValueStringerUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *valueStringer) error {
8582 return checkPointerValueStringer(dec, v)
8583 })
8584
8585 wantPointerStringer := []P{{1, 7}, {1, 8}, {1, 9}, {1, 10}, {1, 11}, {1, 12}}
8586 checkPointerPointerStringer := makePositionChecker("*pointerStringer", wantPointerStringer)
8587 pointerPointerStringerUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *pointerStringer) error {
8588 return checkPointerPointerStringer(dec, v)
8589 })
8590
8591 lastUnmarshaler := UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8592 return checkLast()
8593 })
8594
8595 return JoinUnmarshalers(
8596 // This is just like unmarshaling into a Go array,
8597 // but avoids zeroing the element before calling unmarshal.
8598 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *[14]any) error {
8599 if _, err := dec.ReadToken(); err != nil {
8600 return err
8601 }
8602 for i := range len(*v) {
8603 if err := UnmarshalDecode(dec, &(*v)[i]); err != nil {
8604 return err
8605 }
8606 }
8607 if _, err := dec.ReadToken(); err != nil {
8608 return err
8609 }
8610 return nil
8611 }),
8612
8613 anyUnmarshaler,
8614 pointerAnyUnmarshaler,
8615 namedAnyUnmarshaler,
8616 pointerNamedAnyUnmarshaler, // never called
8617 stringerUnmarshaler,
8618 pointerStringerUnmarshaler, // never called
8619 pointerValueStringerUnmarshaler,
8620 pointerPointerStringerUnmarshaler,
8621 lastUnmarshaler,
8622 )
8623 }()),
8624 },
8625 }, {
8626 name: jsontest.Name("Functions/Precedence/V1First"),
8627 opts: []Options{
8628 WithUnmarshalers(JoinUnmarshalers(
8629 UnmarshalFunc(func(b []byte, v *string) error {
8630 if string(b) != `"called"` {
8631 return fmt.Errorf("got %s, want %s", b, `"called"`)
8632 }
8633 *v = "called"
8634 return nil
8635 }),
8636 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8637 panic("should not be called")
8638 }),
8639 )),
8640 },
8641 inBuf: `"called"`,
8642 inVal: addr(""),
8643 want: addr("called"),
8644 }, {
8645 name: jsontest.Name("Functions/Precedence/V2First"),
8646 opts: []Options{
8647 WithUnmarshalers(JoinUnmarshalers(
8648 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8649 switch t, err := dec.ReadToken(); {
8650 case err != nil:
8651 return err
8652 case t.String() != "called":
8653 return fmt.Errorf("got %q, want %q", t, "called")
8654 }
8655 *v = "called"
8656 return nil
8657 }),
8658 UnmarshalFunc(func([]byte, *string) error {
8659 panic("should not be called")
8660 }),
8661 )),
8662 },
8663 inBuf: `"called"`,
8664 inVal: addr(""),
8665 want: addr("called"),
8666 }, {
8667 name: jsontest.Name("Functions/Precedence/V2Skipped"),
8668 opts: []Options{
8669 WithUnmarshalers(JoinUnmarshalers(
8670 UnmarshalFromFunc(func(dec *jsontext.Decoder, v *string) error {
8671 return SkipFunc
8672 }),
8673 UnmarshalFunc(func(b []byte, v *string) error {
8674 if string(b) != `"called"` {
8675 return fmt.Errorf("got %s, want %s", b, `"called"`)
8676 }
8677 *v = "called"
8678 return nil
8679 }),
8680 )),
8681 },
8682 inBuf: `"called"`,
8683 inVal: addr(""),
8684 want: addr("called"),
8685 }, {
8686 name: jsontest.Name("Functions/Precedence/NestedFirst"),
8687 opts: []Options{
8688 WithUnmarshalers(JoinUnmarshalers(
8689 JoinUnmarshalers(
8690 UnmarshalFunc(func(b []byte, v *string) error {
8691 if string(b) != `"called"` {
8692 return fmt.Errorf("got %s, want %s", b, `"called"`)
8693 }
8694 *v = "called"
8695 return nil
8696 }),
8697 ),
8698 UnmarshalFunc(func([]byte, *string) error {
8699 panic("should not be called")
8700 }),
8701 )),
8702 },
8703 inBuf: `"called"`,
8704 inVal: addr(""),
8705 want: addr("called"),
8706 }, {
8707 name: jsontest.Name("Functions/Precedence/NestedLast"),
8708 opts: []Options{
8709 WithUnmarshalers(JoinUnmarshalers(
8710 UnmarshalFunc(func(b []byte, v *string) error {
8711 if string(b) != `"called"` {
8712 return fmt.Errorf("got %s, want %s", b, `"called"`)
8713 }
8714 *v = "called"
8715 return nil
8716 }),
8717 JoinUnmarshalers(
8718 UnmarshalFunc(func([]byte, *string) error {
8719 panic("should not be called")
8720 }),
8721 ),
8722 )),
8723 },
8724 inBuf: `"called"`,
8725 inVal: addr(""),
8726 want: addr("called"),
8727 }, {
8728 name: jsontest.Name("Duration/Null"),
8729 inBuf: `{"D1":null,"D2":null}`,
8730 inVal: addr(struct {
8731 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8732 D2 time.Duration `json:",format:nano"`
8733 }{1, 1}),
8734 want: addr(struct {
8735 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8736 D2 time.Duration `json:",format:nano"`
8737 }{0, 0}),
8738 }, {
8739 name: jsontest.Name("Duration/Zero"),
8740 inBuf: `{"D1":"0s","D2":0}`,
8741 inVal: addr(struct {
8742 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8743 D2 time.Duration `json:",format:nano"`
8744 }{1, 1}),
8745 want: addr(struct {
8746 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8747 D2 time.Duration `json:",format:nano"`
8748 }{0, 0}),
8749 }, {
8750 name: jsontest.Name("Duration/Positive"),
8751 inBuf: `{"D1":"34293h33m9.123456789s","D2":123456789123456789}`,
8752 inVal: new(struct {
8753 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8754 D2 time.Duration `json:",format:nano"`
8755 }),
8756 want: addr(struct {
8757 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8758 D2 time.Duration `json:",format:nano"`
8759 }{
8760 123456789123456789,
8761 123456789123456789,
8762 }),
8763 }, {
8764 name: jsontest.Name("Duration/Negative"),
8765 inBuf: `{"D1":"-34293h33m9.123456789s","D2":-123456789123456789}`,
8766 inVal: new(struct {
8767 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8768 D2 time.Duration `json:",format:nano"`
8769 }),
8770 want: addr(struct {
8771 D1 time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8772 D2 time.Duration `json:",format:nano"`
8773 }{
8774 -123456789123456789,
8775 -123456789123456789,
8776 }),
8777 }, {
8778 name: jsontest.Name("Duration/Nanos/String"),
8779 inBuf: `{"D":"12345"}`,
8780 inVal: addr(struct {
8781 D time.Duration `json:",string,format:nano"`
8782 }{1}),
8783 want: addr(struct {
8784 D time.Duration `json:",string,format:nano"`
8785 }{12345}),
8786 }, {
8787 name: jsontest.Name("Duration/Nanos/String/Invalid"),
8788 inBuf: `{"D":"+12345"}`,
8789 inVal: addr(struct {
8790 D time.Duration `json:",string,format:nano"`
8791 }{1}),
8792 want: addr(struct {
8793 D time.Duration `json:",string,format:nano"`
8794 }{1}),
8795 wantErr: EU(fmt.Errorf(`invalid duration "+12345": %w`, strconv.ErrSyntax)).withPos(`{"D":`, "/D").withType('"', timeDurationType),
8796 }, {
8797 name: jsontest.Name("Duration/Nanos/Mismatch"),
8798 inBuf: `{"D":"34293h33m9.123456789s"}`,
8799 inVal: addr(struct {
8800 D time.Duration `json:",format:nano"`
8801 }{1}),
8802 want: addr(struct {
8803 D time.Duration `json:",format:nano"`
8804 }{1}),
8805 wantErr: EU(nil).withPos(`{"D":`, "/D").withType('"', timeDurationType),
8806 }, {
8807 name: jsontest.Name("Duration/Nanos"),
8808 inBuf: `{"D":1.324}`,
8809 inVal: addr(struct {
8810 D time.Duration `json:",format:nano"`
8811 }{-1}),
8812 want: addr(struct {
8813 D time.Duration `json:",format:nano"`
8814 }{1}),
8815 }, {
8816 name: jsontest.Name("Duration/String/Mismatch"),
8817 inBuf: `{"D":-123456789123456789}`,
8818 inVal: addr(struct {
8819 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8820 }{1}),
8821 want: addr(struct {
8822 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8823 }{1}),
8824 wantErr: EU(nil).withPos(`{"D":`, "/D").withType('0', timeDurationType),
8825 }, {
8826 name: jsontest.Name("Duration/String/Invalid"),
8827 inBuf: `{"D":"5minkutes"}`,
8828 inVal: addr(struct {
8829 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8830 }{1}),
8831 want: addr(struct {
8832 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8833 }{1}),
8834 wantErr: EU(func() error {
8835 _, err := time.ParseDuration("5minkutes")
8836 return err
8837 }()).withPos(`{"D":`, "/D").withType('"', timeDurationType),
8838 }, {
8839 name: jsontest.Name("Duration/Syntax/Invalid"),
8840 inBuf: `{"D":x}`,
8841 inVal: addr(struct {
8842 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8843 }{1}),
8844 want: addr(struct {
8845 D time.Duration `json:",format:units"` // TODO(https://go.dev/issue/71631): Remove the format flag.
8846 }{1}),
8847 wantErr: newInvalidCharacterError("x", "at start of value", len64(`{"D":`), "/D"),
8848 }, {
8849 name: jsontest.Name("Duration/Format"),
8850 inBuf: `{
8851 "D1": "12h34m56.078090012s",
8852 "D2": "12h34m56.078090012s",
8853 "D3": 45296.078090012,
8854 "D4": "45296.078090012",
8855 "D5": 45296078.090012,
8856 "D6": "45296078.090012",
8857 "D7": 45296078090.012,
8858 "D8": "45296078090.012",
8859 "D9": 45296078090012,
8860 "D10": "45296078090012",
8861 "D11": "PT12H34M56.078090012S"
8862 }`,
8863 inVal: new(structDurationFormat),
8864 want: addr(structDurationFormat{
8865 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8866 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8867 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8868 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8869 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8870 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8871 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8872 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8873 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8874 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8875 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8876 }),
8877 }, {
8878 name: jsontest.Name("Duration/Format/Invalid"),
8879 inBuf: `{"D":"0s"}`,
8880 inVal: addr(struct {
8881 D time.Duration `json:",format:invalid"`
8882 }{1}),
8883 want: addr(struct {
8884 D time.Duration `json:",format:invalid"`
8885 }{1}),
8886 wantErr: EU(errInvalidFormatFlag).withPos(`{"D":`, "/D").withType(0, timeDurationType),
8887 }, {
8888 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
8889 name: jsontest.Name("Duration/Format/Legacy"),
8890 inBuf: `{"D1":45296078090012,"D2":"12h34m56.078090012s"}`,
8891 opts: []Options{jsonflags.FormatDurationAsNano | 1},
8892 inVal: new(structDurationFormat),
8893 want: addr(structDurationFormat{
8894 D1: 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8895 D2: 12*time.Hour + 34*time.Minute + 56*time.Second + 78*time.Millisecond + 90*time.Microsecond + 12*time.Nanosecond,
8896 }),
8897 }, { */
8898 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
8899 name: jsontest.Name("Duration/MapKey"),
8900 inBuf: `{"1s":""}`,
8901 inVal: new(map[time.Duration]string),
8902 want: addr(map[time.Duration]string{time.Second: ""}),
8903 }, { */
8904 name: jsontest.Name("Duration/MapKey/Legacy"),
8905 opts: []Options{jsonflags.FormatDurationAsNano | 1},
8906 inBuf: `{"1000000000":""}`,
8907 inVal: new(map[time.Duration]string),
8908 want: addr(map[time.Duration]string{time.Second: ""}),
8909 }, {
8910 /* TODO(https://go.dev/issue/71631): Re-enable this test case.
8911 name: jsontest.Name("Duration/IgnoreInvalidFormat"),
8912 opts: []Options{invalidFormatOption},
8913 inBuf: `"1s"`,
8914 inVal: addr(time.Duration(0)),
8915 want: addr(time.Second),
8916 }, { */
8917 name: jsontest.Name("Time/Zero"),
8918 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"}`,
8919 inVal: new(struct {
8920 T1 time.Time
8921 T2 time.Time `json:",format:RFC822"`
8922 T3 time.Time `json:",format:'2006-01-02'"`
8923 T4 time.Time `json:",omitzero"`
8924 T5 time.Time `json:",omitempty"`
8925 }),
8926 want: addr(struct {
8927 T1 time.Time
8928 T2 time.Time `json:",format:RFC822"`
8929 T3 time.Time `json:",format:'2006-01-02'"`
8930 T4 time.Time `json:",omitzero"`
8931 T5 time.Time `json:",omitempty"`
8932 }{
8933 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
8934 mustParseTime(time.RFC822, "01 Jan 01 00:00 UTC"),
8935 mustParseTime("2006-01-02", "0001-01-01"),
8936 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
8937 mustParseTime(time.RFC3339Nano, "0001-01-01T00:00:00Z"),
8938 }),
8939 }, {
8940 name: jsontest.Name("Time/Format"),
8941 inBuf: `{
8942 "T1": "1234-01-02T03:04:05.000000006Z",
8943 "T2": "Mon Jan 2 03:04:05 1234",
8944 "T3": "Mon Jan 2 03:04:05 UTC 1234",
8945 "T4": "Mon Jan 02 03:04:05 +0000 1234",
8946 "T5": "02 Jan 34 03:04 UTC",
8947 "T6": "02 Jan 34 03:04 +0000",
8948 "T7": "Monday, 02-Jan-34 03:04:05 UTC",
8949 "T8": "Mon, 02 Jan 1234 03:04:05 UTC",
8950 "T9": "Mon, 02 Jan 1234 03:04:05 +0000",
8951 "T10": "1234-01-02T03:04:05Z",
8952 "T11": "1234-01-02T03:04:05.000000006Z",
8953 "T12": "3:04AM",
8954 "T13": "Jan 2 03:04:05",
8955 "T14": "Jan 2 03:04:05.000",
8956 "T15": "Jan 2 03:04:05.000000",
8957 "T16": "Jan 2 03:04:05.000000006",
8958 "T17": "1234-01-02 03:04:05",
8959 "T18": "1234-01-02",
8960 "T19": "03:04:05",
8961 "T20": "1234-01-02",
8962 "T21": "\"weird\"1234",
8963 "T22": -23225777754.999999994,
8964 "T23": "-23225777754.999999994",
8965 "T24": -23225777754999.999994,
8966 "T25": "-23225777754999.999994",
8967 "T26": -23225777754999999.994,
8968 "T27": "-23225777754999999.994",
8969 "T28": -23225777754999999994,
8970 "T29": "-23225777754999999994"
8971 }`,
8972 inVal: new(structTimeFormat),
8973 want: addr(structTimeFormat{
8974 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
8975 mustParseTime(time.ANSIC, "Mon Jan 2 03:04:05 1234"),
8976 mustParseTime(time.UnixDate, "Mon Jan 2 03:04:05 UTC 1234"),
8977 mustParseTime(time.RubyDate, "Mon Jan 02 03:04:05 +0000 1234"),
8978 mustParseTime(time.RFC822, "02 Jan 34 03:04 UTC"),
8979 mustParseTime(time.RFC822Z, "02 Jan 34 03:04 +0000"),
8980 mustParseTime(time.RFC850, "Monday, 02-Jan-34 03:04:05 UTC"),
8981 mustParseTime(time.RFC1123, "Mon, 02 Jan 1234 03:04:05 UTC"),
8982 mustParseTime(time.RFC1123Z, "Mon, 02 Jan 1234 03:04:05 +0000"),
8983 mustParseTime(time.RFC3339, "1234-01-02T03:04:05Z"),
8984 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
8985 mustParseTime(time.Kitchen, "3:04AM"),
8986 mustParseTime(time.Stamp, "Jan 2 03:04:05"),
8987 mustParseTime(time.StampMilli, "Jan 2 03:04:05.000"),
8988 mustParseTime(time.StampMicro, "Jan 2 03:04:05.000000"),
8989 mustParseTime(time.StampNano, "Jan 2 03:04:05.000000006"),
8990 mustParseTime(time.DateTime, "1234-01-02 03:04:05"),
8991 mustParseTime(time.DateOnly, "1234-01-02"),
8992 mustParseTime(time.TimeOnly, "03:04:05"),
8993 mustParseTime("2006-01-02", "1234-01-02"),
8994 mustParseTime(`\"weird\"2006`, `\"weird\"1234`),
8995 time.Unix(-23225777755, 6).UTC(),
8996 time.Unix(-23225777755, 6).UTC(),
8997 time.Unix(-23225777755, 6).UTC(),
8998 time.Unix(-23225777755, 6).UTC(),
8999 time.Unix(-23225777755, 6).UTC(),
9000 time.Unix(-23225777755, 6).UTC(),
9001 time.Unix(-23225777755, 6).UTC(),
9002 time.Unix(-23225777755, 6).UTC(),
9003 }),
9004 }, {
9005 name: jsontest.Name("Time/Format/UnixString/InvalidNumber"),
9006 inBuf: `{
9007 "T23": -23225777754.999999994,
9008 "T25": -23225777754999.999994,
9009 "T27": -23225777754999999.994,
9010 "T29": -23225777754999999994
9011 }`,
9012 inVal: new(structTimeFormat),
9013 want: new(structTimeFormat),
9014 wantErr: EU(nil).withPos(`{`+"\n\t\t\t"+`"T23": `, "/T23").withType('0', timeTimeType),
9015 }, {
9016 name: jsontest.Name("Time/Format/UnixString/InvalidString"),
9017 inBuf: `{
9018 "T22": "-23225777754.999999994",
9019 "T24": "-23225777754999.999994",
9020 "T26": "-23225777754999999.994",
9021 "T28": "-23225777754999999994"
9022 }`,
9023 inVal: new(structTimeFormat),
9024 want: new(structTimeFormat),
9025 wantErr: EU(nil).withPos(`{`+"\n\t\t\t"+`"T22": `, "/T22").withType('"', timeTimeType),
9026 }, {
9027 name: jsontest.Name("Time/Format/Null"),
9028 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,"T19":null,"T20":null,"T21":null,"T22":null,"T23":null,"T24":null,"T25":null,"T26":null,"T27":null,"T28":null,"T29":null}`,
9029 inVal: addr(structTimeFormat{
9030 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
9031 mustParseTime(time.ANSIC, "Mon Jan 2 03:04:05 1234"),
9032 mustParseTime(time.UnixDate, "Mon Jan 2 03:04:05 UTC 1234"),
9033 mustParseTime(time.RubyDate, "Mon Jan 02 03:04:05 +0000 1234"),
9034 mustParseTime(time.RFC822, "02 Jan 34 03:04 UTC"),
9035 mustParseTime(time.RFC822Z, "02 Jan 34 03:04 +0000"),
9036 mustParseTime(time.RFC850, "Monday, 02-Jan-34 03:04:05 UTC"),
9037 mustParseTime(time.RFC1123, "Mon, 02 Jan 1234 03:04:05 UTC"),
9038 mustParseTime(time.RFC1123Z, "Mon, 02 Jan 1234 03:04:05 +0000"),
9039 mustParseTime(time.RFC3339, "1234-01-02T03:04:05Z"),
9040 mustParseTime(time.RFC3339Nano, "1234-01-02T03:04:05.000000006Z"),
9041 mustParseTime(time.Kitchen, "3:04AM"),
9042 mustParseTime(time.Stamp, "Jan 2 03:04:05"),
9043 mustParseTime(time.StampMilli, "Jan 2 03:04:05.000"),
9044 mustParseTime(time.StampMicro, "Jan 2 03:04:05.000000"),
9045 mustParseTime(time.StampNano, "Jan 2 03:04:05.000000006"),
9046 mustParseTime(time.DateTime, "1234-01-02 03:04:05"),
9047 mustParseTime(time.DateOnly, "1234-01-02"),
9048 mustParseTime(time.TimeOnly, "03:04:05"),
9049 mustParseTime("2006-01-02", "1234-01-02"),
9050 mustParseTime(`\"weird\"2006`, `\"weird\"1234`),
9051 time.Unix(-23225777755, 6).UTC(),
9052 time.Unix(-23225777755, 6).UTC(),
9053 time.Unix(-23225777755, 6).UTC(),
9054 time.Unix(-23225777755, 6).UTC(),
9055 time.Unix(-23225777755, 6).UTC(),
9056 time.Unix(-23225777755, 6).UTC(),
9057 time.Unix(-23225777755, 6).UTC(),
9058 time.Unix(-23225777755, 6).UTC(),
9059 }),
9060 want: new(structTimeFormat),
9061 }, {
9062 name: jsontest.Name("Time/RFC3339/Mismatch"),
9063 inBuf: `{"T":1234}`,
9064 inVal: new(struct {
9065 T time.Time
9066 }),
9067 wantErr: EU(nil).withPos(`{"T":`, "/T").withType('0', timeTimeType),
9068 }, {
9069 name: jsontest.Name("Time/RFC3339/ParseError"),
9070 inBuf: `{"T":"2021-09-29T12:44:52"}`,
9071 inVal: new(struct {
9072 T time.Time
9073 }),
9074 wantErr: EU(func() error {
9075 _, err := time.Parse(time.RFC3339, "2021-09-29T12:44:52")
9076 return err
9077 }()).withPos(`{"T":`, "/T").withType('"', timeTimeType),
9078 }, {
9079 name: jsontest.Name("Time/Format/Invalid"),
9080 inBuf: `{"T":""}`,
9081 inVal: new(struct {
9082 T time.Time `json:",format:UndefinedConstant"`
9083 }),
9084 wantErr: EU(errors.New(`invalid format flag "UndefinedConstant"`)).withPos(`{"T":`, "/T").withType(0, timeTimeType),
9085 }, {
9086 name: jsontest.Name("Time/Format/SingleDigitHour"),
9087 inBuf: `{"T":"2000-01-01T1:12:34Z"}`,
9088 inVal: new(struct{ T time.Time }),
9089 wantErr: EU(newParseTimeError(time.RFC3339, "2000-01-01T1:12:34Z", "15", "1", "")).withPos(`{"T":`, "/T").withType('"', timeTimeType),
9090 }, {
9091 name: jsontest.Name("Time/Format/SubsecondComma"),
9092 inBuf: `{"T":"2000-01-01T00:00:00,000Z"}`,
9093 inVal: new(struct{ T time.Time }),
9094 wantErr: EU(newParseTimeError(time.RFC3339, "2000-01-01T00:00:00,000Z", ".", ",", "")).withPos(`{"T":`, "/T").withType('"', timeTimeType),
9095 }, {
9096 name: jsontest.Name("Time/Format/TimezoneHourOverflow"),
9097 inBuf: `{"T":"2000-01-01T00:00:00+24:00"}`,
9098 inVal: new(struct{ T time.Time }),
9099 wantErr: EU(newParseTimeError(time.RFC3339, "2000-01-01T00:00:00+24:00", "Z07:00", "+24:00", ": timezone hour out of range")).withPos(`{"T":`, "/T").withType('"', timeTimeType),
9100 }, {
9101 name: jsontest.Name("Time/Format/TimezoneMinuteOverflow"),
9102 inBuf: `{"T":"2000-01-01T00:00:00+00:60"}`,
9103 inVal: new(struct{ T time.Time }),
9104 wantErr: EU(newParseTimeError(time.RFC3339, "2000-01-01T00:00:00+00:60", "Z07:00", "+00:60", ": timezone minute out of range")).withPos(`{"T":`, "/T").withType('"', timeTimeType),
9105 }, {
9106 name: jsontest.Name("Time/Syntax/Invalid"),
9107 inBuf: `{"T":x}`,
9108 inVal: new(struct {
9109 T time.Time
9110 }),
9111 wantErr: newInvalidCharacterError("x", "at start of value", len64(`{"T":`), "/T"),
9112 }, {
9113 name: jsontest.Name("Time/IgnoreInvalidFormat"),
9114 opts: []Options{invalidFormatOption},
9115 inBuf: `"2000-01-01T00:00:00Z"`,
9116 inVal: addr(time.Time{}),
9117 want: addr(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)),
9118 }}
9119
9120 for _, tt := range tests {
9121 t.Run(tt.name.Name, func(t *testing.T) {
9122 got := tt.inVal
9123 gotErr := Unmarshal([]byte(tt.inBuf), got, tt.opts...)
9124 if !reflect.DeepEqual(got, tt.want) && tt.want != nil {
9125 t.Errorf("%s: Unmarshal output mismatch:\ngot %v\nwant %v", tt.name.Where, got, tt.want)
9126 }
9127 if !reflect.DeepEqual(gotErr, tt.wantErr) {
9128 t.Errorf("%s: Unmarshal error mismatch:\ngot %v\nwant %v", tt.name.Where, gotErr, tt.wantErr)
9129 }
9130 })
9131 }
9132 }
9133
9134 func TestMarshalInvalidNamespace(t *testing.T) {
9135 tests := []struct {
9136 name jsontest.CaseName
9137 val any
9138 }{
9139 {jsontest.Name("Map"), map[string]string{"X": "\xde\xad\xbe\xef"}},
9140 {jsontest.Name("Struct"), struct{ X string }{"\xde\xad\xbe\xef"}},
9141 }
9142 for _, tt := range tests {
9143 t.Run(tt.name.Name, func(t *testing.T) {
9144 enc := jsontext.NewEncoder(new(bytes.Buffer))
9145 if err := MarshalEncode(enc, tt.val); err == nil {
9146 t.Fatalf("%s: MarshalEncode error is nil, want non-nil", tt.name.Where)
9147 }
9148 for _, tok := range []jsontext.Token{
9149 jsontext.Null, jsontext.String(""), jsontext.Int(0), jsontext.BeginObject, jsontext.EndObject, jsontext.BeginArray, jsontext.EndArray,
9150 } {
9151 if err := enc.WriteToken(tok); err == nil {
9152 t.Fatalf("%s: WriteToken error is nil, want non-nil", tt.name.Where)
9153 }
9154 }
9155 for _, val := range []string{`null`, `""`, `0`, `{}`, `[]`} {
9156 if err := enc.WriteValue([]byte(val)); err == nil {
9157 t.Fatalf("%s: WriteToken error is nil, want non-nil", tt.name.Where)
9158 }
9159 }
9160 })
9161 }
9162 }
9163
9164 func TestUnmarshalInvalidNamespace(t *testing.T) {
9165 tests := []struct {
9166 name jsontest.CaseName
9167 val any
9168 }{
9169 {jsontest.Name("Map"), addr(map[string]int{})},
9170 {jsontest.Name("Struct"), addr(struct{ X int }{})},
9171 }
9172 for _, tt := range tests {
9173 t.Run(tt.name.Name, func(t *testing.T) {
9174 dec := jsontext.NewDecoder(strings.NewReader(`{"X":""}`))
9175 if err := UnmarshalDecode(dec, tt.val); err == nil {
9176 t.Fatalf("%s: UnmarshalDecode error is nil, want non-nil", tt.name.Where)
9177 }
9178 if _, err := dec.ReadToken(); err == nil {
9179 t.Fatalf("%s: ReadToken error is nil, want non-nil", tt.name.Where)
9180 }
9181 if _, err := dec.ReadValue(); err == nil {
9182 t.Fatalf("%s: ReadValue error is nil, want non-nil", tt.name.Where)
9183 }
9184 })
9185 }
9186 }
9187
9188 func TestUnmarshalReuse(t *testing.T) {
9189 t.Run("Bytes", func(t *testing.T) {
9190 in := make([]byte, 3)
9191 want := &in[0]
9192 if err := Unmarshal([]byte(`"AQID"`), &in); err != nil {
9193 t.Fatalf("Unmarshal error: %v", err)
9194 }
9195 got := &in[0]
9196 if got != want {
9197 t.Errorf("input buffer was not reused")
9198 }
9199 })
9200 t.Run("Slices", func(t *testing.T) {
9201 in := make([]int, 3)
9202 want := &in[0]
9203 if err := Unmarshal([]byte(`[0,1,2]`), &in); err != nil {
9204 t.Fatalf("Unmarshal error: %v", err)
9205 }
9206 got := &in[0]
9207 if got != want {
9208 t.Errorf("input slice was not reused")
9209 }
9210 })
9211 t.Run("Maps", func(t *testing.T) {
9212 in := make(map[string]string)
9213 want := reflect.ValueOf(in).Pointer()
9214 if err := Unmarshal([]byte(`{"key":"value"}`), &in); err != nil {
9215 t.Fatalf("Unmarshal error: %v", err)
9216 }
9217 got := reflect.ValueOf(in).Pointer()
9218 if got != want {
9219 t.Errorf("input map was not reused")
9220 }
9221 })
9222 t.Run("Pointers", func(t *testing.T) {
9223 in := addr(addr(addr("hello")))
9224 want := **in
9225 if err := Unmarshal([]byte(`"goodbye"`), &in); err != nil {
9226 t.Fatalf("Unmarshal error: %v", err)
9227 }
9228 got := **in
9229 if got != want {
9230 t.Errorf("input pointer was not reused")
9231 }
9232 })
9233 }
9234
9235 type ReaderFunc func([]byte) (int, error)
9236
9237 func (f ReaderFunc) Read(b []byte) (int, error) { return f(b) }
9238
9239 type WriterFunc func([]byte) (int, error)
9240
9241 func (f WriterFunc) Write(b []byte) (int, error) { return f(b) }
9242
9243 func TestCoderBufferGrowth(t *testing.T) {
9244 // The growth rate of the internal buffer should be exponential,
9245 // but should not grow unbounded.
9246 checkGrowth := func(ns []int) {
9247 t.Helper()
9248 var sumBytes, sumRates, numGrows float64
9249 prev := ns[0]
9250 for i := 1; i < len(ns)-1; i++ {
9251 n := ns[i]
9252 if n != prev {
9253 sumRates += float64(n) / float64(prev)
9254 numGrows++
9255 prev = n
9256 }
9257 if n > 1<<20 {
9258 t.Fatalf("single Read/Write too large: %d", n)
9259 }
9260 sumBytes += float64(n)
9261 }
9262 if mean := sumBytes / float64(len(ns)); mean < 1<<10 {
9263 t.Fatalf("average Read/Write too small: %0.1f", mean)
9264 }
9265 switch mean := sumRates / numGrows; {
9266 case mean < 1.25:
9267 t.Fatalf("average growth rate too slow: %0.3f", mean)
9268 case mean > 2.00:
9269 t.Fatalf("average growth rate too fast: %0.3f", mean)
9270 }
9271 }
9272
9273 // bb is identical to bytes.Buffer,
9274 // but a different type to avoid any optimizations for bytes.Buffer.
9275 bb := struct{ *bytes.Buffer }{new(bytes.Buffer)}
9276
9277 var writeSizes []int
9278 if err := MarshalWrite(WriterFunc(func(b []byte) (int, error) {
9279 n, err := bb.Write(b)
9280 writeSizes = append(writeSizes, n)
9281 return n, err
9282 }), make([]struct{}, 1e6)); err != nil {
9283 t.Fatalf("MarshalWrite error: %v", err)
9284 }
9285 checkGrowth(writeSizes)
9286
9287 var readSizes []int
9288 if err := UnmarshalRead(ReaderFunc(func(b []byte) (int, error) {
9289 n, err := bb.Read(b)
9290 readSizes = append(readSizes, n)
9291 return n, err
9292 }), new([]struct{})); err != nil {
9293 t.Fatalf("UnmarshalRead error: %v", err)
9294 }
9295 checkGrowth(readSizes)
9296 }
9297
9298 func TestUintSet(t *testing.T) {
9299 type operation any // has | insert
9300 type has struct {
9301 in uint
9302 want bool
9303 }
9304 type insert struct {
9305 in uint
9306 want bool
9307 }
9308
9309 // Sequence of operations to perform (order matters).
9310 ops := []operation{
9311 has{0, false},
9312 has{63, false},
9313 has{64, false},
9314 has{1234, false},
9315 insert{3, true},
9316 has{2, false},
9317 has{3, true},
9318 has{4, false},
9319 has{63, false},
9320 insert{3, false},
9321 insert{63, true},
9322 has{63, true},
9323 insert{64, true},
9324 insert{64, false},
9325 has{64, true},
9326 insert{3264, true},
9327 has{3264, true},
9328 insert{3, false},
9329 has{3, true},
9330 }
9331
9332 var us uintSet
9333 for i, op := range ops {
9334 switch op := op.(type) {
9335 case has:
9336 if got := us.has(op.in); got != op.want {
9337 t.Fatalf("%d: uintSet.has(%v) = %v, want %v", i, op.in, got, op.want)
9338 }
9339 case insert:
9340 if got := us.insert(op.in); got != op.want {
9341 t.Fatalf("%d: uintSet.insert(%v) = %v, want %v", i, op.in, got, op.want)
9342 }
9343 default:
9344 panic(fmt.Sprintf("unknown operation: %T", op))
9345 }
9346 }
9347 }
9348
9349 func TestUnmarshalDecodeOptions(t *testing.T) {
9350 var calledFuncs int
9351 var calledOptions Options
9352 in := strings.NewReader(strings.Repeat("\"\xde\xad\xbe\xef\"\n", 5))
9353 dec := jsontext.NewDecoder(in,
9354 jsontext.AllowInvalidUTF8(true), // decoder-specific option
9355 WithUnmarshalers(UnmarshalFromFunc(func(dec *jsontext.Decoder, _ any) error {
9356 opts := dec.Options()
9357 if v, _ := GetOption(opts, jsontext.AllowInvalidUTF8); !v {
9358 t.Errorf("nested Options.AllowInvalidUTF8 = false, want true")
9359 }
9360 calledFuncs++
9361 calledOptions = opts
9362 return SkipFunc
9363 })), // unmarshal-specific option; only relevant for UnmarshalDecode
9364 )
9365
9366 if err := UnmarshalDecode(dec, new(string)); err != nil {
9367 t.Fatalf("UnmarshalDecode: %v", err)
9368 }
9369 if calledFuncs != 1 {
9370 t.Fatalf("calledFuncs = %d, want 1", calledFuncs)
9371 }
9372 if err := UnmarshalDecode(dec, new(string), calledOptions); err != nil {
9373 t.Fatalf("UnmarshalDecode: %v", err)
9374 }
9375 if calledFuncs != 2 {
9376 t.Fatalf("calledFuncs = %d, want 2", calledFuncs)
9377 }
9378 if err := UnmarshalDecode(dec, new(string),
9379 jsontext.AllowInvalidUTF8(false), // should be ignored
9380 WithUnmarshalers(nil), // should override
9381 ); err != nil {
9382 t.Fatalf("UnmarshalDecode: %v", err)
9383 }
9384 if calledFuncs != 2 {
9385 t.Fatalf("calledFuncs = %d, want 2", calledFuncs)
9386 }
9387 if err := UnmarshalDecode(dec, new(string)); err != nil {
9388 t.Fatalf("UnmarshalDecode: %v", err)
9389 }
9390 if calledFuncs != 3 {
9391 t.Fatalf("calledFuncs = %d, want 3", calledFuncs)
9392 }
9393 if err := UnmarshalDecode(dec, new(string), JoinOptions(
9394 jsontext.AllowInvalidUTF8(false), // should be ignored
9395 WithUnmarshalers(UnmarshalFromFunc(func(_ *jsontext.Decoder, _ any) error {
9396 opts := dec.Options()
9397 if v, _ := GetOption(opts, jsontext.AllowInvalidUTF8); !v {
9398 t.Errorf("nested Options.AllowInvalidUTF8 = false, want true")
9399 }
9400 calledFuncs = math.MaxInt
9401 return SkipFunc
9402 })), // should override
9403 )); err != nil {
9404 t.Fatalf("UnmarshalDecode: %v", err)
9405 }
9406 if calledFuncs != math.MaxInt {
9407 t.Fatalf("calledFuncs = %d, want %d", calledFuncs, math.MaxInt)
9408 }
9409
9410 // Reset with the decoder options as part of the arguments should not
9411 // observe mutations to the options until after Reset is done.
9412 opts := dec.Options() // AllowInvalidUTF8 is currently true
9413 dec.Reset(in, jsontext.AllowInvalidUTF8(false), opts) // earlier AllowInvalidUTF8(false) should be overridden by latter AllowInvalidUTF8(true) in opts
9414 if v, _ := GetOption(dec.Options(), jsontext.AllowInvalidUTF8); v == false {
9415 t.Errorf("Options.AllowInvalidUTF8 = false, want true")
9416 }
9417 }
9418
9419 func TestUnmarshalDecodeStream(t *testing.T) {
9420 tests := []struct {
9421 in string
9422 want []any
9423 err error
9424 }{
9425 {in: ``, err: io.EOF},
9426 {in: `{`, err: &jsontext.SyntacticError{ByteOffset: len64(`{`), Err: io.ErrUnexpectedEOF}},
9427 {in: `{"`, err: &jsontext.SyntacticError{ByteOffset: len64(`{"`), Err: io.ErrUnexpectedEOF}},
9428 {in: `{"k"`, err: &jsontext.SyntacticError{ByteOffset: len64(`{"k"`), JSONPointer: "/k", Err: io.ErrUnexpectedEOF}},
9429 {in: `{"k":`, err: &jsontext.SyntacticError{ByteOffset: len64(`{"k":`), JSONPointer: "/k", Err: io.ErrUnexpectedEOF}},
9430 {in: `{"k",`, err: &jsontext.SyntacticError{ByteOffset: len64(`{"k"`), JSONPointer: "/k", Err: jsonwire.NewInvalidCharacterError(",", "after object name (expecting ':')")}},
9431 {in: `{"k"}`, err: &jsontext.SyntacticError{ByteOffset: len64(`{"k"`), JSONPointer: "/k", Err: jsonwire.NewInvalidCharacterError("}", "after object name (expecting ':')")}},
9432 {in: `[`, err: &jsontext.SyntacticError{ByteOffset: len64(`[`), Err: io.ErrUnexpectedEOF}},
9433 {in: `[0`, err: &jsontext.SyntacticError{ByteOffset: len64(`[0`), Err: io.ErrUnexpectedEOF}},
9434 {in: ` [0`, err: &jsontext.SyntacticError{ByteOffset: len64(` [0`), Err: io.ErrUnexpectedEOF}},
9435 {in: `[0.`, err: &jsontext.SyntacticError{ByteOffset: len64(`[`), JSONPointer: "/0", Err: io.ErrUnexpectedEOF}},
9436 {in: `[0. `, err: &jsontext.SyntacticError{ByteOffset: len64(`[0.`), JSONPointer: "/0", Err: jsonwire.NewInvalidCharacterError(" ", "in number (expecting digit)")}},
9437 {in: `[0,`, err: &jsontext.SyntacticError{ByteOffset: len64(`[0,`), Err: io.ErrUnexpectedEOF}},
9438 {in: `[0:`, err: &jsontext.SyntacticError{ByteOffset: len64(`[0`), Err: jsonwire.NewInvalidCharacterError(":", "after array element (expecting ',' or ']')")}},
9439 {in: `n`, err: &jsontext.SyntacticError{ByteOffset: len64(`n`), Err: io.ErrUnexpectedEOF}},
9440 {in: `nul`, err: &jsontext.SyntacticError{ByteOffset: len64(`nul`), Err: io.ErrUnexpectedEOF}},
9441 {in: `fal `, err: &jsontext.SyntacticError{ByteOffset: len64(`fal`), Err: jsonwire.NewInvalidCharacterError(" ", "in literal false (expecting 's')")}},
9442 {in: `false`, want: []any{false}, err: io.EOF},
9443 {in: `false0.0[]null`, want: []any{false, 0.0, []any{}, nil}, err: io.EOF},
9444 }
9445 for _, tt := range tests {
9446 d := jsontext.NewDecoder(strings.NewReader(tt.in))
9447 var got []any
9448 for {
9449 var v any
9450 if err := UnmarshalDecode(d, &v); err != nil {
9451 if !reflect.DeepEqual(err, tt.err) {
9452 t.Errorf("`%s`: UnmarshalDecode error = %v, want %v", tt.in, err, tt.err)
9453 }
9454 break
9455 }
9456 got = append(got, v)
9457 }
9458 if !reflect.DeepEqual(got, tt.want) {
9459 t.Errorf("`%s`: UnmarshalDecode = %v, want %v", tt.in, got, tt.want)
9460 }
9461 }
9462 }
9463
9464 // BenchmarkUnmarshalDecodeOptions is a minimal decode operation to measure
9465 // the overhead options setup before the unmarshal operation.
9466 func BenchmarkUnmarshalDecodeOptions(b *testing.B) {
9467 var i int
9468 in := new(bytes.Buffer)
9469 dec := jsontext.NewDecoder(in)
9470 makeBench := func(opts ...Options) func(*testing.B) {
9471 return func(b *testing.B) {
9472 for range b.N {
9473 in.WriteString("0 ")
9474 }
9475 dec.Reset(in)
9476 b.ResetTimer()
9477 for range b.N {
9478 UnmarshalDecode(dec, &i, opts...)
9479 }
9480 }
9481 }
9482 b.Run("None", makeBench())
9483 b.Run("Same", makeBench(&export.Decoder(dec).Struct))
9484 b.Run("New", makeBench(DefaultOptionsV2()))
9485 }
9486
9487 func TestMarshalEncodeOptions(t *testing.T) {
9488 var calledFuncs int
9489 var calledOptions Options
9490 out := new(bytes.Buffer)
9491 enc := jsontext.NewEncoder(
9492 out,
9493 jsontext.AllowInvalidUTF8(true), // encoder-specific option
9494 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, _ any) error {
9495 opts := enc.Options()
9496 if v, _ := GetOption(opts, jsontext.AllowInvalidUTF8); !v {
9497 t.Errorf("nested Options.AllowInvalidUTF8 = false, want true")
9498 }
9499 calledFuncs++
9500 calledOptions = opts
9501 return SkipFunc
9502 })), // marshal-specific option; only relevant for MarshalEncode
9503 )
9504
9505 if err := MarshalEncode(enc, "\xde\xad\xbe\xef"); err != nil {
9506 t.Fatalf("MarshalEncode: %v", err)
9507 }
9508 if calledFuncs != 1 {
9509 t.Fatalf("calledFuncs = %d, want 1", calledFuncs)
9510 }
9511 if err := MarshalEncode(enc, "\xde\xad\xbe\xef", calledOptions); err != nil {
9512 t.Fatalf("MarshalEncode: %v", err)
9513 }
9514 if calledFuncs != 2 {
9515 t.Fatalf("calledFuncs = %d, want 2", calledFuncs)
9516 }
9517 if err := MarshalEncode(enc, "\xde\xad\xbe\xef",
9518 jsontext.AllowInvalidUTF8(false), // should be ignored
9519 WithMarshalers(nil), // should override
9520 ); err != nil {
9521 t.Fatalf("MarshalEncode: %v", err)
9522 }
9523 if calledFuncs != 2 {
9524 t.Fatalf("calledFuncs = %d, want 2", calledFuncs)
9525 }
9526 if err := MarshalEncode(enc, "\xde\xad\xbe\xef"); err != nil {
9527 t.Fatalf("MarshalEncode: %v", err)
9528 }
9529 if calledFuncs != 3 {
9530 t.Fatalf("calledFuncs = %d, want 3", calledFuncs)
9531 }
9532 if err := MarshalEncode(enc, "\xde\xad\xbe\xef", JoinOptions(
9533 jsontext.AllowInvalidUTF8(false), // should be ignored
9534 WithMarshalers(MarshalToFunc(func(enc *jsontext.Encoder, _ any) error {
9535 opts := enc.Options()
9536 if v, _ := GetOption(opts, jsontext.AllowInvalidUTF8); !v {
9537 t.Errorf("nested Options.AllowInvalidUTF8 = false, want true")
9538 }
9539 calledFuncs = math.MaxInt
9540 return SkipFunc
9541 })), // should override
9542 )); err != nil {
9543 t.Fatalf("MarshalEncode: %v", err)
9544 }
9545 if calledFuncs != math.MaxInt {
9546 t.Fatalf("calledFuncs = %d, want %d", calledFuncs, math.MaxInt)
9547 }
9548 if out.String() != strings.Repeat("\"\xde\xad\ufffd\ufffd\"\n", 5) {
9549 t.Fatalf("output mismatch:\n\tgot: %s\n\twant: %s", out.String(), strings.Repeat("\"\xde\xad\xbe\xef\"\n", 5))
9550 }
9551
9552 // Reset with the encoder options as part of the arguments should not
9553 // observe mutations to the options until after Reset is done.
9554 opts := enc.Options() // AllowInvalidUTF8 is currently true
9555 enc.Reset(out, jsontext.AllowInvalidUTF8(false), opts) // earlier AllowInvalidUTF8(false) should be overridden by latter AllowInvalidUTF8(true) in opts
9556 if v, _ := GetOption(enc.Options(), jsontext.AllowInvalidUTF8); v == false {
9557 t.Errorf("Options.AllowInvalidUTF8 = false, want true")
9558 }
9559 }
9560
9561 // BenchmarkMarshalEncodeOptions is a minimal encode operation to measure
9562 // the overhead of options setup before the marshal operation.
9563 func BenchmarkMarshalEncodeOptions(b *testing.B) {
9564 var i int
9565 out := new(bytes.Buffer)
9566 enc := jsontext.NewEncoder(out)
9567 makeBench := func(opts ...Options) func(*testing.B) {
9568 return func(b *testing.B) {
9569 out.Reset()
9570 enc.Reset(out)
9571 b.ResetTimer()
9572 for range b.N {
9573 MarshalEncode(enc, &i, opts...)
9574 }
9575 }
9576 }
9577 b.Run("None", makeBench())
9578 b.Run("Same", makeBench(&export.Encoder(enc).Struct))
9579 b.Run("New", makeBench(DefaultOptionsV2()))
9580 }