Source file src/encoding/json/v2_encode_test.go

     1  // Copyright 2011 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  //go:build goexperiment.jsonv2
     6  
     7  package json
     8  
     9  import (
    10  	"bytes"
    11  	"encoding"
    12  	"fmt"
    13  	"log"
    14  	"math"
    15  	"reflect"
    16  	"regexp"
    17  	"runtime/debug"
    18  	"strconv"
    19  	"sync"
    20  	"testing"
    21  	"testing/synctest"
    22  	"time"
    23  )
    24  
    25  type OptionalsEmpty struct {
    26  	Sr string `json:"sr"`
    27  	So string `json:"so,omitempty"`
    28  	Sw string `json:"-"`
    29  
    30  	Ir int `json:"omitempty"` // actually named omitempty, not an option
    31  	Io int `json:"io,omitempty"`
    32  
    33  	Slr []string `json:"slr,random"`
    34  	Slo []string `json:"slo,omitempty"`
    35  
    36  	Mr map[string]any `json:"mr"`
    37  	Mo map[string]any `json:",omitempty"`
    38  
    39  	Fr float64 `json:"fr"`
    40  	Fo float64 `json:"fo,omitempty"`
    41  
    42  	Br bool `json:"br"`
    43  	Bo bool `json:"bo,omitempty"`
    44  
    45  	Ur uint `json:"ur"`
    46  	Uo uint `json:"uo,omitempty"`
    47  
    48  	Str struct{} `json:"str"`
    49  	Sto struct{} `json:"sto,omitempty"`
    50  }
    51  
    52  func TestOmitEmpty(t *testing.T) {
    53  	const want = `{
    54   "sr": "",
    55   "omitempty": 0,
    56   "slr": null,
    57   "mr": {},
    58   "fr": 0,
    59   "br": false,
    60   "ur": 0,
    61   "str": {},
    62   "sto": {}
    63  }`
    64  	var o OptionalsEmpty
    65  	o.Sw = "something"
    66  	o.Mr = map[string]any{}
    67  	o.Mo = map[string]any{}
    68  
    69  	got, err := MarshalIndent(&o, "", " ")
    70  	if err != nil {
    71  		t.Fatalf("MarshalIndent error: %v", err)
    72  	}
    73  	if got := string(got); got != want {
    74  		t.Errorf("MarshalIndent:\n\tgot:  %s\n\twant: %s\n", indentNewlines(got), indentNewlines(want))
    75  	}
    76  }
    77  
    78  type NonZeroStruct struct{}
    79  
    80  func (nzs NonZeroStruct) IsZero() bool {
    81  	return false
    82  }
    83  
    84  type NoPanicStruct struct {
    85  	Int int `json:"int,omitzero"`
    86  }
    87  
    88  func (nps *NoPanicStruct) IsZero() bool {
    89  	return nps.Int != 0
    90  }
    91  
    92  type isZeroer interface {
    93  	IsZero() bool
    94  }
    95  
    96  type OptionalsZero struct {
    97  	Sr string `json:"sr"`
    98  	So string `json:"so,omitzero"`
    99  	Sw string `json:"-"`
   100  
   101  	Ir int `json:"omitzero"` // actually named omitzero, not an option
   102  	Io int `json:"io,omitzero"`
   103  
   104  	Slr       []string `json:"slr,random"`
   105  	Slo       []string `json:"slo,omitzero"`
   106  	SloNonNil []string `json:"slononnil,omitzero"`
   107  
   108  	Mr  map[string]any `json:"mr"`
   109  	Mo  map[string]any `json:",omitzero"`
   110  	Moo map[string]any `json:"moo,omitzero"`
   111  
   112  	Fr   float64    `json:"fr"`
   113  	Fo   float64    `json:"fo,omitzero"`
   114  	Foo  float64    `json:"foo,omitzero"`
   115  	Foo2 [2]float64 `json:"foo2,omitzero"`
   116  
   117  	Br bool `json:"br"`
   118  	Bo bool `json:"bo,omitzero"`
   119  
   120  	Ur uint `json:"ur"`
   121  	Uo uint `json:"uo,omitzero"`
   122  
   123  	Str struct{} `json:"str"`
   124  	Sto struct{} `json:"sto,omitzero"`
   125  
   126  	Time      time.Time     `json:"time,omitzero"`
   127  	TimeLocal time.Time     `json:"timelocal,omitzero"`
   128  	Nzs       NonZeroStruct `json:"nzs,omitzero"`
   129  
   130  	NilIsZeroer    isZeroer       `json:"niliszeroer,omitzero"`    // nil interface
   131  	NonNilIsZeroer isZeroer       `json:"nonniliszeroer,omitzero"` // non-nil interface
   132  	NoPanicStruct0 isZeroer       `json:"nps0,omitzero"`           // non-nil interface with nil pointer
   133  	NoPanicStruct1 isZeroer       `json:"nps1,omitzero"`           // non-nil interface with non-nil pointer
   134  	NoPanicStruct2 *NoPanicStruct `json:"nps2,omitzero"`           // nil pointer
   135  	NoPanicStruct3 *NoPanicStruct `json:"nps3,omitzero"`           // non-nil pointer
   136  	NoPanicStruct4 NoPanicStruct  `json:"nps4,omitzero"`           // concrete type
   137  }
   138  
   139  func TestOmitZero(t *testing.T) {
   140  	const want = `{
   141   "sr": "",
   142   "omitzero": 0,
   143   "slr": null,
   144   "slononnil": [],
   145   "mr": {},
   146   "Mo": {},
   147   "fr": 0,
   148   "br": false,
   149   "ur": 0,
   150   "str": {},
   151   "nzs": {},
   152   "nps1": {},
   153   "nps3": {},
   154   "nps4": {}
   155  }`
   156  	var o OptionalsZero
   157  	o.Sw = "something"
   158  	o.SloNonNil = make([]string, 0)
   159  	o.Mr = map[string]any{}
   160  	o.Mo = map[string]any{}
   161  
   162  	o.Foo = -0
   163  	o.Foo2 = [2]float64{+0, -0}
   164  
   165  	o.TimeLocal = time.Time{}.Local()
   166  
   167  	o.NonNilIsZeroer = time.Time{}
   168  	o.NoPanicStruct0 = (*NoPanicStruct)(nil)
   169  	o.NoPanicStruct1 = &NoPanicStruct{}
   170  	o.NoPanicStruct3 = &NoPanicStruct{}
   171  
   172  	got, err := MarshalIndent(&o, "", " ")
   173  	if err != nil {
   174  		t.Fatalf("MarshalIndent error: %v", err)
   175  	}
   176  	if got := string(got); got != want {
   177  		t.Errorf("MarshalIndent:\n\tgot:  %s\n\twant: %s\n", indentNewlines(got), indentNewlines(want))
   178  	}
   179  }
   180  
   181  func TestOmitZeroMap(t *testing.T) {
   182  	const want = `{
   183   "foo": {
   184    "sr": "",
   185    "omitzero": 0,
   186    "slr": null,
   187    "mr": null,
   188    "fr": 0,
   189    "br": false,
   190    "ur": 0,
   191    "str": {},
   192    "nzs": {},
   193    "nps4": {}
   194   }
   195  }`
   196  	m := map[string]OptionalsZero{"foo": {}}
   197  	got, err := MarshalIndent(m, "", " ")
   198  	if err != nil {
   199  		t.Fatalf("MarshalIndent error: %v", err)
   200  	}
   201  	if got := string(got); got != want {
   202  		fmt.Println(got)
   203  		t.Errorf("MarshalIndent:\n\tgot:  %s\n\twant: %s\n", indentNewlines(got), indentNewlines(want))
   204  	}
   205  }
   206  
   207  type OptionalsEmptyZero struct {
   208  	Sr string `json:"sr"`
   209  	So string `json:"so,omitempty,omitzero"`
   210  	Sw string `json:"-"`
   211  
   212  	Io int `json:"io,omitempty,omitzero"`
   213  
   214  	Slr       []string `json:"slr,random"`
   215  	Slo       []string `json:"slo,omitempty,omitzero"`
   216  	SloNonNil []string `json:"slononnil,omitempty,omitzero"`
   217  
   218  	Mr map[string]any `json:"mr"`
   219  	Mo map[string]any `json:",omitempty,omitzero"`
   220  
   221  	Fr float64 `json:"fr"`
   222  	Fo float64 `json:"fo,omitempty,omitzero"`
   223  
   224  	Br bool `json:"br"`
   225  	Bo bool `json:"bo,omitempty,omitzero"`
   226  
   227  	Ur uint `json:"ur"`
   228  	Uo uint `json:"uo,omitempty,omitzero"`
   229  
   230  	Str struct{} `json:"str"`
   231  	Sto struct{} `json:"sto,omitempty,omitzero"`
   232  
   233  	Time time.Time     `json:"time,omitempty,omitzero"`
   234  	Nzs  NonZeroStruct `json:"nzs,omitempty,omitzero"`
   235  }
   236  
   237  func TestOmitEmptyZero(t *testing.T) {
   238  	const want = `{
   239   "sr": "",
   240   "slr": null,
   241   "mr": {},
   242   "fr": 0,
   243   "br": false,
   244   "ur": 0,
   245   "str": {},
   246   "nzs": {}
   247  }`
   248  	var o OptionalsEmptyZero
   249  	o.Sw = "something"
   250  	o.SloNonNil = make([]string, 0)
   251  	o.Mr = map[string]any{}
   252  	o.Mo = map[string]any{}
   253  
   254  	got, err := MarshalIndent(&o, "", " ")
   255  	if err != nil {
   256  		t.Fatalf("MarshalIndent error: %v", err)
   257  	}
   258  	if got := string(got); got != want {
   259  		t.Errorf("MarshalIndent:\n\tgot:  %s\n\twant: %s\n", indentNewlines(got), indentNewlines(want))
   260  	}
   261  }
   262  
   263  type StringTag struct {
   264  	BoolStr    bool    `json:",string"`
   265  	IntStr     int64   `json:",string"`
   266  	UintptrStr uintptr `json:",string"`
   267  	StrStr     string  `json:",string"`
   268  	NumberStr  Number  `json:",string"`
   269  }
   270  
   271  func TestRoundtripStringTag(t *testing.T) {
   272  	tests := []struct {
   273  		CaseName
   274  		in   StringTag
   275  		want string // empty to just test that we roundtrip
   276  	}{{
   277  		CaseName: Name("AllTypes"),
   278  		in: StringTag{
   279  			BoolStr:    true,
   280  			IntStr:     42,
   281  			UintptrStr: 44,
   282  			StrStr:     "xzbit",
   283  			NumberStr:  "46",
   284  		},
   285  		want: `{
   286  	"BoolStr": "true",
   287  	"IntStr": "42",
   288  	"UintptrStr": "44",
   289  	"StrStr": "\"xzbit\"",
   290  	"NumberStr": "46"
   291  }`,
   292  	}, {
   293  		// See golang.org/issues/38173.
   294  		CaseName: Name("StringDoubleEscapes"),
   295  		in: StringTag{
   296  			StrStr:    "\b\f\n\r\t\"\\",
   297  			NumberStr: "0", // just to satisfy the roundtrip
   298  		},
   299  		want: `{
   300  	"BoolStr": "false",
   301  	"IntStr": "0",
   302  	"UintptrStr": "0",
   303  	"StrStr": "\"\\b\\f\\n\\r\\t\\\"\\\\\"",
   304  	"NumberStr": "0"
   305  }`,
   306  	}}
   307  	for _, tt := range tests {
   308  		t.Run(tt.Name, func(t *testing.T) {
   309  			got, err := MarshalIndent(&tt.in, "", "\t")
   310  			if err != nil {
   311  				t.Fatalf("%s: MarshalIndent error: %v", tt.Where, err)
   312  			}
   313  			if got := string(got); got != tt.want {
   314  				t.Fatalf("%s: MarshalIndent:\n\tgot:  %s\n\twant: %s", tt.Where, stripWhitespace(got), stripWhitespace(tt.want))
   315  			}
   316  
   317  			// Verify that it round-trips.
   318  			var s2 StringTag
   319  			if err := Unmarshal(got, &s2); err != nil {
   320  				t.Fatalf("%s: Decode error: %v", tt.Where, err)
   321  			}
   322  			if !reflect.DeepEqual(s2, tt.in) {
   323  				t.Fatalf("%s: Decode:\n\tinput: %s\n\tgot:  %#v\n\twant: %#v", tt.Where, indentNewlines(string(got)), s2, tt.in)
   324  			}
   325  		})
   326  	}
   327  }
   328  
   329  // byte slices are special even if they're renamed types.
   330  type renamedByte byte
   331  type renamedByteSlice []byte
   332  type renamedRenamedByteSlice []renamedByte
   333  
   334  func TestEncodeRenamedByteSlice(t *testing.T) {
   335  	s := renamedByteSlice("abc")
   336  	got, err := Marshal(s)
   337  	if err != nil {
   338  		t.Fatalf("Marshal error: %v", err)
   339  	}
   340  	want := `"YWJj"`
   341  	if string(got) != want {
   342  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   343  	}
   344  	r := renamedRenamedByteSlice("abc")
   345  	got, err = Marshal(r)
   346  	if err != nil {
   347  		t.Fatalf("Marshal error: %v", err)
   348  	}
   349  	if string(got) != want {
   350  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   351  	}
   352  }
   353  
   354  type SamePointerNoCycle struct {
   355  	Ptr1, Ptr2 *SamePointerNoCycle
   356  }
   357  
   358  var samePointerNoCycle = &SamePointerNoCycle{}
   359  
   360  type PointerCycle struct {
   361  	Ptr *PointerCycle
   362  }
   363  
   364  var pointerCycle = &PointerCycle{}
   365  
   366  type PointerCycleIndirect struct {
   367  	Ptrs []any
   368  }
   369  
   370  type RecursiveSlice []RecursiveSlice
   371  
   372  var (
   373  	pointerCycleIndirect = &PointerCycleIndirect{}
   374  	mapCycle             = make(map[string]any)
   375  	sliceCycle           = []any{nil}
   376  	sliceNoCycle         = []any{nil, nil}
   377  	recursiveSliceCycle  = []RecursiveSlice{nil}
   378  )
   379  
   380  func init() {
   381  	ptr := &SamePointerNoCycle{}
   382  	samePointerNoCycle.Ptr1 = ptr
   383  	samePointerNoCycle.Ptr2 = ptr
   384  
   385  	pointerCycle.Ptr = pointerCycle
   386  	pointerCycleIndirect.Ptrs = []any{pointerCycleIndirect}
   387  
   388  	mapCycle["x"] = mapCycle
   389  	sliceCycle[0] = sliceCycle
   390  	sliceNoCycle[1] = sliceNoCycle[:1]
   391  	const startDetectingCyclesAfter = 1e3
   392  	for i := startDetectingCyclesAfter; i > 0; i-- {
   393  		sliceNoCycle = []any{sliceNoCycle}
   394  	}
   395  	recursiveSliceCycle[0] = recursiveSliceCycle
   396  }
   397  
   398  func TestSamePointerNoCycle(t *testing.T) {
   399  	if _, err := Marshal(samePointerNoCycle); err != nil {
   400  		t.Fatalf("Marshal error: %v", err)
   401  	}
   402  }
   403  
   404  func TestSliceNoCycle(t *testing.T) {
   405  	if _, err := Marshal(sliceNoCycle); err != nil {
   406  		t.Fatalf("Marshal error: %v", err)
   407  	}
   408  }
   409  
   410  func TestUnsupportedValues(t *testing.T) {
   411  	tests := []struct {
   412  		CaseName
   413  		in any
   414  	}{
   415  		{Name(""), math.NaN()},
   416  		{Name(""), math.Inf(-1)},
   417  		{Name(""), math.Inf(1)},
   418  		{Name(""), pointerCycle},
   419  		{Name(""), pointerCycleIndirect},
   420  		{Name(""), mapCycle},
   421  		{Name(""), sliceCycle},
   422  		{Name(""), recursiveSliceCycle},
   423  	}
   424  	for _, tt := range tests {
   425  		t.Run(tt.Name, func(t *testing.T) {
   426  			if _, err := Marshal(tt.in); err != nil {
   427  				if _, ok := err.(*UnsupportedValueError); !ok {
   428  					t.Errorf("%s: Marshal error:\n\tgot:  %T\n\twant: %T", tt.Where, err, new(UnsupportedValueError))
   429  				}
   430  			} else {
   431  				t.Errorf("%s: Marshal error: got nil, want non-nil", tt.Where)
   432  			}
   433  		})
   434  	}
   435  }
   436  
   437  // Issue 81176: UnsupportedValueError.Value should hold the NaN or ±Inf value.
   438  func TestUnsupportedValueErrorValue(t *testing.T) {
   439  	type NamedFloat float64
   440  	tests := []struct {
   441  		CaseName
   442  		in   any
   443  		want any
   444  	}{
   445  		{Name(""), NamedFloat(math.NaN()), NamedFloat(math.NaN())},
   446  		{Name(""), math.Inf(-1), math.Inf(-1)},
   447  		{Name(""), NamedFloat(math.Inf(1)), NamedFloat(math.Inf(1))},
   448  		{Name(""), map[string]float64{"x": math.Inf(1)}, math.Inf(1)},
   449  		{Name(""), []NamedFloat{NamedFloat(math.NaN())}, NamedFloat(math.NaN())},
   450  		{Name(""), struct{ F float64 }{math.Inf(-1)}, math.Inf(-1)},
   451  	}
   452  	for _, tt := range tests {
   453  		t.Run(tt.Name, func(t *testing.T) {
   454  			_, err := Marshal(tt.in)
   455  			uve, ok := err.(*UnsupportedValueError)
   456  			if !ok {
   457  				t.Fatalf("%s: Marshal error:\n\tgot:  %T\n\twant: %T", tt.Where, err, new(UnsupportedValueError))
   458  			}
   459  			got := uve.Value
   460  			want := reflect.ValueOf(tt.want)
   461  			if got.Type() != want.Type() {
   462  				t.Fatalf("%s: UnsupportedValueError.Value.Type = %v, want %v", tt.Where, got.Type(), want.Type())
   463  			}
   464  			equalFloat := func(x, y float64) bool {
   465  				return x == y || math.IsNaN(x) == math.IsNaN(y)
   466  			}
   467  			if !equalFloat(got.Float(), want.Float()) {
   468  				t.Fatalf("%s: UnsupportedValueError.Value.Float = %v, want %v", tt.Where, got.Float(), want.Float())
   469  			}
   470  		})
   471  	}
   472  }
   473  
   474  // Issue 82079: UnsupportedValueError.Value should hold the value with the cycle.
   475  func TestUnsupportedValueErrorValueCycle(t *testing.T) {
   476  	tests := []struct {
   477  		CaseName
   478  		in   any
   479  		want reflect.Type
   480  	}{
   481  		{Name(""), pointerCycle, reflect.TypeFor[*PointerCycle]()},
   482  		{Name(""), pointerCycleIndirect, reflect.TypeFor[*PointerCycleIndirect]()},
   483  		{Name(""), mapCycle, reflect.TypeFor[map[string]any]()},
   484  		{Name(""), sliceCycle, reflect.TypeFor[[]any]()},
   485  		{Name(""), recursiveSliceCycle, reflect.TypeFor[RecursiveSlice]()},
   486  	}
   487  	for _, tt := range tests {
   488  		t.Run(tt.Name, func(t *testing.T) {
   489  			_, err := Marshal(tt.in)
   490  			uve, ok := err.(*UnsupportedValueError)
   491  			if !ok {
   492  				t.Fatalf("%s: Marshal error:\n\tgot:  %T\n\twant: %T", tt.Where, err, new(UnsupportedValueError))
   493  			}
   494  			if !uve.Value.IsValid() {
   495  				t.Fatalf("%s: UnsupportedValueError.Value is invalid", tt.Where)
   496  			}
   497  			if got := uve.Value.Type(); got != tt.want {
   498  				t.Fatalf("%s: UnsupportedValueError.Value.Type = %v, want %v", tt.Where, got, tt.want)
   499  			}
   500  			if got, want := uve.Str, "encountered a cycle via "+tt.want.String(); got != want {
   501  				t.Fatalf("%s: UnsupportedValueError.Str = %q, want %q", tt.Where, got, want)
   502  			}
   503  		})
   504  	}
   505  }
   506  
   507  // Issue 43207
   508  func TestMarshalTextFloatMap(t *testing.T) {
   509  	m := map[textfloat]string{
   510  		textfloat(math.NaN()): "1",
   511  		textfloat(math.NaN()): "1",
   512  	}
   513  	got, err := Marshal(m)
   514  	if err != nil {
   515  		t.Errorf("Marshal error: %v", err)
   516  	}
   517  	want := `{"TF:NaN":"1","TF:NaN":"1"}`
   518  	if string(got) != want {
   519  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   520  	}
   521  }
   522  
   523  // Ref has Marshaler and Unmarshaler methods with pointer receiver.
   524  type Ref int
   525  
   526  func (*Ref) MarshalJSON() ([]byte, error) {
   527  	return []byte(`"ref"`), nil
   528  }
   529  
   530  func (r *Ref) UnmarshalJSON([]byte) error {
   531  	*r = 12
   532  	return nil
   533  }
   534  
   535  // Val has Marshaler methods with value receiver.
   536  type Val int
   537  
   538  func (Val) MarshalJSON() ([]byte, error) {
   539  	return []byte(`"val"`), nil
   540  }
   541  
   542  // RefText has Marshaler and Unmarshaler methods with pointer receiver.
   543  type RefText int
   544  
   545  func (*RefText) MarshalText() ([]byte, error) {
   546  	return []byte(`"ref"`), nil
   547  }
   548  
   549  func (r *RefText) UnmarshalText([]byte) error {
   550  	*r = 13
   551  	return nil
   552  }
   553  
   554  // ValText has Marshaler methods with value receiver.
   555  type ValText int
   556  
   557  func (ValText) MarshalText() ([]byte, error) {
   558  	return []byte(`"val"`), nil
   559  }
   560  
   561  func TestRefValMarshal(t *testing.T) {
   562  	var s = struct {
   563  		R0 Ref
   564  		R1 *Ref
   565  		R2 RefText
   566  		R3 *RefText
   567  		V0 Val
   568  		V1 *Val
   569  		V2 ValText
   570  		V3 *ValText
   571  	}{
   572  		R0: 12,
   573  		R1: new(Ref),
   574  		R2: 14,
   575  		R3: new(RefText),
   576  		V0: 13,
   577  		V1: new(Val),
   578  		V2: 15,
   579  		V3: new(ValText),
   580  	}
   581  	const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}`
   582  	b, err := Marshal(&s)
   583  	if err != nil {
   584  		t.Fatalf("Marshal error: %v", err)
   585  	}
   586  	if got := string(b); got != want {
   587  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   588  	}
   589  }
   590  
   591  // C implements Marshaler and returns unescaped JSON.
   592  type C int
   593  
   594  func (C) MarshalJSON() ([]byte, error) {
   595  	return []byte(`"<&>"`), nil
   596  }
   597  
   598  // CText implements Marshaler and returns unescaped text.
   599  type CText int
   600  
   601  func (CText) MarshalText() ([]byte, error) {
   602  	return []byte(`"<&>"`), nil
   603  }
   604  
   605  func TestMarshalerEscaping(t *testing.T) {
   606  	var c C
   607  	want := `"\u003c\u0026\u003e"`
   608  	b, err := Marshal(c)
   609  	if err != nil {
   610  		t.Fatalf("Marshal error: %v", err)
   611  	}
   612  	if got := string(b); got != want {
   613  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   614  	}
   615  
   616  	var ct CText
   617  	want = `"\"\u003c\u0026\u003e\""`
   618  	b, err = Marshal(ct)
   619  	if err != nil {
   620  		t.Fatalf("Marshal error: %v", err)
   621  	}
   622  	if got := string(b); got != want {
   623  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   624  	}
   625  }
   626  
   627  func TestAnonymousFields(t *testing.T) {
   628  	tests := []struct {
   629  		CaseName
   630  		makeInput func() any // Function to create input value
   631  		want      string     // Expected JSON output
   632  	}{{
   633  		// Both S1 and S2 have a field named X. From the perspective of S,
   634  		// it is ambiguous which one X refers to.
   635  		// This should not serialize either field.
   636  		CaseName: Name("AmbiguousField"),
   637  		makeInput: func() any {
   638  			type (
   639  				S1 struct{ x, X int }
   640  				S2 struct{ x, X int }
   641  				S  struct {
   642  					S1
   643  					S2
   644  				}
   645  			)
   646  			return S{S1{1, 2}, S2{3, 4}}
   647  		},
   648  		want: `{}`,
   649  	}, {
   650  		CaseName: Name("DominantField"),
   651  		// Both S1 and S2 have a field named X, but since S has an X field as
   652  		// well, it takes precedence over S1.X and S2.X.
   653  		makeInput: func() any {
   654  			type (
   655  				S1 struct{ x, X int }
   656  				S2 struct{ x, X int }
   657  				S  struct {
   658  					S1
   659  					S2
   660  					x, X int
   661  				}
   662  			)
   663  			return S{S1{1, 2}, S2{3, 4}, 5, 6}
   664  		},
   665  		want: `{"X":6}`,
   666  	}, {
   667  		// Unexported embedded field of non-struct type should not be serialized.
   668  		CaseName: Name("UnexportedEmbeddedInt"),
   669  		makeInput: func() any {
   670  			type (
   671  				myInt int
   672  				S     struct{ myInt }
   673  			)
   674  			return S{5}
   675  		},
   676  		want: `{}`,
   677  	}, {
   678  		// Exported embedded field of non-struct type should be serialized.
   679  		CaseName: Name("ExportedEmbeddedInt"),
   680  		makeInput: func() any {
   681  			type (
   682  				MyInt int
   683  				S     struct{ MyInt }
   684  			)
   685  			return S{5}
   686  		},
   687  		want: `{"MyInt":5}`,
   688  	}, {
   689  		// Unexported embedded field of pointer to non-struct type
   690  		// should not be serialized.
   691  		CaseName: Name("UnexportedEmbeddedIntPointer"),
   692  		makeInput: func() any {
   693  			type (
   694  				myInt int
   695  				S     struct{ *myInt }
   696  			)
   697  			s := S{new(myInt)}
   698  			*s.myInt = 5
   699  			return s
   700  		},
   701  		want: `{}`,
   702  	}, {
   703  		// Exported embedded field of pointer to non-struct type
   704  		// should be serialized.
   705  		CaseName: Name("ExportedEmbeddedIntPointer"),
   706  		makeInput: func() any {
   707  			type (
   708  				MyInt int
   709  				S     struct{ *MyInt }
   710  			)
   711  			s := S{new(MyInt)}
   712  			*s.MyInt = 5
   713  			return s
   714  		},
   715  		want: `{"MyInt":5}`,
   716  	}, {
   717  		// Exported fields of embedded structs should have their
   718  		// exported fields be serialized regardless of whether the struct types
   719  		// themselves are exported.
   720  		CaseName: Name("EmbeddedStruct"),
   721  		makeInput: func() any {
   722  			type (
   723  				s1 struct{ x, X int }
   724  				S2 struct{ y, Y int }
   725  				S  struct {
   726  					s1
   727  					S2
   728  				}
   729  			)
   730  			return S{s1{1, 2}, S2{3, 4}}
   731  		},
   732  		want: `{"X":2,"Y":4}`,
   733  	}, {
   734  		// Exported fields of pointers to embedded structs should have their
   735  		// exported fields be serialized regardless of whether the struct types
   736  		// themselves are exported.
   737  		CaseName: Name("EmbeddedStructPointer"),
   738  		makeInput: func() any {
   739  			type (
   740  				s1 struct{ x, X int }
   741  				S2 struct{ y, Y int }
   742  				S  struct {
   743  					*s1
   744  					*S2
   745  				}
   746  			)
   747  			return S{&s1{1, 2}, &S2{3, 4}}
   748  		},
   749  		want: `{"X":2,"Y":4}`,
   750  	}, {
   751  		// Exported fields on embedded unexported structs at multiple levels
   752  		// of nesting should still be serialized.
   753  		CaseName: Name("NestedStructAndInts"),
   754  		makeInput: func() any {
   755  			type (
   756  				MyInt1 int
   757  				MyInt2 int
   758  				myInt  int
   759  				s2     struct {
   760  					MyInt2
   761  					myInt
   762  				}
   763  				s1 struct {
   764  					MyInt1
   765  					myInt
   766  					s2
   767  				}
   768  				S struct {
   769  					s1
   770  					myInt
   771  				}
   772  			)
   773  			return S{s1{1, 2, s2{3, 4}}, 6}
   774  		},
   775  		want: `{"MyInt1":1,"MyInt2":3}`,
   776  	}, {
   777  		// If an anonymous struct pointer field is nil, we should ignore
   778  		// the embedded fields behind it. Not properly doing so may
   779  		// result in the wrong output or reflect panics.
   780  		CaseName: Name("EmbeddedFieldBehindNilPointer"),
   781  		makeInput: func() any {
   782  			type (
   783  				S2 struct{ Field string }
   784  				S  struct{ *S2 }
   785  			)
   786  			return S{}
   787  		},
   788  		want: `{}`,
   789  	}}
   790  
   791  	for _, tt := range tests {
   792  		t.Run(tt.Name, func(t *testing.T) {
   793  			b, err := Marshal(tt.makeInput())
   794  			if err != nil {
   795  				t.Fatalf("%s: Marshal error: %v", tt.Where, err)
   796  			}
   797  			if string(b) != tt.want {
   798  				t.Fatalf("%s: Marshal:\n\tgot:  %s\n\twant: %s", tt.Where, b, tt.want)
   799  			}
   800  		})
   801  	}
   802  }
   803  
   804  type BugA struct {
   805  	S string
   806  }
   807  
   808  type BugB struct {
   809  	BugA
   810  	S string
   811  }
   812  
   813  type BugC struct {
   814  	S string
   815  }
   816  
   817  // Legal Go: We never use the repeated embedded field (S).
   818  type BugX struct {
   819  	A int
   820  	BugA
   821  	BugB
   822  }
   823  
   824  // golang.org/issue/16042.
   825  // Even if a nil interface value is passed in, as long as
   826  // it implements Marshaler, it should be marshaled.
   827  type nilJSONMarshaler string
   828  
   829  func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) {
   830  	if nm == nil {
   831  		return Marshal("0zenil0")
   832  	}
   833  	return Marshal("zenil:" + string(*nm))
   834  }
   835  
   836  // golang.org/issue/34235.
   837  // Even if a nil interface value is passed in, as long as
   838  // it implements encoding.TextMarshaler, it should be marshaled.
   839  type nilTextMarshaler string
   840  
   841  func (nm *nilTextMarshaler) MarshalText() ([]byte, error) {
   842  	if nm == nil {
   843  		return []byte("0zenil0"), nil
   844  	}
   845  	return []byte("zenil:" + string(*nm)), nil
   846  }
   847  
   848  // See golang.org/issue/16042 and golang.org/issue/34235.
   849  func TestNilMarshal(t *testing.T) {
   850  	tests := []struct {
   851  		CaseName
   852  		in   any
   853  		want string
   854  	}{
   855  		{Name(""), nil, `null`},
   856  		{Name(""), new(float64), `0`},
   857  		{Name(""), []any(nil), `null`},
   858  		{Name(""), []string(nil), `null`},
   859  		{Name(""), map[string]string(nil), `null`},
   860  		{Name(""), []byte(nil), `null`},
   861  		{Name(""), struct{ M string }{"gopher"}, `{"M":"gopher"}`},
   862  		{Name(""), struct{ M Marshaler }{}, `{"M":null}`},
   863  		{Name(""), struct{ M Marshaler }{(*nilJSONMarshaler)(nil)}, `{"M":"0zenil0"}`},
   864  		{Name(""), struct{ M any }{(*nilJSONMarshaler)(nil)}, `{"M":null}`},
   865  		{Name(""), struct{ M encoding.TextMarshaler }{}, `{"M":null}`},
   866  		{Name(""), struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, `{"M":"0zenil0"}`},
   867  		{Name(""), struct{ M any }{(*nilTextMarshaler)(nil)}, `{"M":null}`},
   868  	}
   869  	for _, tt := range tests {
   870  		t.Run(tt.Name, func(t *testing.T) {
   871  			switch got, err := Marshal(tt.in); {
   872  			case err != nil:
   873  				t.Fatalf("%s: Marshal error: %v", tt.Where, err)
   874  			case string(got) != tt.want:
   875  				t.Fatalf("%s: Marshal:\n\tgot:  %s\n\twant: %s", tt.Where, got, tt.want)
   876  			}
   877  		})
   878  	}
   879  }
   880  
   881  // Issue 5245.
   882  func TestEmbeddedBug(t *testing.T) {
   883  	v := BugB{
   884  		BugA{"A"},
   885  		"B",
   886  	}
   887  	b, err := Marshal(v)
   888  	if err != nil {
   889  		t.Fatal("Marshal error:", err)
   890  	}
   891  	want := `{"S":"B"}`
   892  	got := string(b)
   893  	if got != want {
   894  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   895  	}
   896  	// Now check that the duplicate field, S, does not appear.
   897  	x := BugX{
   898  		A: 23,
   899  	}
   900  	b, err = Marshal(x)
   901  	if err != nil {
   902  		t.Fatal("Marshal error:", err)
   903  	}
   904  	want = `{"A":23}`
   905  	got = string(b)
   906  	if got != want {
   907  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   908  	}
   909  }
   910  
   911  type BugD struct { // Same as BugA after tagging.
   912  	XXX string `json:"S"`
   913  }
   914  
   915  // BugD's tagged S field should dominate BugA's.
   916  type BugY struct {
   917  	BugA
   918  	BugD
   919  }
   920  
   921  // Test that a field with a tag dominates untagged fields.
   922  func TestTaggedFieldDominates(t *testing.T) {
   923  	v := BugY{
   924  		BugA{"BugA"},
   925  		BugD{"BugD"},
   926  	}
   927  	b, err := Marshal(v)
   928  	if err != nil {
   929  		t.Fatal("Marshal error:", err)
   930  	}
   931  	want := `{"S":"BugD"}`
   932  	got := string(b)
   933  	if got != want {
   934  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   935  	}
   936  }
   937  
   938  // There are no tags here, so S should not appear.
   939  type BugZ struct {
   940  	BugA
   941  	BugC
   942  	BugY // Contains a tagged S field through BugD; should not dominate.
   943  }
   944  
   945  func TestDuplicatedFieldDisappears(t *testing.T) {
   946  	v := BugZ{
   947  		BugA{"BugA"},
   948  		BugC{"BugC"},
   949  		BugY{
   950  			BugA{"nested BugA"},
   951  			BugD{"nested BugD"},
   952  		},
   953  	}
   954  	b, err := Marshal(v)
   955  	if err != nil {
   956  		t.Fatal("Marshal error:", err)
   957  	}
   958  	want := `{}`
   959  	got := string(b)
   960  	if got != want {
   961  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
   962  	}
   963  }
   964  
   965  func TestIssue10281(t *testing.T) {
   966  	type Foo struct {
   967  		N Number
   968  	}
   969  	x := Foo{Number(`invalid`)}
   970  
   971  	if _, err := Marshal(&x); err == nil {
   972  		t.Fatalf("Marshal error: got nil, want non-nil")
   973  	}
   974  }
   975  
   976  func TestMarshalErrorAndReuseEncodeState(t *testing.T) {
   977  	// Disable the GC temporarily to prevent encodeState's in Pool being cleaned away during the test.
   978  	percent := debug.SetGCPercent(-1)
   979  	defer debug.SetGCPercent(percent)
   980  
   981  	// Trigger an error in Marshal with cyclic data.
   982  	type Dummy struct {
   983  		Name string
   984  		Next *Dummy
   985  	}
   986  	dummy := Dummy{Name: "Dummy"}
   987  	dummy.Next = &dummy
   988  	if _, err := Marshal(dummy); err == nil {
   989  		t.Errorf("Marshal error: got nil, want non-nil")
   990  	}
   991  
   992  	type Data struct {
   993  		A string
   994  		I int
   995  	}
   996  	want := Data{A: "a", I: 1}
   997  	b, err := Marshal(want)
   998  	if err != nil {
   999  		t.Errorf("Marshal error: %v", err)
  1000  	}
  1001  
  1002  	var got Data
  1003  	if err := Unmarshal(b, &got); err != nil {
  1004  		t.Errorf("Unmarshal error: %v", err)
  1005  	}
  1006  	if got != want {
  1007  		t.Errorf("Unmarshal:\n\tgot:  %v\n\twant: %v", got, want)
  1008  	}
  1009  }
  1010  
  1011  func TestHTMLEscape(t *testing.T) {
  1012  	var b, want bytes.Buffer
  1013  	m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}`
  1014  	want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`))
  1015  	HTMLEscape(&b, []byte(m))
  1016  	if !bytes.Equal(b.Bytes(), want.Bytes()) {
  1017  		t.Errorf("HTMLEscape:\n\tgot:  %s\n\twant: %s", b.Bytes(), want.Bytes())
  1018  	}
  1019  }
  1020  
  1021  // golang.org/issue/8582
  1022  func TestEncodePointerString(t *testing.T) {
  1023  	type stringPointer struct {
  1024  		N *int64 `json:"n,string"`
  1025  	}
  1026  	var n int64 = 42
  1027  	b, err := Marshal(stringPointer{N: &n})
  1028  	if err != nil {
  1029  		t.Fatalf("Marshal error: %v", err)
  1030  	}
  1031  	if got, want := string(b), `{"n":"42"}`; got != want {
  1032  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
  1033  	}
  1034  	var back stringPointer
  1035  	switch err = Unmarshal(b, &back); {
  1036  	case err != nil:
  1037  		t.Fatalf("Unmarshal error: %v", err)
  1038  	case back.N == nil:
  1039  		t.Fatalf("Unmarshal: back.N = nil, want non-nil")
  1040  	case *back.N != 42:
  1041  		t.Fatalf("Unmarshal: *back.N = %d, want 42", *back.N)
  1042  	}
  1043  }
  1044  
  1045  var encodeStringTests = []struct {
  1046  	in  string
  1047  	out string
  1048  }{
  1049  	{"\x00", `"\u0000"`},
  1050  	{"\x01", `"\u0001"`},
  1051  	{"\x02", `"\u0002"`},
  1052  	{"\x03", `"\u0003"`},
  1053  	{"\x04", `"\u0004"`},
  1054  	{"\x05", `"\u0005"`},
  1055  	{"\x06", `"\u0006"`},
  1056  	{"\x07", `"\u0007"`},
  1057  	{"\x08", `"\b"`},
  1058  	{"\x09", `"\t"`},
  1059  	{"\x0a", `"\n"`},
  1060  	{"\x0b", `"\u000b"`},
  1061  	{"\x0c", `"\f"`},
  1062  	{"\x0d", `"\r"`},
  1063  	{"\x0e", `"\u000e"`},
  1064  	{"\x0f", `"\u000f"`},
  1065  	{"\x10", `"\u0010"`},
  1066  	{"\x11", `"\u0011"`},
  1067  	{"\x12", `"\u0012"`},
  1068  	{"\x13", `"\u0013"`},
  1069  	{"\x14", `"\u0014"`},
  1070  	{"\x15", `"\u0015"`},
  1071  	{"\x16", `"\u0016"`},
  1072  	{"\x17", `"\u0017"`},
  1073  	{"\x18", `"\u0018"`},
  1074  	{"\x19", `"\u0019"`},
  1075  	{"\x1a", `"\u001a"`},
  1076  	{"\x1b", `"\u001b"`},
  1077  	{"\x1c", `"\u001c"`},
  1078  	{"\x1d", `"\u001d"`},
  1079  	{"\x1e", `"\u001e"`},
  1080  	{"\x1f", `"\u001f"`},
  1081  }
  1082  
  1083  func TestEncodeString(t *testing.T) {
  1084  	for _, tt := range encodeStringTests {
  1085  		b, err := Marshal(tt.in)
  1086  		if err != nil {
  1087  			t.Errorf("Marshal(%q) error: %v", tt.in, err)
  1088  			continue
  1089  		}
  1090  		out := string(b)
  1091  		if out != tt.out {
  1092  			t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out)
  1093  		}
  1094  	}
  1095  }
  1096  
  1097  type jsonbyte byte
  1098  
  1099  func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) }
  1100  
  1101  type textbyte byte
  1102  
  1103  func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) }
  1104  
  1105  type jsonint int
  1106  
  1107  func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) }
  1108  
  1109  type textint int
  1110  
  1111  func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
  1112  
  1113  func tenc(format string, a ...any) ([]byte, error) {
  1114  	var buf bytes.Buffer
  1115  	fmt.Fprintf(&buf, format, a...)
  1116  	return buf.Bytes(), nil
  1117  }
  1118  
  1119  type textfloat float64
  1120  
  1121  func (f textfloat) MarshalText() ([]byte, error) { return tenc(`TF:%0.2f`, f) }
  1122  
  1123  // Issue 13783
  1124  func TestEncodeBytekind(t *testing.T) {
  1125  	tests := []struct {
  1126  		CaseName
  1127  		in   any
  1128  		want string
  1129  	}{
  1130  		{Name(""), byte(7), "7"},
  1131  		{Name(""), jsonbyte(7), `{"JB":7}`},
  1132  		{Name(""), textbyte(4), `"TB:4"`},
  1133  		{Name(""), jsonint(5), `{"JI":5}`},
  1134  		{Name(""), textint(1), `"TI:1"`},
  1135  		{Name(""), []byte{0, 1}, `"AAE="`},
  1136  		{Name(""), []jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`},
  1137  		{Name(""), [][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`},
  1138  		{Name(""), []textbyte{2, 3}, `["TB:2","TB:3"]`},
  1139  		{Name(""), []jsonint{5, 4}, `[{"JI":5},{"JI":4}]`},
  1140  		{Name(""), []textint{9, 3}, `["TI:9","TI:3"]`},
  1141  		{Name(""), []int{9, 3}, `[9,3]`},
  1142  		{Name(""), []textfloat{12, 3}, `["TF:12.00","TF:3.00"]`},
  1143  	}
  1144  	for _, tt := range tests {
  1145  		t.Run(tt.Name, func(t *testing.T) {
  1146  			b, err := Marshal(tt.in)
  1147  			if err != nil {
  1148  				t.Errorf("%s: Marshal error: %v", tt.Where, err)
  1149  			}
  1150  			got, want := string(b), tt.want
  1151  			if got != want {
  1152  				t.Errorf("%s: Marshal:\n\tgot:  %s\n\twant: %s", tt.Where, got, want)
  1153  			}
  1154  		})
  1155  	}
  1156  }
  1157  
  1158  func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
  1159  	got, err := Marshal(map[unmarshalerText]int{
  1160  		{"x", "y"}: 1,
  1161  		{"y", "x"}: 2,
  1162  		{"a", "z"}: 3,
  1163  		{"z", "a"}: 4,
  1164  	})
  1165  	if err != nil {
  1166  		t.Fatalf("Marshal error: %v", err)
  1167  	}
  1168  	const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}`
  1169  	if string(got) != want {
  1170  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
  1171  	}
  1172  }
  1173  
  1174  // https://golang.org/issue/33675
  1175  func TestNilMarshalerTextMapKey(t *testing.T) {
  1176  	got, err := Marshal(map[*unmarshalerText]int{
  1177  		(*unmarshalerText)(nil): 1,
  1178  		{"A", "B"}:              2,
  1179  	})
  1180  	if err != nil {
  1181  		t.Fatalf("Marshal error: %v", err)
  1182  	}
  1183  	const want = `{"":1,"A:B":2}`
  1184  	if string(got) != want {
  1185  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
  1186  	}
  1187  }
  1188  
  1189  // textMarshalerString is a string kind that implements encoding.TextMarshaler.
  1190  type textMarshalerString string
  1191  
  1192  func (s textMarshalerString) MarshalText() ([]byte, error) {
  1193  	return []byte("X_" + string(s)), nil
  1194  }
  1195  
  1196  func (s textMarshalerString) AppendText(b []byte) ([]byte, error) {
  1197  	return append(b, ("X_" + string(s))...), nil
  1198  }
  1199  
  1200  // Issue 81355: string-kind map keys are used directly even if the key type
  1201  // implements encoding.TextMarshaler. MarshalText is still called for values.
  1202  func TestStringKindTextMarshalerMapKey(t *testing.T) {
  1203  	got, err := Marshal(map[textMarshalerString]textMarshalerString{"foo": "bar"})
  1204  	if err != nil {
  1205  		t.Fatalf("Marshal error: %v", err)
  1206  	}
  1207  	const want = `{"foo":"X_bar"}`
  1208  	if string(got) != want {
  1209  		t.Errorf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
  1210  	}
  1211  }
  1212  
  1213  var re = regexp.MustCompile
  1214  
  1215  // syntactic checks on form of marshaled floating point numbers.
  1216  var badFloatREs = []*regexp.Regexp{
  1217  	re(`p`),                     // no binary exponential notation
  1218  	re(`^\+`),                   // no leading + sign
  1219  	re(`^-?0[^.]`),              // no unnecessary leading zeros
  1220  	re(`^-?\.`),                 // leading zero required before decimal point
  1221  	re(`\.(e|$)`),               // no trailing decimal
  1222  	re(`\.[0-9]+0(e|$)`),        // no trailing zero in fraction
  1223  	re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa
  1224  	re(`e[0-9]`),                // positive exponent must be signed
  1225  	re(`e[+-]0`),                // exponent must not have leading zeros
  1226  	re(`e-[1-6]$`),              // not tiny enough for exponential notation
  1227  	re(`e+(.|1.|20)$`),          // not big enough for exponential notation
  1228  	re(`^-?0\.0000000`),         // too tiny, should use exponential notation
  1229  	re(`^-?[0-9]{22}`),          // too big, should use exponential notation
  1230  	re(`[1-9][0-9]{16}[1-9]`),   // too many significant digits in integer
  1231  	re(`[1-9][0-9.]{17}[1-9]`),  // too many significant digits in decimal
  1232  	// below here for float32 only
  1233  	re(`[1-9][0-9]{8}[1-9]`),  // too many significant digits in integer
  1234  	re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal
  1235  }
  1236  
  1237  func TestMarshalFloat(t *testing.T) {
  1238  	t.Parallel()
  1239  	nfail := 0
  1240  	test := func(f float64, bits int) {
  1241  		vf := any(f)
  1242  		if bits == 32 {
  1243  			f = float64(float32(f)) // round
  1244  			vf = float32(f)
  1245  		}
  1246  		bout, err := Marshal(vf)
  1247  		if err != nil {
  1248  			t.Errorf("Marshal(%T(%g)) error: %v", vf, vf, err)
  1249  			nfail++
  1250  			return
  1251  		}
  1252  		out := string(bout)
  1253  
  1254  		// result must convert back to the same float
  1255  		g, err := strconv.ParseFloat(out, bits)
  1256  		if err != nil {
  1257  			t.Errorf("ParseFloat(%q) error: %v", out, err)
  1258  			nfail++
  1259  			return
  1260  		}
  1261  		if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0
  1262  			t.Errorf("ParseFloat(%q):\n\tgot:  %g\n\twant: %g", out, float32(g), vf)
  1263  			nfail++
  1264  			return
  1265  		}
  1266  
  1267  		bad := badFloatREs
  1268  		if bits == 64 {
  1269  			bad = bad[:len(bad)-2]
  1270  		}
  1271  		for _, re := range bad {
  1272  			if re.MatchString(out) {
  1273  				t.Errorf("Marshal(%T(%g)) = %q; must not match /%s/", vf, vf, out, re)
  1274  				nfail++
  1275  				return
  1276  			}
  1277  		}
  1278  	}
  1279  
  1280  	var (
  1281  		bigger  = math.Inf(+1)
  1282  		smaller = math.Inf(-1)
  1283  	)
  1284  
  1285  	var digits = "1.2345678901234567890123"
  1286  	for i := len(digits); i >= 2; i-- {
  1287  		if testing.Short() && i < len(digits)-4 {
  1288  			break
  1289  		}
  1290  		for exp := -30; exp <= 30; exp++ {
  1291  			for _, sign := range "+-" {
  1292  				for bits := 32; bits <= 64; bits += 32 {
  1293  					s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp)
  1294  					f, err := strconv.ParseFloat(s, bits)
  1295  					if err != nil {
  1296  						log.Fatal(err)
  1297  					}
  1298  					next := math.Nextafter
  1299  					if bits == 32 {
  1300  						next = func(g, h float64) float64 {
  1301  							return float64(math.Nextafter32(float32(g), float32(h)))
  1302  						}
  1303  					}
  1304  					test(f, bits)
  1305  					test(next(f, bigger), bits)
  1306  					test(next(f, smaller), bits)
  1307  					if nfail > 50 {
  1308  						t.Fatalf("stopping test early")
  1309  					}
  1310  				}
  1311  			}
  1312  		}
  1313  	}
  1314  	test(0, 64)
  1315  	test(math.Copysign(0, -1), 64)
  1316  	test(0, 32)
  1317  	test(math.Copysign(0, -1), 32)
  1318  }
  1319  
  1320  func TestMarshalRawMessageValue(t *testing.T) {
  1321  	type (
  1322  		T1 struct {
  1323  			M RawMessage `json:",omitempty"`
  1324  		}
  1325  		T2 struct {
  1326  			M *RawMessage `json:",omitempty"`
  1327  		}
  1328  	)
  1329  
  1330  	var (
  1331  		rawNil   = RawMessage(nil)
  1332  		rawEmpty = RawMessage([]byte{})
  1333  		rawText  = RawMessage([]byte(`"foo"`))
  1334  	)
  1335  
  1336  	tests := []struct {
  1337  		CaseName
  1338  		in   any
  1339  		want string
  1340  		ok   bool
  1341  	}{
  1342  		// Test with nil RawMessage.
  1343  		{Name(""), rawNil, "null", true},
  1344  		{Name(""), &rawNil, "null", true},
  1345  		{Name(""), []any{rawNil}, "[null]", true},
  1346  		{Name(""), &[]any{rawNil}, "[null]", true},
  1347  		{Name(""), []any{&rawNil}, "[null]", true},
  1348  		{Name(""), &[]any{&rawNil}, "[null]", true},
  1349  		{Name(""), struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
  1350  		{Name(""), &struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
  1351  		{Name(""), struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
  1352  		{Name(""), &struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
  1353  		{Name(""), map[string]any{"M": rawNil}, `{"M":null}`, true},
  1354  		{Name(""), &map[string]any{"M": rawNil}, `{"M":null}`, true},
  1355  		{Name(""), map[string]any{"M": &rawNil}, `{"M":null}`, true},
  1356  		{Name(""), &map[string]any{"M": &rawNil}, `{"M":null}`, true},
  1357  		{Name(""), T1{rawNil}, "{}", true},
  1358  		{Name(""), T2{&rawNil}, `{"M":null}`, true},
  1359  		{Name(""), &T1{rawNil}, "{}", true},
  1360  		{Name(""), &T2{&rawNil}, `{"M":null}`, true},
  1361  
  1362  		// Test with empty, but non-nil, RawMessage.
  1363  		{Name(""), rawEmpty, "", false},
  1364  		{Name(""), &rawEmpty, "", false},
  1365  		{Name(""), []any{rawEmpty}, "", false},
  1366  		{Name(""), &[]any{rawEmpty}, "", false},
  1367  		{Name(""), []any{&rawEmpty}, "", false},
  1368  		{Name(""), &[]any{&rawEmpty}, "", false},
  1369  		{Name(""), struct{ X RawMessage }{rawEmpty}, "", false},
  1370  		{Name(""), &struct{ X RawMessage }{rawEmpty}, "", false},
  1371  		{Name(""), struct{ X *RawMessage }{&rawEmpty}, "", false},
  1372  		{Name(""), &struct{ X *RawMessage }{&rawEmpty}, "", false},
  1373  		{Name(""), map[string]any{"nil": rawEmpty}, "", false},
  1374  		{Name(""), &map[string]any{"nil": rawEmpty}, "", false},
  1375  		{Name(""), map[string]any{"nil": &rawEmpty}, "", false},
  1376  		{Name(""), &map[string]any{"nil": &rawEmpty}, "", false},
  1377  		{Name(""), T1{rawEmpty}, "{}", true},
  1378  		{Name(""), T2{&rawEmpty}, "", false},
  1379  		{Name(""), &T1{rawEmpty}, "{}", true},
  1380  		{Name(""), &T2{&rawEmpty}, "", false},
  1381  
  1382  		// Test with RawMessage with some text.
  1383  		//
  1384  		// The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo".
  1385  		// This behavior was intentionally changed in Go 1.8.
  1386  		// See https://golang.org/issues/14493#issuecomment-255857318
  1387  		{Name(""), rawText, `"foo"`, true}, // Issue6458
  1388  		{Name(""), &rawText, `"foo"`, true},
  1389  		{Name(""), []any{rawText}, `["foo"]`, true},  // Issue6458
  1390  		{Name(""), &[]any{rawText}, `["foo"]`, true}, // Issue6458
  1391  		{Name(""), []any{&rawText}, `["foo"]`, true},
  1392  		{Name(""), &[]any{&rawText}, `["foo"]`, true},
  1393  		{Name(""), struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
  1394  		{Name(""), &struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true},
  1395  		{Name(""), struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
  1396  		{Name(""), &struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
  1397  		{Name(""), map[string]any{"M": rawText}, `{"M":"foo"}`, true},  // Issue6458
  1398  		{Name(""), &map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
  1399  		{Name(""), map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
  1400  		{Name(""), &map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
  1401  		{Name(""), T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
  1402  		{Name(""), T2{&rawText}, `{"M":"foo"}`, true},
  1403  		{Name(""), &T1{rawText}, `{"M":"foo"}`, true},
  1404  		{Name(""), &T2{&rawText}, `{"M":"foo"}`, true},
  1405  	}
  1406  
  1407  	for _, tt := range tests {
  1408  		t.Run(tt.Name, func(t *testing.T) {
  1409  			b, err := Marshal(tt.in)
  1410  			if ok := (err == nil); ok != tt.ok {
  1411  				if err != nil {
  1412  					t.Errorf("%s: Marshal error: %v", tt.Where, err)
  1413  				} else {
  1414  					t.Errorf("%s: Marshal error: got nil, want non-nil", tt.Where)
  1415  				}
  1416  			}
  1417  			if got := string(b); got != tt.want {
  1418  				t.Errorf("%s: Marshal:\n\tinput: %#v\n\tgot:  %s\n\twant: %s", tt.Where, tt.in, got, tt.want)
  1419  			}
  1420  		})
  1421  	}
  1422  }
  1423  
  1424  type marshalPanic struct{}
  1425  
  1426  func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) }
  1427  
  1428  func TestMarshalPanic(t *testing.T) {
  1429  	defer func() {
  1430  		if got := recover(); !reflect.DeepEqual(got, 0xdead) {
  1431  			t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
  1432  		}
  1433  	}()
  1434  	Marshal(&marshalPanic{})
  1435  	t.Error("Marshal should have panicked")
  1436  }
  1437  
  1438  func TestMarshalUncommonFieldNames(t *testing.T) {
  1439  	v := struct {
  1440  		A0, À, Aβ int
  1441  	}{}
  1442  	b, err := Marshal(v)
  1443  	if err != nil {
  1444  		t.Fatal("Marshal error:", err)
  1445  	}
  1446  	want := `{"A0":0,"À":0,"Aβ":0}`
  1447  	got := string(b)
  1448  	if got != want {
  1449  		t.Fatalf("Marshal:\n\tgot:  %s\n\twant: %s", got, want)
  1450  	}
  1451  }
  1452  
  1453  func TestMarshalerError(t *testing.T) {
  1454  	s := "test variable"
  1455  	st := reflect.TypeOf(s)
  1456  	const errText = "json: test error"
  1457  
  1458  	tests := []struct {
  1459  		CaseName
  1460  		err  *MarshalerError
  1461  		want string
  1462  	}{{
  1463  		Name(""),
  1464  		&MarshalerError{st, fmt.Errorf(errText), ""},
  1465  		"json: error calling MarshalJSON for type " + st.String() + ": " + errText,
  1466  	}, {
  1467  		Name(""),
  1468  		&MarshalerError{st, fmt.Errorf(errText), "TestMarshalerError"},
  1469  		"json: error calling TestMarshalerError for type " + st.String() + ": " + errText,
  1470  	}}
  1471  
  1472  	for _, tt := range tests {
  1473  		t.Run(tt.Name, func(t *testing.T) {
  1474  			got := tt.err.Error()
  1475  			if got != tt.want {
  1476  				t.Errorf("%s: Error:\n\tgot:  %s\n\twant: %s", tt.Where, got, tt.want)
  1477  			}
  1478  		})
  1479  	}
  1480  }
  1481  
  1482  type marshaledValue string
  1483  
  1484  func (v marshaledValue) MarshalJSON() ([]byte, error) {
  1485  	return []byte(v), nil
  1486  }
  1487  
  1488  func TestIssue63379(t *testing.T) {
  1489  	for _, v := range []string{
  1490  		"[]<",
  1491  		"[]>",
  1492  		"[]&",
  1493  		"[]\u2028",
  1494  		"[]\u2029",
  1495  		"{}<",
  1496  		"{}>",
  1497  		"{}&",
  1498  		"{}\u2028",
  1499  		"{}\u2029",
  1500  	} {
  1501  		_, err := Marshal(marshaledValue(v))
  1502  		if err == nil {
  1503  			t.Errorf("expected error for %q", v)
  1504  		}
  1505  	}
  1506  }
  1507  
  1508  // Issue #73733: encoding/json used a WaitGroup to coordinate access to cache entries.
  1509  // Since WaitGroup.Wait is durably blocking, this caused apparent deadlocks when
  1510  // multiple bubbles called json.Marshal at the same time.
  1511  func TestSynctestMarshal(t *testing.T) {
  1512  	var wg sync.WaitGroup
  1513  	for range 5 {
  1514  		wg.Go(func() {
  1515  			synctest.Test(t, func(t *testing.T) {
  1516  				_, err := Marshal([]string{})
  1517  				if err != nil {
  1518  					t.Errorf("Marshal: %v", err)
  1519  				}
  1520  			})
  1521  		})
  1522  	}
  1523  	wg.Wait()
  1524  }
  1525  

View as plain text