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

View as plain text