github.com/3JoB/go-json@v0.10.4/decode_test.go (about)

     1  package json_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding"
     7  	stdjson "encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"image"
    11  	"math"
    12  	"math/big"
    13  	"net"
    14  	"strconv"
    15  	"strings"
    16  	"testing"
    17  	"time"
    18  	"unsafe"
    19  
    20  	"github.com/3JoB/go-reflect"
    21  
    22  	"github.com/3JoB/go-json"
    23  )
    24  
    25  func Test_Decoder(t *testing.T) {
    26  	t.Run("int", func(t *testing.T) {
    27  		var v int
    28  		assertErr(t, json.Unmarshal([]byte(`-1`), &v))
    29  		assertEq(t, "int", int(-1), v)
    30  	})
    31  	t.Run("int8", func(t *testing.T) {
    32  		var v int8
    33  		assertErr(t, json.Unmarshal([]byte(`-2`), &v))
    34  		assertEq(t, "int8", int8(-2), v)
    35  	})
    36  	t.Run("int16", func(t *testing.T) {
    37  		var v int16
    38  		assertErr(t, json.Unmarshal([]byte(`-3`), &v))
    39  		assertEq(t, "int16", int16(-3), v)
    40  	})
    41  	t.Run("int32", func(t *testing.T) {
    42  		var v int32
    43  		assertErr(t, json.Unmarshal([]byte(`-4`), &v))
    44  		assertEq(t, "int32", int32(-4), v)
    45  	})
    46  	t.Run("int64", func(t *testing.T) {
    47  		var v int64
    48  		assertErr(t, json.Unmarshal([]byte(`-5`), &v))
    49  		assertEq(t, "int64", int64(-5), v)
    50  	})
    51  	t.Run("uint", func(t *testing.T) {
    52  		var v uint
    53  		assertErr(t, json.Unmarshal([]byte(`1`), &v))
    54  		assertEq(t, "uint", uint(1), v)
    55  	})
    56  	t.Run("uint8", func(t *testing.T) {
    57  		var v uint8
    58  		assertErr(t, json.Unmarshal([]byte(`2`), &v))
    59  		assertEq(t, "uint8", uint8(2), v)
    60  	})
    61  	t.Run("uint16", func(t *testing.T) {
    62  		var v uint16
    63  		assertErr(t, json.Unmarshal([]byte(`3`), &v))
    64  		assertEq(t, "uint16", uint16(3), v)
    65  	})
    66  	t.Run("uint32", func(t *testing.T) {
    67  		var v uint32
    68  		assertErr(t, json.Unmarshal([]byte(`4`), &v))
    69  		assertEq(t, "uint32", uint32(4), v)
    70  	})
    71  	t.Run("uint64", func(t *testing.T) {
    72  		var v uint64
    73  		assertErr(t, json.Unmarshal([]byte(`5`), &v))
    74  		assertEq(t, "uint64", uint64(5), v)
    75  	})
    76  	t.Run("bool", func(t *testing.T) {
    77  		t.Run("true", func(t *testing.T) {
    78  			var v bool
    79  			assertErr(t, json.Unmarshal([]byte(`true`), &v))
    80  			assertEq(t, "bool", true, v)
    81  		})
    82  		t.Run("false", func(t *testing.T) {
    83  			v := true
    84  			assertErr(t, json.Unmarshal([]byte(`false`), &v))
    85  			assertEq(t, "bool", false, v)
    86  		})
    87  	})
    88  	t.Run("string", func(t *testing.T) {
    89  		var v string
    90  		assertErr(t, json.Unmarshal([]byte(`"hello"`), &v))
    91  		assertEq(t, "string", "hello", v)
    92  	})
    93  	t.Run("float32", func(t *testing.T) {
    94  		var v float32
    95  		assertErr(t, json.Unmarshal([]byte(`3.14`), &v))
    96  		assertEq(t, "float32", float32(3.14), v)
    97  	})
    98  	t.Run("float64", func(t *testing.T) {
    99  		var v float64
   100  		assertErr(t, json.Unmarshal([]byte(`3.14`), &v))
   101  		assertEq(t, "float64", float64(3.14), v)
   102  	})
   103  	t.Run("slice", func(t *testing.T) {
   104  		var v []int
   105  		assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v))
   106  		assertEq(t, "slice", fmt.Sprint([]int{1, 2, 3, 4}), fmt.Sprint(v))
   107  	})
   108  	t.Run("slice_reuse_data", func(t *testing.T) {
   109  		v := make([]int, 0, 10)
   110  		assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v))
   111  		assertEq(t, "slice", fmt.Sprint([]int{1, 2, 3, 4}), fmt.Sprint(v))
   112  		assertEq(t, "cap", 10, cap(v))
   113  	})
   114  	t.Run("array", func(t *testing.T) {
   115  		var v [4]int
   116  		assertErr(t, json.Unmarshal([]byte(` [ 1 , 2 , 3 , 4 ] `), &v))
   117  		assertEq(t, "array", fmt.Sprint([4]int{1, 2, 3, 4}), fmt.Sprint(v))
   118  	})
   119  	t.Run("map", func(t *testing.T) {
   120  		var v map[string]int
   121  		assertErr(t, json.Unmarshal([]byte(` { "a": 1, "b": 2, "c": 3, "d": 4 } `), &v))
   122  		assertEq(t, "map.a", v["a"], 1)
   123  		assertEq(t, "map.b", v["b"], 2)
   124  		assertEq(t, "map.c", v["c"], 3)
   125  		assertEq(t, "map.d", v["d"], 4)
   126  		t.Run("nested map", func(t *testing.T) {
   127  			// https://github.com/3JoB/go-json/issues/8
   128  			content := `
   129  {
   130    "a": {
   131      "nestedA": "value of nested a"
   132    },
   133    "b": {
   134      "nestedB": "value of nested b"
   135    },
   136    "c": {
   137      "nestedC": "value of nested c"
   138    }
   139  }`
   140  			var v map[string]any
   141  			assertErr(t, json.Unmarshal([]byte(content), &v))
   142  			assertEq(t, "length", 3, len(v))
   143  		})
   144  	})
   145  	t.Run("struct", func(t *testing.T) {
   146  		type T struct {
   147  			AA int    `json:"aa"`
   148  			BB string `json:"bb"`
   149  			CC bool   `json:"cc"`
   150  		}
   151  		var v struct {
   152  			A int    `json:"abcd"`
   153  			B string `json:"str"`
   154  			C bool
   155  			D *T
   156  			E func()
   157  		}
   158  		content := []byte(`
   159  {
   160    "abcd": 123,
   161    "str" : "hello",
   162    "c"   : true,
   163    "d"   : {
   164      "aa": 2,
   165      "bb": "world",
   166      "cc": true
   167    },
   168    "e"   : null
   169  }`)
   170  		assertErr(t, json.Unmarshal(content, &v))
   171  		assertEq(t, "struct.A", 123, v.A)
   172  		assertEq(t, "struct.B", "hello", v.B)
   173  		assertEq(t, "struct.C", true, v.C)
   174  		assertEq(t, "struct.D.AA", 2, v.D.AA)
   175  		assertEq(t, "struct.D.BB", "world", v.D.BB)
   176  		assertEq(t, "struct.D.CC", true, v.D.CC)
   177  		assertEq(t, "struct.E", true, v.E == nil)
   178  		t.Run("struct.field null", func(t *testing.T) {
   179  			var v struct {
   180  				A string
   181  				B []string
   182  				C []int
   183  				D map[string]any
   184  				E [2]string
   185  				F any
   186  				G func()
   187  			}
   188  			assertErr(t, json.Unmarshal([]byte(`{"a":null,"b":null,"c":null,"d":null,"e":null,"f":null,"g":null}`), &v))
   189  			assertEq(t, "string", v.A, "")
   190  			assertNeq(t, "[]string", v.B, nil)
   191  			assertEq(t, "[]string", len(v.B), 0)
   192  			assertNeq(t, "[]int", v.C, nil)
   193  			assertEq(t, "[]int", len(v.C), 0)
   194  			assertNeq(t, "map", v.D, nil)
   195  			assertEq(t, "map", len(v.D), 0)
   196  			assertNeq(t, "array", v.E, nil)
   197  			assertEq(t, "array", len(v.E), 2)
   198  			assertEq(t, "interface{}", v.F, nil)
   199  			assertEq(t, "nilfunc", true, v.G == nil)
   200  		})
   201  	})
   202  	t.Run("interface", func(t *testing.T) {
   203  		t.Run("number", func(t *testing.T) {
   204  			var v any
   205  			assertErr(t, json.Unmarshal([]byte(`10`), &v))
   206  			assertEq(t, "interface.kind", "float64", reflect.TypeOf(v).Kind().String())
   207  			assertEq(t, "interface", `10`, fmt.Sprint(v))
   208  		})
   209  		t.Run("string", func(t *testing.T) {
   210  			var v any
   211  			assertErr(t, json.Unmarshal([]byte(`"hello"`), &v))
   212  			assertEq(t, "interface.kind", "string", reflect.TypeOf(v).Kind().String())
   213  			assertEq(t, "interface", `hello`, fmt.Sprint(v))
   214  		})
   215  		t.Run("escaped string", func(t *testing.T) {
   216  			var v any
   217  			assertErr(t, json.Unmarshal([]byte(`"he\"llo"`), &v))
   218  			assertEq(t, "interface.kind", "string", reflect.TypeOf(v).Kind().String())
   219  			assertEq(t, "interface", `he"llo`, fmt.Sprint(v))
   220  		})
   221  		t.Run("bool", func(t *testing.T) {
   222  			var v any
   223  			assertErr(t, json.Unmarshal([]byte(`true`), &v))
   224  			assertEq(t, "interface.kind", "bool", reflect.TypeOf(v).Kind().String())
   225  			assertEq(t, "interface", `true`, fmt.Sprint(v))
   226  		})
   227  		t.Run("slice", func(t *testing.T) {
   228  			var v any
   229  			assertErr(t, json.Unmarshal([]byte(`[1,2,3,4]`), &v))
   230  			assertEq(t, "interface.kind", "slice", reflect.TypeOf(v).Kind().String())
   231  			assertEq(t, "interface", `[1 2 3 4]`, fmt.Sprint(v))
   232  		})
   233  		t.Run("map", func(t *testing.T) {
   234  			var v any
   235  			assertErr(t, json.Unmarshal([]byte(`{"a": 1, "b": "c"}`), &v))
   236  			assertEq(t, "interface.kind", "map", reflect.TypeOf(v).Kind().String())
   237  			m := v.(map[string]any)
   238  			assertEq(t, "interface", `1`, fmt.Sprint(m["a"]))
   239  			assertEq(t, "interface", `c`, fmt.Sprint(m["b"]))
   240  		})
   241  		t.Run("null", func(t *testing.T) {
   242  			var v any
   243  			v = 1
   244  			assertErr(t, json.Unmarshal([]byte(`null`), &v))
   245  			assertEq(t, "interface", nil, v)
   246  		})
   247  	})
   248  	t.Run("func", func(t *testing.T) {
   249  		var v func()
   250  		assertErr(t, json.Unmarshal([]byte(`null`), &v))
   251  		assertEq(t, "nilfunc", true, v == nil)
   252  	})
   253  }
   254  
   255  func TestIssue98(t *testing.T) {
   256  	data := "[\"\\"
   257  	var v any
   258  	if err := json.Unmarshal([]byte(data), &v); err == nil {
   259  		t.Fatal("expected error")
   260  	}
   261  }
   262  
   263  func Test_Decoder_UseNumber(t *testing.T) {
   264  	dec := json.NewDecoder(strings.NewReader(`{"a": 3.14}`))
   265  	dec.UseNumber()
   266  	var v map[string]any
   267  	assertErr(t, dec.Decode(&v))
   268  	assertEq(t, "json.Number", "json.Number", fmt.Sprintf("%T", v["a"]))
   269  }
   270  
   271  func Test_Decoder_DisallowUnknownFields(t *testing.T) {
   272  	dec := json.NewDecoder(strings.NewReader(`{"x": 1}`))
   273  	dec.DisallowUnknownFields()
   274  	var v struct {
   275  		x int
   276  	}
   277  	err := dec.Decode(&v)
   278  	if err == nil {
   279  		t.Fatal("expected unknown field error")
   280  	}
   281  	if err.Error() != `json: unknown field "x"` {
   282  		t.Fatal("expected unknown field error")
   283  	}
   284  }
   285  
   286  func Test_Decoder_EmptyObjectWithSpace(t *testing.T) {
   287  	dec := json.NewDecoder(strings.NewReader(`{"obj":{ }}`))
   288  	var v struct {
   289  		Obj map[string]int `json:"obj"`
   290  	}
   291  	assertErr(t, dec.Decode(&v))
   292  }
   293  
   294  type unmarshalJSON struct {
   295  	v int
   296  }
   297  
   298  func (u *unmarshalJSON) UnmarshalJSON(b []byte) error {
   299  	var v int
   300  	if err := json.Unmarshal(b, &v); err != nil {
   301  		return err
   302  	}
   303  	u.v = v
   304  	return nil
   305  }
   306  
   307  func Test_UnmarshalJSON(t *testing.T) {
   308  	t.Run("*struct", func(t *testing.T) {
   309  		var v unmarshalJSON
   310  		assertErr(t, json.Unmarshal([]byte(`10`), &v))
   311  		assertEq(t, "unmarshal", 10, v.v)
   312  	})
   313  }
   314  
   315  type unmarshalText struct {
   316  	v int
   317  }
   318  
   319  func (u *unmarshalText) UnmarshalText(b []byte) error {
   320  	var v int
   321  	if err := json.Unmarshal(b, &v); err != nil {
   322  		return err
   323  	}
   324  	u.v = v
   325  	return nil
   326  }
   327  
   328  func Test_UnmarshalText(t *testing.T) {
   329  	t.Run("*struct", func(t *testing.T) {
   330  		var v unmarshalText
   331  		assertErr(t, json.Unmarshal([]byte(`"11"`), &v))
   332  		assertEq(t, "unmarshal", v.v, 11)
   333  	})
   334  }
   335  
   336  func Test_InvalidUnmarshalError(t *testing.T) {
   337  	t.Run("nil", func(t *testing.T) {
   338  		var v *struct{}
   339  		err := fmt.Sprint(json.Unmarshal([]byte(`{}`), v))
   340  		assertEq(t, "invalid unmarshal error", "json: Unmarshal(nil *struct {})", err)
   341  	})
   342  	t.Run("non pointer", func(t *testing.T) {
   343  		var v int
   344  		err := fmt.Sprint(json.Unmarshal([]byte(`{}`), v))
   345  		assertEq(t, "invalid unmarshal error", "json: Unmarshal(non-pointer int)", err)
   346  	})
   347  }
   348  
   349  func Test_Token(t *testing.T) {
   350  	dec := json.NewDecoder(strings.NewReader(`{"a": 1, "b": true, "c": [1, "two", null]}`))
   351  	cnt := 0
   352  	for {
   353  		if _, err := dec.Token(); err != nil {
   354  			break
   355  		}
   356  		cnt++
   357  	}
   358  	if cnt != 12 {
   359  		t.Fatal("failed to parse token")
   360  	}
   361  }
   362  
   363  func Test_DecodeStream(t *testing.T) {
   364  	const stream = `
   365  	[
   366  		{"Name": "Ed", "Text": "Knock knock."},
   367  		{"Name": "Sam", "Text": "Who's there?"},
   368  		{"Name": "Ed", "Text": "Go fmt."},
   369  		{"Name": "Sam", "Text": "Go fmt who?"},
   370  		{"Name": "Ed", "Text": "Go fmt yourself!"}
   371  	]
   372  `
   373  	type Message struct {
   374  		Name, Text string
   375  	}
   376  	dec := json.NewDecoder(strings.NewReader(stream))
   377  
   378  	tk, err := dec.Token()
   379  	assertErr(t, err)
   380  	assertEq(t, "[", fmt.Sprint(tk), "[")
   381  
   382  	elem := 0
   383  	// while the array contains values
   384  	for dec.More() {
   385  		var m Message
   386  		// decode an array value (Message)
   387  		assertErr(t, dec.Decode(&m))
   388  		if m.Name == "" || m.Text == "" {
   389  			t.Fatal("failed to assign value to struct field")
   390  		}
   391  		elem++
   392  	}
   393  	assertEq(t, "decode count", elem, 5)
   394  
   395  	tk, err = dec.Token()
   396  	assertErr(t, err)
   397  	assertEq(t, "]", fmt.Sprint(tk), "]")
   398  }
   399  
   400  type T struct {
   401  	X string
   402  	Y int
   403  	Z int `json:"-"`
   404  }
   405  
   406  type U struct {
   407  	Alphabet string `json:"alpha"`
   408  }
   409  
   410  type V struct {
   411  	F1 any
   412  	F2 int32
   413  	F3 json.Number
   414  	F4 *VOuter
   415  }
   416  
   417  type VOuter struct {
   418  	V V
   419  }
   420  
   421  type W struct {
   422  	S SS
   423  }
   424  
   425  type P struct {
   426  	PP PP
   427  }
   428  
   429  type PP struct {
   430  	T  T
   431  	Ts []T
   432  }
   433  
   434  type SS string
   435  
   436  func (*SS) UnmarshalJSON(data []byte) error {
   437  	return &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(SS(""))}
   438  }
   439  
   440  // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and
   441  // without UseNumber
   442  var ifaceNumAsFloat64 = map[string]any{
   443  	"k1": float64(1),
   444  	"k2": "s",
   445  	"k3": []any{float64(1), float64(2.0), float64(3e-3)},
   446  	"k4": map[string]any{"kk1": "s", "kk2": float64(2)},
   447  }
   448  
   449  var ifaceNumAsNumber = map[string]any{
   450  	"k1": json.Number("1"),
   451  	"k2": "s",
   452  	"k3": []any{json.Number("1"), json.Number("2.0"), json.Number("3e-3")},
   453  	"k4": map[string]any{"kk1": "s", "kk2": json.Number("2")},
   454  }
   455  
   456  type tx struct {
   457  	x int
   458  }
   459  
   460  type u8 uint8
   461  
   462  // A type that can unmarshal itself.
   463  
   464  type unmarshaler struct {
   465  	T bool
   466  }
   467  
   468  func (u *unmarshaler) UnmarshalJSON(b []byte) error {
   469  	*u = unmarshaler{T: true} // All we need to see that UnmarshalJSON is called.
   470  	return nil
   471  }
   472  
   473  type ustruct struct {
   474  	M unmarshaler
   475  }
   476  
   477  var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil)
   478  
   479  type ustructText struct {
   480  	M unmarshalerText
   481  }
   482  
   483  // u8marshal is an integer type that can marshal/unmarshal itself.
   484  type u8marshal uint8
   485  
   486  func (u8 u8marshal) MarshalText() ([]byte, error) {
   487  	return []byte(fmt.Sprintf("u%d", u8)), nil
   488  }
   489  
   490  var errMissingU8Prefix = errors.New("missing 'u' prefix")
   491  
   492  func (u8 *u8marshal) UnmarshalText(b []byte) error {
   493  	if !bytes.HasPrefix(b, []byte{'u'}) {
   494  		return errMissingU8Prefix
   495  	}
   496  	n, err := strconv.Atoi(string(b[1:]))
   497  	if err != nil {
   498  		return err
   499  	}
   500  	*u8 = u8marshal(n)
   501  	return nil
   502  }
   503  
   504  var _ encoding.TextUnmarshaler = (*u8marshal)(nil)
   505  
   506  var (
   507  	umtrue   = unmarshaler{T: true}
   508  	umslice  = []unmarshaler{{T: true}}
   509  	umstruct = ustruct{M: unmarshaler{T: true}}
   510  
   511  	umtrueXY   = unmarshalerText{A: "x", B: "y"}
   512  	umsliceXY  = []unmarshalerText{{A: "x", B: "y"}}
   513  	umstructXY = ustructText{M: unmarshalerText{A: "x", B: "y"}}
   514  
   515  	ummapXY = map[unmarshalerText]bool{{A: "x", B: "y"}: true}
   516  )
   517  
   518  // Test data structures for anonymous fields.
   519  
   520  type Point struct {
   521  	Z int
   522  }
   523  
   524  type Top struct {
   525  	Level0 int
   526  	Embed0
   527  	*Embed0a
   528  	*Embed0b `json:"e,omitempty"` // treated as named
   529  	Embed0c  `json:"-"`           // ignored
   530  	Loop
   531  	Embed0p // has Point with X, Y, used
   532  	Embed0q // has Point with Z, used
   533  	embed   // contains exported field
   534  }
   535  
   536  type Embed0 struct {
   537  	Level1a int // overridden by Embed0a's Level1a with json tag
   538  	Level1b int // used because Embed0a's Level1b is renamed
   539  	Level1c int // used because Embed0a's Level1c is ignored
   540  	Level1d int // annihilated by Embed0a's Level1d
   541  	Level1e int `json:"x"` // annihilated by Embed0a.Level1e
   542  }
   543  
   544  type Embed0a struct {
   545  	Level1a int `json:"Level1a,omitempty"`
   546  	Level1b int `json:"LEVEL1B,omitempty"`
   547  	Level1c int `json:"-"`
   548  	Level1d int // annihilated by Embed0's Level1d
   549  	Level1f int `json:"x"` // annihilated by Embed0's Level1e
   550  }
   551  
   552  type Embed0b Embed0
   553  
   554  type Embed0c Embed0
   555  
   556  type Embed0p struct {
   557  	image.Point
   558  }
   559  
   560  type Embed0q struct {
   561  	Point
   562  }
   563  
   564  type embed struct {
   565  	Q int
   566  }
   567  
   568  type Loop struct {
   569  	Loop1 int `json:",omitempty"`
   570  	Loop2 int `json:",omitempty"`
   571  	*Loop
   572  }
   573  
   574  // From reflect test:
   575  // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
   576  type S5 struct {
   577  	S6
   578  	S7
   579  	S8
   580  }
   581  
   582  type S6 struct {
   583  	X int
   584  }
   585  
   586  type S7 S6
   587  
   588  type S8 struct {
   589  	S9
   590  }
   591  
   592  type S9 struct {
   593  	X int
   594  	Y int
   595  }
   596  
   597  // From reflect test:
   598  // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
   599  type S10 struct {
   600  	S11
   601  	S12
   602  	S13
   603  }
   604  
   605  type S11 struct {
   606  	S6
   607  }
   608  
   609  type S12 struct {
   610  	S6
   611  }
   612  
   613  type S13 struct {
   614  	S8
   615  }
   616  
   617  type Ambig struct {
   618  	// Given "hello", the first match should win.
   619  	First int `json:"HELLO"`
   620  
   621  	Second int `json:"Hello"`
   622  }
   623  
   624  type XYZ struct {
   625  	X any
   626  	Y any
   627  	Z any
   628  }
   629  
   630  type unexportedWithMethods struct{}
   631  
   632  func (unexportedWithMethods) F() {}
   633  
   634  type byteWithMarshalJSON byte
   635  
   636  func (b byteWithMarshalJSON) MarshalJSON() ([]byte, error) {
   637  	return []byte(fmt.Sprintf(`"Z%.2x"`, byte(b))), nil
   638  }
   639  
   640  func (b *byteWithMarshalJSON) UnmarshalJSON(data []byte) error {
   641  	if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
   642  		return errors.New("bad quoted string")
   643  	}
   644  	i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
   645  	if err != nil {
   646  		return errors.New("bad hex")
   647  	}
   648  	*b = byteWithMarshalJSON(i)
   649  	return nil
   650  }
   651  
   652  type byteWithPtrMarshalJSON byte
   653  
   654  func (b *byteWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
   655  	return byteWithMarshalJSON(*b).MarshalJSON()
   656  }
   657  
   658  func (b *byteWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
   659  	return (*byteWithMarshalJSON)(b).UnmarshalJSON(data)
   660  }
   661  
   662  type byteWithMarshalText byte
   663  
   664  func (b byteWithMarshalText) MarshalText() ([]byte, error) {
   665  	return []byte(fmt.Sprintf(`Z%.2x`, byte(b))), nil
   666  }
   667  
   668  func (b *byteWithMarshalText) UnmarshalText(data []byte) error {
   669  	if len(data) != 3 || data[0] != 'Z' {
   670  		return errors.New("bad quoted string")
   671  	}
   672  	i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
   673  	if err != nil {
   674  		return errors.New("bad hex")
   675  	}
   676  	*b = byteWithMarshalText(i)
   677  	return nil
   678  }
   679  
   680  type byteWithPtrMarshalText byte
   681  
   682  func (b *byteWithPtrMarshalText) MarshalText() ([]byte, error) {
   683  	return byteWithMarshalText(*b).MarshalText()
   684  }
   685  
   686  func (b *byteWithPtrMarshalText) UnmarshalText(data []byte) error {
   687  	return (*byteWithMarshalText)(b).UnmarshalText(data)
   688  }
   689  
   690  type intWithMarshalJSON int
   691  
   692  func (b intWithMarshalJSON) MarshalJSON() ([]byte, error) {
   693  	return []byte(fmt.Sprintf(`"Z%.2x"`, int(b))), nil
   694  }
   695  
   696  func (b *intWithMarshalJSON) UnmarshalJSON(data []byte) error {
   697  	if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
   698  		return errors.New("bad quoted string")
   699  	}
   700  	i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
   701  	if err != nil {
   702  		return errors.New("bad hex")
   703  	}
   704  	*b = intWithMarshalJSON(i)
   705  	return nil
   706  }
   707  
   708  type intWithPtrMarshalJSON int
   709  
   710  func (b *intWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
   711  	return intWithMarshalJSON(*b).MarshalJSON()
   712  }
   713  
   714  func (b *intWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
   715  	return (*intWithMarshalJSON)(b).UnmarshalJSON(data)
   716  }
   717  
   718  type intWithMarshalText int
   719  
   720  func (b intWithMarshalText) MarshalText() ([]byte, error) {
   721  	return []byte(fmt.Sprintf(`Z%.2x`, int(b))), nil
   722  }
   723  
   724  func (b *intWithMarshalText) UnmarshalText(data []byte) error {
   725  	if len(data) != 3 || data[0] != 'Z' {
   726  		return errors.New("bad quoted string")
   727  	}
   728  	i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
   729  	if err != nil {
   730  		return errors.New("bad hex")
   731  	}
   732  	*b = intWithMarshalText(i)
   733  	return nil
   734  }
   735  
   736  type intWithPtrMarshalText int
   737  
   738  func (b *intWithPtrMarshalText) MarshalText() ([]byte, error) {
   739  	return intWithMarshalText(*b).MarshalText()
   740  }
   741  
   742  func (b *intWithPtrMarshalText) UnmarshalText(data []byte) error {
   743  	return (*intWithMarshalText)(b).UnmarshalText(data)
   744  }
   745  
   746  type mapStringToStringData struct {
   747  	Data map[string]string `json:"data"`
   748  }
   749  
   750  type unmarshalTest struct {
   751  	in                    string
   752  	ptr                   any // new(type)
   753  	out                   any
   754  	err                   error
   755  	useNumber             bool
   756  	golden                bool
   757  	disallowUnknownFields bool
   758  }
   759  
   760  type B struct {
   761  	B bool `json:",string"`
   762  }
   763  
   764  type DoublePtr struct {
   765  	I **int
   766  	J **int
   767  }
   768  
   769  var unmarshalTests = []unmarshalTest{
   770  	// basic types
   771  	{in: `true`, ptr: new(bool), out: true},                                           // 0
   772  	{in: `1`, ptr: new(int), out: 1},                                                  // 1
   773  	{in: `1.2`, ptr: new(float64), out: 1.2},                                          // 2
   774  	{in: `-5`, ptr: new(int16), out: int16(-5)},                                       // 3
   775  	{in: `2`, ptr: new(json.Number), out: json.Number("2"), useNumber: true},          // 4
   776  	{in: `2`, ptr: new(json.Number), out: json.Number("2")},                           // 5
   777  	{in: `2`, ptr: new(any), out: float64(2.0)},                                       // 6
   778  	{in: `2`, ptr: new(any), out: json.Number("2"), useNumber: true},                  // 7
   779  	{in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},                               // 8
   780  	{in: `"http:\/\/"`, ptr: new(string), out: "http://"},                             // 9
   781  	{in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},       // 10
   782  	{in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, // 11
   783  	{in: "null", ptr: new(any), out: nil},                                             // 12
   784  	{in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &json.UnmarshalTypeError{Value: "array", Type: reflect.TypeOf(""), Offset: 7, Struct: "T", Field: "X"}},                            // 13
   785  	{in: `{"X": 23}`, ptr: new(T), out: T{}, err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 8, Struct: "T", Field: "X"}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, // 14
   786  	{in: `{"x": 1}`, ptr: new(tx), out: tx{}}, // 15, 16
   787  	{in: `{"x": 1}`, ptr: new(tx), err: errors.New("json: unknown field \"x\""), disallowUnknownFields: true},                                                  // 17
   788  	{in: `{"S": 23}`, ptr: new(W), out: W{}, err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(SS("")), Offset: 0, Struct: "W", Field: "S"}}, // 18
   789  	{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: json.Number("3")}},                                                    // 19
   790  	{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: json.Number("1"), F2: int32(2), F3: json.Number("3")}, useNumber: true},                             // 20
   791  	{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsFloat64},                                                // 21
   792  	{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsNumber, useNumber: true},                                // 22
   793  
   794  	// raw values with whitespace
   795  	{in: "\n true ", ptr: new(bool), out: true},                  // 23
   796  	{in: "\t 1 ", ptr: new(int), out: 1},                         // 24
   797  	{in: "\r 1.2 ", ptr: new(float64), out: 1.2},                 // 25
   798  	{in: "\t -5 \n", ptr: new(int16), out: int16(-5)},            // 26
   799  	{in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"}, // 27
   800  
   801  	// Z has a "-" tag.
   802  	{in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},                                                              // 28
   803  	{in: `{"Y": 1, "Z": 2}`, ptr: new(T), err: errors.New("json: unknown field \"Z\""), disallowUnknownFields: true}, // 29
   804  
   805  	{in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},                                                          // 30
   806  	{in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), err: errors.New("json: unknown field \"alphabet\""), disallowUnknownFields: true}, // 31
   807  	{in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},                                                                             // 32
   808  	{in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},                                                                                         // 33
   809  	{in: `{"alphabet": "xyz"}`, ptr: new(U), err: errors.New("json: unknown field \"alphabet\""), disallowUnknownFields: true},                 // 34
   810  
   811  	// syntax errors
   812  	{in: `{"X": "foo", "Y"}`, err: json.NewSyntaxError("invalid character '}' after object key", 17)},                                              // 35
   813  	{in: `[1, 2, 3+]`, err: json.NewSyntaxError("invalid character '+' after array element", 9)},                                                   // 36
   814  	{in: `{"X":12x}`, err: json.NewSyntaxError("invalid character 'x' after object key:value pair", 8), useNumber: true},                           // 37
   815  	{in: `[2, 3`, err: json.NewSyntaxError("unexpected end of JSON input", 5)},                                                                     // 38
   816  	{in: `{"F3": -}`, ptr: new(V), out: V{F3: json.Number("-")}, err: json.NewSyntaxError("strconv.ParseFloat: parsing \"-\": invalid syntax", 9)}, // 39
   817  
   818  	// raw value errors
   819  	{in: "\x01 42", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)},         // 40
   820  	{in: " 42 \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 5)},                 // 41
   821  	{in: "\x01 true", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)},       // 42
   822  	{in: " false \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 8)},              // 43
   823  	{in: "\x01 1.2", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)},        // 44
   824  	{in: " 3.4 \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 6)},                // 45
   825  	{in: "\x01 \"string\"", err: json.NewSyntaxError("invalid character '\\x01' looking for beginning of value", 1)}, // 46
   826  	{in: " \"string\" \x01", err: json.NewSyntaxError("invalid character '\\x01' after top-level value", 11)},        // 47
   827  
   828  	// array tests
   829  	{in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},                                           // 48
   830  	{in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},                                                 // 49
   831  	{in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},                                     // 50
   832  	{in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")}, // 51
   833  
   834  	// empty array to interface test
   835  	{in: `[]`, ptr: new([]any), out: []any{}},
   836  	{in: `null`, ptr: new([]any), out: []any(nil)}, // 53
   837  	{in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}},
   838  	{in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}}, // 55
   839  
   840  	// composite tests
   841  	{in: allValueIndent, ptr: new(All), out: allValue},      // 56
   842  	{in: allValueCompact, ptr: new(All), out: allValue},     // 57
   843  	{in: allValueIndent, ptr: new(*All), out: &allValue},    // 58
   844  	{in: allValueCompact, ptr: new(*All), out: &allValue},   // 59
   845  	{in: pallValueIndent, ptr: new(All), out: pallValue},    // 60
   846  	{in: pallValueCompact, ptr: new(All), out: pallValue},   // 61
   847  	{in: pallValueIndent, ptr: new(*All), out: &pallValue},  // 62
   848  	{in: pallValueCompact, ptr: new(*All), out: &pallValue}, // 63
   849  
   850  	// unmarshal interface test
   851  	{in: `{"T":false}`, ptr: new(unmarshaler), out: umtrue},        // use "false" so test will fail if custom unmarshaler is not called
   852  	{in: `{"T":false}`, ptr: new(*unmarshaler), out: &umtrue},      // 65
   853  	{in: `[{"T":false}]`, ptr: new([]unmarshaler), out: umslice},   // 66
   854  	{in: `[{"T":false}]`, ptr: new(*[]unmarshaler), out: &umslice}, // 67
   855  	{in: `{"M":{"T":"x:y"}}`, ptr: new(ustruct), out: umstruct},    // 68
   856  
   857  	// UnmarshalText interface test
   858  	{in: `"x:y"`, ptr: new(unmarshalerText), out: umtrueXY},        // 69
   859  	{in: `"x:y"`, ptr: new(*unmarshalerText), out: &umtrueXY},      // 70
   860  	{in: `["x:y"]`, ptr: new([]unmarshalerText), out: umsliceXY},   // 71
   861  	{in: `["x:y"]`, ptr: new(*[]unmarshalerText), out: &umsliceXY}, // 72
   862  	{in: `{"M":"x:y"}`, ptr: new(ustructText), out: umstructXY},    // 73
   863  	// integer-keyed map test
   864  	{
   865  		in:  `{"-1":"a","0":"b","1":"c"}`, // 74
   866  		ptr: new(map[int]string),
   867  		out: map[int]string{-1: "a", 0: "b", 1: "c"},
   868  	},
   869  	{
   870  		in:  `{"0":"a","10":"c","9":"b"}`, // 75
   871  		ptr: new(map[u8]string),
   872  		out: map[u8]string{0: "a", 9: "b", 10: "c"},
   873  	},
   874  	{
   875  		in:  `{"-9223372036854775808":"min","9223372036854775807":"max"}`, // 76
   876  		ptr: new(map[int64]string),
   877  		out: map[int64]string{math.MinInt64: "min", math.MaxInt64: "max"},
   878  	},
   879  	{
   880  		in:  `{"18446744073709551615":"max"}`, // 77
   881  		ptr: new(map[uint64]string),
   882  		out: map[uint64]string{math.MaxUint64: "max"},
   883  	},
   884  	{
   885  		in:  `{"0":false,"10":true}`, // 78
   886  		ptr: new(map[uintptr]bool),
   887  		out: map[uintptr]bool{0: false, 10: true},
   888  	},
   889  	// Check that MarshalText and UnmarshalText take precedence
   890  	// over default integer handling in map keys.
   891  	{
   892  		in:  `{"u2":4}`, // 79
   893  		ptr: new(map[u8marshal]int),
   894  		out: map[u8marshal]int{2: 4},
   895  	},
   896  	{
   897  		in:  `{"2":4}`, // 80
   898  		ptr: new(map[u8marshal]int),
   899  		err: errMissingU8Prefix,
   900  	},
   901  	// integer-keyed map errors
   902  	{
   903  		in:  `{"abc":"abc"}`, // 81
   904  		ptr: new(map[int]string),
   905  		err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(0), Offset: 2},
   906  	},
   907  	{
   908  		in:  `{"256":"abc"}`, // 82
   909  		ptr: new(map[uint8]string),
   910  		err: &json.UnmarshalTypeError{Value: "number 256", Type: reflect.TypeOf(uint8(0)), Offset: 2},
   911  	},
   912  	{
   913  		in:  `{"128":"abc"}`, // 83
   914  		ptr: new(map[int8]string),
   915  		err: &json.UnmarshalTypeError{Value: "number 128", Type: reflect.TypeOf(int8(0)), Offset: 2},
   916  	},
   917  	{
   918  		in:  `{"-1":"abc"}`, // 84
   919  		ptr: new(map[uint8]string),
   920  		err: &json.UnmarshalTypeError{Value: "number -", Type: reflect.TypeOf(uint8(0)), Offset: 2},
   921  	},
   922  	{
   923  		in:  `{"F":{"a":2,"3":4}}`, // 85
   924  		ptr: new(map[string]map[int]int),
   925  		err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(int(0)), Offset: 7},
   926  	},
   927  	{
   928  		in:  `{"F":{"a":2,"3":4}}`, // 86
   929  		ptr: new(map[string]map[uint]int),
   930  		err: &json.UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(uint(0)), Offset: 7},
   931  	},
   932  	// Map keys can be encoding.TextUnmarshalers.
   933  	{in: `{"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY}, // 87
   934  	// If multiple values for the same key exists, only the most recent value is used.
   935  	{in: `{"x:y":false,"x:y":true}`, ptr: new(map[unmarshalerText]bool), out: ummapXY}, // 88
   936  	{ // 89
   937  		in: `{
   938  							"Level0": 1,
   939  							"Level1b": 2,
   940  							"Level1c": 3,
   941  							"x": 4,
   942  							"Level1a": 5,
   943  							"LEVEL1B": 6,
   944  							"e": {
   945  								"Level1a": 8,
   946  								"Level1b": 9,
   947  								"Level1c": 10,
   948  								"Level1d": 11,
   949  								"x": 12
   950  							},
   951  							"Loop1": 13,
   952  							"Loop2": 14,
   953  							"X": 15,
   954  							"Y": 16,
   955  							"Z": 17,
   956  							"Q": 18
   957  						}`,
   958  		ptr: new(Top),
   959  		out: Top{
   960  			Level0: 1,
   961  			Embed0: Embed0{
   962  				Level1b: 2,
   963  				Level1c: 3,
   964  			},
   965  			Embed0a: &Embed0a{
   966  				Level1a: 5,
   967  				Level1b: 6,
   968  			},
   969  			Embed0b: &Embed0b{
   970  				Level1a: 8,
   971  				Level1b: 9,
   972  				Level1c: 10,
   973  				Level1d: 11,
   974  				Level1e: 12,
   975  			},
   976  			Loop: Loop{
   977  				Loop1: 13,
   978  				Loop2: 14,
   979  			},
   980  			Embed0p: Embed0p{
   981  				Point: image.Point{X: 15, Y: 16},
   982  			},
   983  			Embed0q: Embed0q{
   984  				Point: Point{Z: 17},
   985  			},
   986  			embed: embed{
   987  				Q: 18,
   988  			},
   989  		},
   990  	},
   991  	{
   992  		in:  `{"hello": 1}`, // 90
   993  		ptr: new(Ambig),
   994  		out: Ambig{First: 1},
   995  	},
   996  	{
   997  		in:  `{"X": 1,"Y":2}`, // 91
   998  		ptr: new(S5),
   999  		out: S5{S8: S8{S9: S9{Y: 2}}},
  1000  	},
  1001  	{
  1002  		in:                    `{"X": 1,"Y":2}`, // 92
  1003  		ptr:                   new(S5),
  1004  		err:                   errors.New("json: unknown field \"X\""),
  1005  		disallowUnknownFields: true,
  1006  	},
  1007  	{
  1008  		in:  `{"X": 1,"Y":2}`, // 93
  1009  		ptr: new(S10),
  1010  		out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
  1011  	},
  1012  	{
  1013  		in:                    `{"X": 1,"Y":2}`, // 94
  1014  		ptr:                   new(S10),
  1015  		err:                   errors.New("json: unknown field \"X\""),
  1016  		disallowUnknownFields: true,
  1017  	},
  1018  	{
  1019  		in:  `{"I": 0, "I": null, "J": null}`, // 95
  1020  		ptr: new(DoublePtr),
  1021  		out: DoublePtr{I: nil, J: nil},
  1022  	},
  1023  	{
  1024  		in:  "\"hello\\ud800world\"", // 96
  1025  		ptr: new(string),
  1026  		out: "hello\ufffdworld",
  1027  	},
  1028  	{
  1029  		in:  "\"hello\\ud800\\ud800world\"", // 97
  1030  		ptr: new(string),
  1031  		out: "hello\ufffd\ufffdworld",
  1032  	},
  1033  	{
  1034  		in:  "\"hello\\ud800\\ud800world\"", // 98
  1035  		ptr: new(string),
  1036  		out: "hello\ufffd\ufffdworld",
  1037  	},
  1038  	// Used to be issue 8305, but time.Time implements encoding.TextUnmarshaler so this works now.
  1039  	{
  1040  		in:  `{"2009-11-10T23:00:00Z": "hello world"}`, // 99
  1041  		ptr: new(map[time.Time]string),
  1042  		out: map[time.Time]string{time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC): "hello world"},
  1043  	},
  1044  	// issue 8305
  1045  	{
  1046  		in:  `{"2009-11-10T23:00:00Z": "hello world"}`, // 100
  1047  		ptr: new(map[Point]string),
  1048  		err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(Point{}), Offset: 0},
  1049  	},
  1050  	{
  1051  		in:  `{"asdf": "hello world"}`, // 101
  1052  		ptr: new(map[unmarshaler]string),
  1053  		err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(unmarshaler{}), Offset: 1},
  1054  	},
  1055  	// related to issue 13783.
  1056  	// Go 1.7 changed marshaling a slice of typed byte to use the methods on the byte type,
  1057  	// similar to marshaling a slice of typed int.
  1058  	// These tests check that, assuming the byte type also has valid decoding methods,
  1059  	// either the old base64 string encoding or the new per-element encoding can be
  1060  	// successfully unmarshaled. The custom unmarshalers were accessible in earlier
  1061  	// versions of Go, even though the custom marshaler was not.
  1062  	{
  1063  		in:  `"AQID"`, // 102
  1064  		ptr: new([]byteWithMarshalJSON),
  1065  		out: []byteWithMarshalJSON{1, 2, 3},
  1066  	},
  1067  	{
  1068  		in:     `["Z01","Z02","Z03"]`, // 103
  1069  		ptr:    new([]byteWithMarshalJSON),
  1070  		out:    []byteWithMarshalJSON{1, 2, 3},
  1071  		golden: true,
  1072  	},
  1073  	{
  1074  		in:  `"AQID"`, // 104
  1075  		ptr: new([]byteWithMarshalText),
  1076  		out: []byteWithMarshalText{1, 2, 3},
  1077  	},
  1078  	{
  1079  		in:     `["Z01","Z02","Z03"]`, // 105
  1080  		ptr:    new([]byteWithMarshalText),
  1081  		out:    []byteWithMarshalText{1, 2, 3},
  1082  		golden: true,
  1083  	},
  1084  	{
  1085  		in:  `"AQID"`, // 106
  1086  		ptr: new([]byteWithPtrMarshalJSON),
  1087  		out: []byteWithPtrMarshalJSON{1, 2, 3},
  1088  	},
  1089  	{
  1090  		in:     `["Z01","Z02","Z03"]`, // 107
  1091  		ptr:    new([]byteWithPtrMarshalJSON),
  1092  		out:    []byteWithPtrMarshalJSON{1, 2, 3},
  1093  		golden: true,
  1094  	},
  1095  	{
  1096  		in:  `"AQID"`, // 108
  1097  		ptr: new([]byteWithPtrMarshalText),
  1098  		out: []byteWithPtrMarshalText{1, 2, 3},
  1099  	},
  1100  	{
  1101  		in:     `["Z01","Z02","Z03"]`, // 109
  1102  		ptr:    new([]byteWithPtrMarshalText),
  1103  		out:    []byteWithPtrMarshalText{1, 2, 3},
  1104  		golden: true,
  1105  	},
  1106  
  1107  	// ints work with the marshaler but not the base64 []byte case
  1108  	{
  1109  		in:     `["Z01","Z02","Z03"]`, // 110
  1110  		ptr:    new([]intWithMarshalJSON),
  1111  		out:    []intWithMarshalJSON{1, 2, 3},
  1112  		golden: true,
  1113  	},
  1114  	{
  1115  		in:     `["Z01","Z02","Z03"]`, // 111
  1116  		ptr:    new([]intWithMarshalText),
  1117  		out:    []intWithMarshalText{1, 2, 3},
  1118  		golden: true,
  1119  	},
  1120  	{
  1121  		in:     `["Z01","Z02","Z03"]`, // 112
  1122  		ptr:    new([]intWithPtrMarshalJSON),
  1123  		out:    []intWithPtrMarshalJSON{1, 2, 3},
  1124  		golden: true,
  1125  	},
  1126  	{
  1127  		in:     `["Z01","Z02","Z03"]`, // 113
  1128  		ptr:    new([]intWithPtrMarshalText),
  1129  		out:    []intWithPtrMarshalText{1, 2, 3},
  1130  		golden: true,
  1131  	},
  1132  
  1133  	{in: `0.000001`, ptr: new(float64), out: 0.000001, golden: true},                               // 114
  1134  	{in: `1e-07`, ptr: new(float64), out: 1e-7, golden: true},                                      // 115
  1135  	{in: `100000000000000000000`, ptr: new(float64), out: 100000000000000000000.0, golden: true},   // 116
  1136  	{in: `1e+21`, ptr: new(float64), out: 1e21, golden: true},                                      // 117
  1137  	{in: `-0.000001`, ptr: new(float64), out: -0.000001, golden: true},                             // 118
  1138  	{in: `-1e-07`, ptr: new(float64), out: -1e-7, golden: true},                                    // 119
  1139  	{in: `-100000000000000000000`, ptr: new(float64), out: -100000000000000000000.0, golden: true}, // 120
  1140  	{in: `-1e+21`, ptr: new(float64), out: -1e21, golden: true},                                    // 121
  1141  	{in: `999999999999999900000`, ptr: new(float64), out: 999999999999999900000.0, golden: true},   // 122
  1142  	{in: `9007199254740992`, ptr: new(float64), out: 9007199254740992.0, golden: true},             // 123
  1143  	{in: `9007199254740993`, ptr: new(float64), out: 9007199254740992.0, golden: false},            // 124
  1144  	{
  1145  		in:  `{"V": {"F2": "hello"}}`, // 125
  1146  		ptr: new(VOuter),
  1147  		err: &json.UnmarshalTypeError{
  1148  			Value:  `number "`,
  1149  			Struct: "V",
  1150  			Field:  "F2",
  1151  			Type:   reflect.TypeOf(int32(0)),
  1152  			Offset: 20,
  1153  		},
  1154  	},
  1155  	{
  1156  		in:  `{"V": {"F4": {}, "F2": "hello"}}`, // 126
  1157  		ptr: new(VOuter),
  1158  		err: &json.UnmarshalTypeError{
  1159  			Value:  `number "`,
  1160  			Struct: "V",
  1161  			Field:  "F2",
  1162  			Type:   reflect.TypeOf(int32(0)),
  1163  			Offset: 30,
  1164  		},
  1165  	},
  1166  	// issue 15146.
  1167  	// invalid inputs in wrongStringTests below.
  1168  	{in: `{"B":"true"}`, ptr: new(B), out: B{B: true}, golden: true},                                                            // 127
  1169  	{in: `{"B":"false"}`, ptr: new(B), out: B{B: false}, golden: true},                                                          // 128
  1170  	{in: `{"B": "maybe"}`, ptr: new(B), err: errors.New(`json: bool unexpected end of JSON input`)},                             // 129
  1171  	{in: `{"B": "tru"}`, ptr: new(B), err: errors.New(`json: invalid character as true`)},                                       // 130
  1172  	{in: `{"B": "False"}`, ptr: new(B), err: errors.New(`json: bool unexpected end of JSON input`)},                             // 131
  1173  	{in: `{"B": "null"}`, ptr: new(B), out: B{B: false}},                                                                        // 132
  1174  	{in: `{"B": "nul"}`, ptr: new(B), err: errors.New(`json: invalid character as null`)},                                       // 133
  1175  	{in: `{"B": [2, 3]}`, ptr: new(B), err: errors.New(`json: cannot unmarshal array into Go struct field B.B of type string`)}, // 134
  1176  	// additional tests for disallowUnknownFields
  1177  	{ // 135
  1178  		in: `{
  1179  						"Level0": 1,
  1180  						"Level1b": 2,
  1181  						"Level1c": 3,
  1182  						"x": 4,
  1183  						"Level1a": 5,
  1184  						"LEVEL1B": 6,
  1185  						"e": {
  1186  							"Level1a": 8,
  1187  							"Level1b": 9,
  1188  							"Level1c": 10,
  1189  							"Level1d": 11,
  1190  							"x": 12
  1191  						},
  1192  						"Loop1": 13,
  1193  						"Loop2": 14,
  1194  						"X": 15,
  1195  						"Y": 16,
  1196  						"Z": 17,
  1197  						"Q": 18,
  1198  						"extra": true
  1199  					}`,
  1200  		ptr:                   new(Top),
  1201  		err:                   errors.New("json: unknown field \"extra\""),
  1202  		disallowUnknownFields: true,
  1203  	},
  1204  	{ // 136
  1205  		in: `{
  1206  						"Level0": 1,
  1207  						"Level1b": 2,
  1208  						"Level1c": 3,
  1209  						"x": 4,
  1210  						"Level1a": 5,
  1211  						"LEVEL1B": 6,
  1212  						"e": {
  1213  							"Level1a": 8,
  1214  							"Level1b": 9,
  1215  							"Level1c": 10,
  1216  							"Level1d": 11,
  1217  							"x": 12,
  1218  							"extra": null
  1219  						},
  1220  						"Loop1": 13,
  1221  						"Loop2": 14,
  1222  						"X": 15,
  1223  						"Y": 16,
  1224  						"Z": 17,
  1225  						"Q": 18
  1226  					}`,
  1227  		ptr:                   new(Top),
  1228  		err:                   errors.New("json: unknown field \"extra\""),
  1229  		disallowUnknownFields: true,
  1230  	},
  1231  	// issue 26444
  1232  	// UnmarshalTypeError without field & struct values
  1233  	{
  1234  		in:  `{"data":{"test1": "bob", "test2": 123}}`, // 137
  1235  		ptr: new(mapStringToStringData),
  1236  		err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 37, Struct: "mapStringToStringData", Field: "Data"},
  1237  	},
  1238  	{
  1239  		in:  `{"data":{"test1": 123, "test2": "bob"}}`, // 138
  1240  		ptr: new(mapStringToStringData),
  1241  		err: &json.UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 21, Struct: "mapStringToStringData", Field: "Data"},
  1242  	},
  1243  
  1244  	// trying to decode JSON arrays or objects via TextUnmarshaler
  1245  	{
  1246  		in:  `[1, 2, 3]`, // 139
  1247  		ptr: new(MustNotUnmarshalText),
  1248  		err: &json.UnmarshalTypeError{Value: "array", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1},
  1249  	},
  1250  	{
  1251  		in:  `{"foo": "bar"}`, // 140
  1252  		ptr: new(MustNotUnmarshalText),
  1253  		err: &json.UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1},
  1254  	},
  1255  	// #22369
  1256  	{
  1257  		in:  `{"PP": {"T": {"Y": "bad-type"}}}`, // 141
  1258  		ptr: new(P),
  1259  		err: &json.UnmarshalTypeError{
  1260  			Value:  `number "`,
  1261  			Struct: "T",
  1262  			Field:  "Y",
  1263  			Type:   reflect.TypeOf(int(0)),
  1264  			Offset: 29,
  1265  		},
  1266  	},
  1267  	{
  1268  		in:  `{"Ts": [{"Y": 1}, {"Y": 2}, {"Y": "bad-type"}]}`, // 142
  1269  		ptr: new(PP),
  1270  		err: &json.UnmarshalTypeError{
  1271  			Value:  `number "`,
  1272  			Struct: "T",
  1273  			Field:  "Y",
  1274  			Type:   reflect.TypeOf(int(0)),
  1275  			Offset: 29,
  1276  		},
  1277  	},
  1278  	// #14702
  1279  	{
  1280  		in:  `invalid`, // 143
  1281  		ptr: new(json.Number),
  1282  		err: json.NewSyntaxError(
  1283  			`invalid character 'i' looking for beginning of value`,
  1284  			1,
  1285  		),
  1286  	},
  1287  	{
  1288  		in:  `"invalid"`, // 144
  1289  		ptr: new(json.Number),
  1290  		err: errors.New(`strconv.ParseFloat: parsing "invalid": invalid syntax`),
  1291  	},
  1292  	{
  1293  		in:  `{"A":"invalid"}`, // 145
  1294  		ptr: new(struct{ A json.Number }),
  1295  		err: errors.New(`strconv.ParseFloat: parsing "invalid": invalid syntax`),
  1296  	},
  1297  	{
  1298  		in: `{"A":"invalid"}`, // 146
  1299  		ptr: new(struct {
  1300  			A json.Number `json:",string"`
  1301  		}),
  1302  		err: errors.New(`json: json.Number unexpected end of JSON input`),
  1303  	},
  1304  	{
  1305  		in:  `{"A":"invalid"}`, // 147
  1306  		ptr: new(map[string]json.Number),
  1307  		err: errors.New(`strconv.ParseFloat: parsing "invalid": invalid syntax`),
  1308  	},
  1309  	// invalid UTF-8 is coerced to valid UTF-8.
  1310  	{
  1311  		in:  "\"hello\xffworld\"", // 148
  1312  		ptr: new(string),
  1313  		out: "hello\ufffdworld",
  1314  	},
  1315  	{
  1316  		in:  "\"hello\xc2\xc2world\"", // 149
  1317  		ptr: new(string),
  1318  		out: "hello\ufffd\ufffdworld",
  1319  	},
  1320  	{
  1321  		in:  "\"hello\xc2\xffworld\"", // 150
  1322  		ptr: new(string),
  1323  		out: "hello\ufffd\ufffdworld",
  1324  	},
  1325  	{
  1326  		in:  "\"hello\xed\xa0\x80\xed\xb0\x80world\"", // 151
  1327  		ptr: new(string),
  1328  		out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
  1329  	},
  1330  	{in: "-128", ptr: new(int8), out: int8(-128)},
  1331  	{in: "127", ptr: new(int8), out: int8(127)},
  1332  	{in: "-32768", ptr: new(int16), out: int16(-32768)},
  1333  	{in: "32767", ptr: new(int16), out: int16(32767)},
  1334  	{in: "-2147483648", ptr: new(int32), out: int32(-2147483648)},
  1335  	{in: "2147483647", ptr: new(int32), out: int32(2147483647)},
  1336  }
  1337  
  1338  type All struct {
  1339  	Bool    bool
  1340  	Int     int
  1341  	Int8    int8
  1342  	Int16   int16
  1343  	Int32   int32
  1344  	Int64   int64
  1345  	Uint    uint
  1346  	Uint8   uint8
  1347  	Uint16  uint16
  1348  	Uint32  uint32
  1349  	Uint64  uint64
  1350  	Uintptr uintptr
  1351  	Float32 float32
  1352  	Float64 float64
  1353  
  1354  	Foo  string `json:"bar"`
  1355  	Foo2 string `json:"bar2,dummyopt"`
  1356  
  1357  	IntStr     int64   `json:",string"`
  1358  	UintptrStr uintptr `json:",string"`
  1359  
  1360  	PBool    *bool
  1361  	PInt     *int
  1362  	PInt8    *int8
  1363  	PInt16   *int16
  1364  	PInt32   *int32
  1365  	PInt64   *int64
  1366  	PUint    *uint
  1367  	PUint8   *uint8
  1368  	PUint16  *uint16
  1369  	PUint32  *uint32
  1370  	PUint64  *uint64
  1371  	PUintptr *uintptr
  1372  	PFloat32 *float32
  1373  	PFloat64 *float64
  1374  
  1375  	String  string
  1376  	PString *string
  1377  
  1378  	Map   map[string]Small
  1379  	MapP  map[string]*Small
  1380  	PMap  *map[string]Small
  1381  	PMapP *map[string]*Small
  1382  
  1383  	EmptyMap map[string]Small
  1384  	NilMap   map[string]Small
  1385  
  1386  	Slice   []Small
  1387  	SliceP  []*Small
  1388  	PSlice  *[]Small
  1389  	PSliceP *[]*Small
  1390  
  1391  	EmptySlice []Small
  1392  	NilSlice   []Small
  1393  
  1394  	StringSlice []string
  1395  	ByteSlice   []byte
  1396  
  1397  	Small   Small
  1398  	PSmall  *Small
  1399  	PPSmall **Small
  1400  
  1401  	Interface  any
  1402  	PInterface *any
  1403  
  1404  	unexported int
  1405  }
  1406  
  1407  type Small struct {
  1408  	Tag string
  1409  }
  1410  
  1411  var allValue = All{
  1412  	Bool:       true,
  1413  	Int:        2,
  1414  	Int8:       3,
  1415  	Int16:      4,
  1416  	Int32:      5,
  1417  	Int64:      6,
  1418  	Uint:       7,
  1419  	Uint8:      8,
  1420  	Uint16:     9,
  1421  	Uint32:     10,
  1422  	Uint64:     11,
  1423  	Uintptr:    12,
  1424  	Float32:    14.1,
  1425  	Float64:    15.1,
  1426  	Foo:        "foo",
  1427  	Foo2:       "foo2",
  1428  	IntStr:     42,
  1429  	UintptrStr: 44,
  1430  	String:     "16",
  1431  	Map: map[string]Small{
  1432  		"17": {Tag: "tag17"},
  1433  		"18": {Tag: "tag18"},
  1434  	},
  1435  	MapP: map[string]*Small{
  1436  		"19": {Tag: "tag19"},
  1437  		"20": nil,
  1438  	},
  1439  	EmptyMap:    map[string]Small{},
  1440  	Slice:       []Small{{Tag: "tag20"}, {Tag: "tag21"}},
  1441  	SliceP:      []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
  1442  	EmptySlice:  []Small{},
  1443  	StringSlice: []string{"str24", "str25", "str26"},
  1444  	ByteSlice:   []byte{27, 28, 29},
  1445  	Small:       Small{Tag: "tag30"},
  1446  	PSmall:      &Small{Tag: "tag31"},
  1447  	Interface:   5.2,
  1448  }
  1449  
  1450  var pallValue = All{
  1451  	PBool:      &allValue.Bool,
  1452  	PInt:       &allValue.Int,
  1453  	PInt8:      &allValue.Int8,
  1454  	PInt16:     &allValue.Int16,
  1455  	PInt32:     &allValue.Int32,
  1456  	PInt64:     &allValue.Int64,
  1457  	PUint:      &allValue.Uint,
  1458  	PUint8:     &allValue.Uint8,
  1459  	PUint16:    &allValue.Uint16,
  1460  	PUint32:    &allValue.Uint32,
  1461  	PUint64:    &allValue.Uint64,
  1462  	PUintptr:   &allValue.Uintptr,
  1463  	PFloat32:   &allValue.Float32,
  1464  	PFloat64:   &allValue.Float64,
  1465  	PString:    &allValue.String,
  1466  	PMap:       &allValue.Map,
  1467  	PMapP:      &allValue.MapP,
  1468  	PSlice:     &allValue.Slice,
  1469  	PSliceP:    &allValue.SliceP,
  1470  	PPSmall:    &allValue.PSmall,
  1471  	PInterface: &allValue.Interface,
  1472  }
  1473  
  1474  var allValueIndent = `{
  1475  	"Bool": true,
  1476  	"Int": 2,
  1477  	"Int8": 3,
  1478  	"Int16": 4,
  1479  	"Int32": 5,
  1480  	"Int64": 6,
  1481  	"Uint": 7,
  1482  	"Uint8": 8,
  1483  	"Uint16": 9,
  1484  	"Uint32": 10,
  1485  	"Uint64": 11,
  1486  	"Uintptr": 12,
  1487  	"Float32": 14.1,
  1488  	"Float64": 15.1,
  1489  	"bar": "foo",
  1490  	"bar2": "foo2",
  1491  	"IntStr": "42",
  1492  	"UintptrStr": "44",
  1493  	"PBool": null,
  1494  	"PInt": null,
  1495  	"PInt8": null,
  1496  	"PInt16": null,
  1497  	"PInt32": null,
  1498  	"PInt64": null,
  1499  	"PUint": null,
  1500  	"PUint8": null,
  1501  	"PUint16": null,
  1502  	"PUint32": null,
  1503  	"PUint64": null,
  1504  	"PUintptr": null,
  1505  	"PFloat32": null,
  1506  	"PFloat64": null,
  1507  	"String": "16",
  1508  	"PString": null,
  1509  	"Map": {
  1510  		"17": {
  1511  			"Tag": "tag17"
  1512  		},
  1513  		"18": {
  1514  			"Tag": "tag18"
  1515  		}
  1516  	},
  1517  	"MapP": {
  1518  		"19": {
  1519  			"Tag": "tag19"
  1520  		},
  1521  		"20": null
  1522  	},
  1523  	"PMap": null,
  1524  	"PMapP": null,
  1525  	"EmptyMap": {},
  1526  	"NilMap": null,
  1527  	"Slice": [
  1528  		{
  1529  			"Tag": "tag20"
  1530  		},
  1531  		{
  1532  			"Tag": "tag21"
  1533  		}
  1534  	],
  1535  	"SliceP": [
  1536  		{
  1537  			"Tag": "tag22"
  1538  		},
  1539  		null,
  1540  		{
  1541  			"Tag": "tag23"
  1542  		}
  1543  	],
  1544  	"PSlice": null,
  1545  	"PSliceP": null,
  1546  	"EmptySlice": [],
  1547  	"NilSlice": null,
  1548  	"StringSlice": [
  1549  		"str24",
  1550  		"str25",
  1551  		"str26"
  1552  	],
  1553  	"ByteSlice": "Gxwd",
  1554  	"Small": {
  1555  		"Tag": "tag30"
  1556  	},
  1557  	"PSmall": {
  1558  		"Tag": "tag31"
  1559  	},
  1560  	"PPSmall": null,
  1561  	"Interface": 5.2,
  1562  	"PInterface": null
  1563  }`
  1564  
  1565  var allValueCompact = strings.Map(noSpace, allValueIndent)
  1566  
  1567  var pallValueIndent = `{
  1568  	"Bool": false,
  1569  	"Int": 0,
  1570  	"Int8": 0,
  1571  	"Int16": 0,
  1572  	"Int32": 0,
  1573  	"Int64": 0,
  1574  	"Uint": 0,
  1575  	"Uint8": 0,
  1576  	"Uint16": 0,
  1577  	"Uint32": 0,
  1578  	"Uint64": 0,
  1579  	"Uintptr": 0,
  1580  	"Float32": 0,
  1581  	"Float64": 0,
  1582  	"bar": "",
  1583  	"bar2": "",
  1584          "IntStr": "0",
  1585  	"UintptrStr": "0",
  1586  	"PBool": true,
  1587  	"PInt": 2,
  1588  	"PInt8": 3,
  1589  	"PInt16": 4,
  1590  	"PInt32": 5,
  1591  	"PInt64": 6,
  1592  	"PUint": 7,
  1593  	"PUint8": 8,
  1594  	"PUint16": 9,
  1595  	"PUint32": 10,
  1596  	"PUint64": 11,
  1597  	"PUintptr": 12,
  1598  	"PFloat32": 14.1,
  1599  	"PFloat64": 15.1,
  1600  	"String": "",
  1601  	"PString": "16",
  1602  	"Map": null,
  1603  	"MapP": null,
  1604  	"PMap": {
  1605  		"17": {
  1606  			"Tag": "tag17"
  1607  		},
  1608  		"18": {
  1609  			"Tag": "tag18"
  1610  		}
  1611  	},
  1612  	"PMapP": {
  1613  		"19": {
  1614  			"Tag": "tag19"
  1615  		},
  1616  		"20": null
  1617  	},
  1618  	"EmptyMap": null,
  1619  	"NilMap": null,
  1620  	"Slice": null,
  1621  	"SliceP": null,
  1622  	"PSlice": [
  1623  		{
  1624  			"Tag": "tag20"
  1625  		},
  1626  		{
  1627  			"Tag": "tag21"
  1628  		}
  1629  	],
  1630  	"PSliceP": [
  1631  		{
  1632  			"Tag": "tag22"
  1633  		},
  1634  		null,
  1635  		{
  1636  			"Tag": "tag23"
  1637  		}
  1638  	],
  1639  	"EmptySlice": null,
  1640  	"NilSlice": null,
  1641  	"StringSlice": null,
  1642  	"ByteSlice": null,
  1643  	"Small": {
  1644  		"Tag": ""
  1645  	},
  1646  	"PSmall": null,
  1647  	"PPSmall": {
  1648  		"Tag": "tag31"
  1649  	},
  1650  	"Interface": null,
  1651  	"PInterface": 5.2
  1652  }`
  1653  
  1654  var pallValueCompact = strings.Map(noSpace, pallValueIndent)
  1655  
  1656  type NullTest struct {
  1657  	Bool      bool
  1658  	Int       int
  1659  	Int8      int8
  1660  	Int16     int16
  1661  	Int32     int32
  1662  	Int64     int64
  1663  	Uint      uint
  1664  	Uint8     uint8
  1665  	Uint16    uint16
  1666  	Uint32    uint32
  1667  	Uint64    uint64
  1668  	Float32   float32
  1669  	Float64   float64
  1670  	String    string
  1671  	PBool     *bool
  1672  	Map       map[string]string
  1673  	Slice     []string
  1674  	Interface any
  1675  
  1676  	PRaw    *json.RawMessage
  1677  	PTime   *time.Time
  1678  	PBigInt *big.Int
  1679  	PText   *MustNotUnmarshalText
  1680  	PBuffer *bytes.Buffer // has methods, just not relevant ones
  1681  	PStruct *struct{}
  1682  
  1683  	Raw    json.RawMessage
  1684  	Time   time.Time
  1685  	BigInt big.Int
  1686  	Text   MustNotUnmarshalText
  1687  	Buffer bytes.Buffer
  1688  	Struct struct{}
  1689  }
  1690  
  1691  type MustNotUnmarshalJSON struct{}
  1692  
  1693  func (x MustNotUnmarshalJSON) UnmarshalJSON(data []byte) error {
  1694  	return errors.New("MustNotUnmarshalJSON was used")
  1695  }
  1696  
  1697  type MustNotUnmarshalText struct{}
  1698  
  1699  func (x MustNotUnmarshalText) UnmarshalText(text []byte) error {
  1700  	return errors.New("MustNotUnmarshalText was used")
  1701  }
  1702  
  1703  func isSpace(c byte) bool {
  1704  	return c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n')
  1705  }
  1706  
  1707  func noSpace(c rune) rune {
  1708  	if isSpace(byte(c)) { // only used for ascii
  1709  		return -1
  1710  	}
  1711  	return c
  1712  }
  1713  
  1714  var badUTF8 = []struct {
  1715  	in, out string
  1716  }{
  1717  	{in: "hello\xffworld", out: `"hello\ufffdworld"`},
  1718  	{in: "", out: `""`},
  1719  	{in: "\xff", out: `"\ufffd"`},
  1720  	{in: "\xff\xff", out: `"\ufffd\ufffd"`},
  1721  	{in: "a\xffb", out: `"a\ufffdb"`},
  1722  	{in: "\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", out: `"日本\ufffd\ufffd\ufffd"`},
  1723  }
  1724  
  1725  func TestMarshalAllValue(t *testing.T) {
  1726  	b, err := json.Marshal(allValue)
  1727  	if err != nil {
  1728  		t.Fatalf("Marshal allValue: %v", err)
  1729  	}
  1730  	if string(b) != allValueCompact {
  1731  		t.Errorf("Marshal allValueCompact")
  1732  		diff(t, b, []byte(allValueCompact))
  1733  		return
  1734  	}
  1735  
  1736  	b, err = json.Marshal(pallValue)
  1737  	if err != nil {
  1738  		t.Fatalf("Marshal pallValue: %v", err)
  1739  	}
  1740  	if string(b) != pallValueCompact {
  1741  		t.Errorf("Marshal pallValueCompact")
  1742  		diff(t, b, []byte(pallValueCompact))
  1743  		return
  1744  	}
  1745  }
  1746  
  1747  func TestMarshalBadUTF8(t *testing.T) {
  1748  	for _, tt := range badUTF8 {
  1749  		b, err := json.Marshal(tt.in)
  1750  		if string(b) != tt.out || err != nil {
  1751  			t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out)
  1752  		}
  1753  	}
  1754  }
  1755  
  1756  func TestMarshalNumberZeroVal(t *testing.T) {
  1757  	var n json.Number
  1758  	out, err := json.Marshal(n)
  1759  	if err != nil {
  1760  		t.Fatal(err)
  1761  	}
  1762  	outStr := string(out)
  1763  	if outStr != "0" {
  1764  		t.Fatalf("Invalid zero val for Number: %q", outStr)
  1765  	}
  1766  }
  1767  
  1768  func TestMarshalEmbeds(t *testing.T) {
  1769  	top := &Top{
  1770  		Level0: 1,
  1771  		Embed0: Embed0{
  1772  			Level1b: 2,
  1773  			Level1c: 3,
  1774  		},
  1775  		Embed0a: &Embed0a{
  1776  			Level1a: 5,
  1777  			Level1b: 6,
  1778  		},
  1779  		Embed0b: &Embed0b{
  1780  			Level1a: 8,
  1781  			Level1b: 9,
  1782  			Level1c: 10,
  1783  			Level1d: 11,
  1784  			Level1e: 12,
  1785  		},
  1786  		Loop: Loop{
  1787  			Loop1: 13,
  1788  			Loop2: 14,
  1789  		},
  1790  		Embed0p: Embed0p{
  1791  			Point: image.Point{X: 15, Y: 16},
  1792  		},
  1793  		Embed0q: Embed0q{
  1794  			Point: Point{Z: 17},
  1795  		},
  1796  		embed: embed{
  1797  			Q: 18,
  1798  		},
  1799  	}
  1800  	b, err := json.Marshal(top)
  1801  	if err != nil {
  1802  		t.Fatal(err)
  1803  	}
  1804  	want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}"
  1805  	if string(b) != want {
  1806  		t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want)
  1807  	}
  1808  }
  1809  
  1810  func equalError(a, b error) bool {
  1811  	if a == nil {
  1812  		return b == nil
  1813  	}
  1814  	if b == nil {
  1815  		return a == nil
  1816  	}
  1817  	return a.Error() == b.Error()
  1818  }
  1819  
  1820  func TestUnmarshal(t *testing.T) {
  1821  	for i, tt := range unmarshalTests {
  1822  		t.Run(fmt.Sprintf("%d_%q", i, tt.in), func(t *testing.T) {
  1823  			in := []byte(tt.in)
  1824  			if tt.ptr == nil {
  1825  				return
  1826  			}
  1827  
  1828  			typ := reflect.TypeOf(tt.ptr)
  1829  			if typ.Kind() != reflect.Ptr {
  1830  				t.Errorf("#%d: unmarshalTest.ptr %T is not a pointer type", i, tt.ptr)
  1831  				return
  1832  			}
  1833  			typ = typ.Elem()
  1834  
  1835  			// v = new(right-type)
  1836  			v := reflect.New(typ)
  1837  
  1838  			if !reflect.DeepEqual(tt.ptr, v.Interface()) {
  1839  				// There's no reason for ptr to point to non-zero data,
  1840  				// as we decode into new(right-type), so the data is
  1841  				// discarded.
  1842  				// This can easily mean tests that silently don't test
  1843  				// what they should. To test decoding into existing
  1844  				// data, see TestPrefilled.
  1845  				t.Errorf("#%d: unmarshalTest.ptr %#v is not a pointer to a zero value", i, tt.ptr)
  1846  				return
  1847  			}
  1848  
  1849  			dec := json.NewDecoder(bytes.NewReader(in))
  1850  			if tt.useNumber {
  1851  				dec.UseNumber()
  1852  			}
  1853  			if tt.disallowUnknownFields {
  1854  				dec.DisallowUnknownFields()
  1855  			}
  1856  			if err := dec.Decode(v.Interface()); !equalError(err, tt.err) {
  1857  				t.Errorf("#%d: %v, want %v", i, err, tt.err)
  1858  				return
  1859  			} else if err != nil {
  1860  				return
  1861  			}
  1862  			if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
  1863  				t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
  1864  				data, _ := json.Marshal(v.Elem().Interface())
  1865  				println(string(data))
  1866  				data, _ = json.Marshal(tt.out)
  1867  				println(string(data))
  1868  				return
  1869  			}
  1870  
  1871  			// Check round trip also decodes correctly.
  1872  			if tt.err == nil {
  1873  				enc, err := json.Marshal(v.Interface())
  1874  				if err != nil {
  1875  					t.Errorf("#%d: error re-marshaling: %v", i, err)
  1876  					return
  1877  				}
  1878  				if tt.golden && !bytes.Equal(enc, in) {
  1879  					t.Errorf("#%d: remarshal mismatch:\nhave: %s\nwant: %s", i, enc, in)
  1880  				}
  1881  				vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
  1882  				dec = json.NewDecoder(bytes.NewReader(enc))
  1883  				if tt.useNumber {
  1884  					dec.UseNumber()
  1885  				}
  1886  				if err := dec.Decode(vv.Interface()); err != nil {
  1887  					t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err)
  1888  					return
  1889  				}
  1890  				if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
  1891  					t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
  1892  					t.Errorf("     In: %q", strings.Map(noSpace, string(in)))
  1893  					t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc)))
  1894  					return
  1895  				}
  1896  			}
  1897  		})
  1898  	}
  1899  }
  1900  
  1901  func TestUnmarshalMarshal(t *testing.T) {
  1902  	initBig()
  1903  	var v any
  1904  	if err := json.Unmarshal(jsonBig, &v); err != nil {
  1905  		t.Fatalf("Unmarshal: %v", err)
  1906  	}
  1907  	b, err := json.Marshal(v)
  1908  	if err != nil {
  1909  		t.Fatalf("Marshal: %v", err)
  1910  	}
  1911  	if !bytes.Equal(jsonBig, b) {
  1912  		t.Errorf("Marshal jsonBig")
  1913  		diff(t, b, jsonBig)
  1914  		return
  1915  	}
  1916  }
  1917  
  1918  var numberTests = []struct {
  1919  	in       string
  1920  	i        int64
  1921  	intErr   string
  1922  	f        float64
  1923  	floatErr string
  1924  }{
  1925  	{in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
  1926  	{in: "-12", i: -12, f: -12.0},
  1927  	{in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
  1928  }
  1929  
  1930  // Independent of Decode, basic coverage of the accessors in Number
  1931  func TestNumberAccessors(t *testing.T) {
  1932  	for _, tt := range numberTests {
  1933  		n := json.Number(tt.in)
  1934  		if s := n.String(); s != tt.in {
  1935  			t.Errorf("Number(%q).String() is %q", tt.in, s)
  1936  		}
  1937  		if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
  1938  			t.Errorf("Number(%q).Int64() is %d", tt.in, i)
  1939  		} else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
  1940  			t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err)
  1941  		}
  1942  		if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
  1943  			t.Errorf("Number(%q).Float64() is %g", tt.in, f)
  1944  		} else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
  1945  			t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err)
  1946  		}
  1947  	}
  1948  }
  1949  
  1950  func TestLargeByteSlice(t *testing.T) {
  1951  	s0 := make([]byte, 2000)
  1952  	for i := range s0 {
  1953  		s0[i] = byte(i)
  1954  	}
  1955  	b, err := json.Marshal(s0)
  1956  	if err != nil {
  1957  		t.Fatalf("Marshal: %v", err)
  1958  	}
  1959  	var s1 []byte
  1960  	if err := json.Unmarshal(b, &s1); err != nil {
  1961  		t.Fatalf("Unmarshal: %v", err)
  1962  	}
  1963  	if !bytes.Equal(s0, s1) {
  1964  		t.Errorf("Marshal large byte slice")
  1965  		diff(t, s0, s1)
  1966  	}
  1967  }
  1968  
  1969  type Xint struct {
  1970  	X int
  1971  }
  1972  
  1973  func TestUnmarshalInterface(t *testing.T) {
  1974  	var xint Xint
  1975  	var i any = &xint
  1976  	if err := json.Unmarshal([]byte(`{"X":1}`), &i); err != nil {
  1977  		t.Fatalf("Unmarshal: %v", err)
  1978  	}
  1979  	if xint.X != 1 {
  1980  		t.Fatalf("Did not write to xint")
  1981  	}
  1982  }
  1983  
  1984  func TestUnmarshalPtrPtr(t *testing.T) {
  1985  	var xint Xint
  1986  	pxint := &xint
  1987  	if err := json.Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
  1988  		t.Fatalf("Unmarshal: %v", err)
  1989  	}
  1990  	if xint.X != 1 {
  1991  		t.Fatalf("Did not write to xint")
  1992  	}
  1993  }
  1994  
  1995  func TestEscape(t *testing.T) {
  1996  	const input = `"foobar"<html>` + " [\u2028 \u2029]"
  1997  	const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"`
  1998  	b, err := json.Marshal(input)
  1999  	if err != nil {
  2000  		t.Fatalf("Marshal error: %v", err)
  2001  	}
  2002  	if s := string(b); s != expected {
  2003  		t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected)
  2004  	}
  2005  }
  2006  
  2007  // WrongString is a struct that's misusing the ,string modifier.
  2008  type WrongString struct {
  2009  	Message string `json:"result,string"`
  2010  }
  2011  
  2012  type wrongStringTest struct {
  2013  	in, err string
  2014  }
  2015  
  2016  var wrongStringTests = []wrongStringTest{
  2017  	{in: `{"result":"x"}`, err: `invalid character 'x' looking for beginning of value`},
  2018  	{in: `{"result":"foo"}`, err: `invalid character 'f' looking for beginning of value`},
  2019  	{in: `{"result":"123"}`, err: `json: cannot unmarshal number into Go struct field WrongString.Message of type string`},
  2020  	{in: `{"result":123}`, err: `json: cannot unmarshal number into Go struct field WrongString.Message of type string`},
  2021  	{in: `{"result":"\""}`, err: `json: string unexpected end of JSON input`},
  2022  	{in: `{"result":"\"foo"}`, err: `json: string unexpected end of JSON input`},
  2023  }
  2024  
  2025  // If people misuse the ,string modifier, the error message should be
  2026  // helpful, telling the user that they're doing it wrong.
  2027  func TestErrorMessageFromMisusedString(t *testing.T) {
  2028  	for n, tt := range wrongStringTests {
  2029  		r := strings.NewReader(tt.in)
  2030  		var s WrongString
  2031  		err := json.NewDecoder(r).Decode(&s)
  2032  		got := fmt.Sprintf("%v", err)
  2033  		if got != tt.err {
  2034  			t.Errorf("%d. got err = %q, want %q", n, got, tt.err)
  2035  		}
  2036  	}
  2037  }
  2038  
  2039  func TestRefUnmarshal(t *testing.T) {
  2040  	type S struct {
  2041  		// Ref is defined in encode_test.go.
  2042  		R0 Ref
  2043  
  2044  		R1 *Ref
  2045  		R2 RefText
  2046  		R3 *RefText
  2047  	}
  2048  	want := S{
  2049  		R0: 12,
  2050  		R1: new(Ref),
  2051  		R2: 13,
  2052  		R3: new(RefText),
  2053  	}
  2054  	*want.R1 = 12
  2055  	*want.R3 = 13
  2056  
  2057  	var got S
  2058  	if err := json.Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil {
  2059  		t.Fatalf("Unmarshal: %v", err)
  2060  	}
  2061  	if !reflect.DeepEqual(got, want) {
  2062  		t.Errorf("got %+v, want %+v", got, want)
  2063  	}
  2064  }
  2065  
  2066  // Test that the empty string doesn't panic decoding when ,string is specified
  2067  // Issue 3450
  2068  func TestEmptyString(t *testing.T) {
  2069  	type T2 struct {
  2070  		Number1 int `json:",string"`
  2071  		Number2 int `json:",string"`
  2072  	}
  2073  	data := `{"Number1":"1", "Number2":""}`
  2074  	dec := json.NewDecoder(strings.NewReader(data))
  2075  	var t2 T2
  2076  	err := dec.Decode(&t2)
  2077  	if err == nil {
  2078  		t.Fatal("Decode: did not return error")
  2079  	}
  2080  	if t2.Number1 != 1 {
  2081  		t.Fatal("Decode: did not set Number1")
  2082  	}
  2083  }
  2084  
  2085  // Test that a null for ,string is not replaced with the previous quoted string (issue 7046).
  2086  // It should also not be an error (issue 2540, issue 8587).
  2087  func TestNullString(t *testing.T) {
  2088  	type T struct {
  2089  		A int  `json:",string"`
  2090  		B int  `json:",string"`
  2091  		C *int `json:",string"`
  2092  	}
  2093  	data := []byte(`{"A": "1", "B": null, "C": null}`)
  2094  	var s T
  2095  	s.B = 1
  2096  	s.C = new(int)
  2097  	*s.C = 2
  2098  	err := json.Unmarshal(data, &s)
  2099  	if err != nil {
  2100  		t.Fatalf("Unmarshal: %v", err)
  2101  	}
  2102  	if s.B != 1 || s.C != nil {
  2103  		t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C)
  2104  	}
  2105  }
  2106  
  2107  func intp(x int) *int {
  2108  	p := new(int)
  2109  	*p = x
  2110  	return p
  2111  }
  2112  
  2113  func intpp(x *int) **int {
  2114  	pp := new(*int)
  2115  	*pp = x
  2116  	return pp
  2117  }
  2118  
  2119  var interfaceSetTests = []struct {
  2120  	pre  any
  2121  	json string
  2122  	post any
  2123  }{
  2124  	{pre: "foo", json: `"bar"`, post: "bar"},
  2125  	{pre: "foo", json: `2`, post: 2.0},
  2126  	{pre: "foo", json: `true`, post: true},
  2127  	{pre: "foo", json: `null`, post: nil},
  2128  	{pre: nil, json: `null`, post: nil},
  2129  	{pre: new(int), json: `null`, post: nil},
  2130  	{pre: (*int)(nil), json: `null`, post: nil},
  2131  	// {new(*int), `null`, new(*int)},
  2132  	{pre: (**int)(nil), json: `null`, post: nil},
  2133  	{pre: intp(1), json: `null`, post: nil},
  2134  	// {intpp(nil), `null`, intpp(nil)},
  2135  	// {intpp(intp(1)), `null`, intpp(nil)},
  2136  }
  2137  
  2138  func TestInterfaceSet(t *testing.T) {
  2139  	for idx, tt := range interfaceSetTests {
  2140  		b := struct{ X any }{X: tt.pre}
  2141  		blob := `{"X":` + tt.json + `}`
  2142  		if err := json.Unmarshal([]byte(blob), &b); err != nil {
  2143  			t.Errorf("Unmarshal %#q: %v", blob, err)
  2144  			continue
  2145  		}
  2146  		if !reflect.DeepEqual(b.X, tt.post) {
  2147  			t.Errorf("%d: Unmarshal %#q into %#v: X=%#v, want %#v", idx, blob, tt.pre, b.X, tt.post)
  2148  		}
  2149  	}
  2150  }
  2151  
  2152  // JSON null values should be ignored for primitives and string values instead of resulting in an error.
  2153  // Issue 2540
  2154  func TestUnmarshalNulls(t *testing.T) {
  2155  	// Unmarshal docs:
  2156  	// The JSON null value unmarshals into an interface, map, pointer, or slice
  2157  	// by setting that Go value to nil. Because null is often used in JSON to mean
  2158  	// ``not present,'' unmarshaling a JSON null into any other Go type has no effect
  2159  	// on the value and produces no error.
  2160  
  2161  	jsonData := []byte(`{
  2162  				"Bool"    : null,
  2163  				"Int"     : null,
  2164  				"Int8"    : null,
  2165  				"Int16"   : null,
  2166  				"Int32"   : null,
  2167  				"Int64"   : null,
  2168  				"Uint"    : null,
  2169  				"Uint8"   : null,
  2170  				"Uint16"  : null,
  2171  				"Uint32"  : null,
  2172  				"Uint64"  : null,
  2173  				"Float32" : null,
  2174  				"Float64" : null,
  2175  				"String"  : null,
  2176  				"PBool": null,
  2177  				"Map": null,
  2178  				"Slice": null,
  2179  				"Interface": null,
  2180  				"PRaw": null,
  2181  				"PTime": null,
  2182  				"PBigInt": null,
  2183  				"PText": null,
  2184  				"PBuffer": null,
  2185  				"PStruct": null,
  2186  				"Raw": null,
  2187  				"Time": null,
  2188  				"BigInt": null,
  2189  				"Text": null,
  2190  				"Buffer": null,
  2191  				"Struct": null
  2192  			}`)
  2193  	nulls := NullTest{
  2194  		Bool:      true,
  2195  		Int:       2,
  2196  		Int8:      3,
  2197  		Int16:     4,
  2198  		Int32:     5,
  2199  		Int64:     6,
  2200  		Uint:      7,
  2201  		Uint8:     8,
  2202  		Uint16:    9,
  2203  		Uint32:    10,
  2204  		Uint64:    11,
  2205  		Float32:   12.1,
  2206  		Float64:   13.1,
  2207  		String:    "14",
  2208  		PBool:     new(bool),
  2209  		Map:       map[string]string{},
  2210  		Slice:     []string{},
  2211  		Interface: new(MustNotUnmarshalJSON),
  2212  		PRaw:      new(json.RawMessage),
  2213  		PTime:     new(time.Time),
  2214  		PBigInt:   new(big.Int),
  2215  		PText:     new(MustNotUnmarshalText),
  2216  		PStruct:   new(struct{}),
  2217  		PBuffer:   new(bytes.Buffer),
  2218  		Raw:       json.RawMessage("123"),
  2219  		Time:      time.Unix(123456789, 0),
  2220  		BigInt:    *big.NewInt(123),
  2221  	}
  2222  
  2223  	before := nulls.Time.String()
  2224  
  2225  	err := json.Unmarshal(jsonData, &nulls)
  2226  	if err != nil {
  2227  		t.Errorf("Unmarshal of null values failed: %v", err)
  2228  	}
  2229  	if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
  2230  		nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
  2231  		nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
  2232  		t.Errorf("Unmarshal of null values affected primitives")
  2233  	}
  2234  
  2235  	if nulls.PBool != nil {
  2236  		t.Errorf("Unmarshal of null did not clear nulls.PBool")
  2237  	}
  2238  	if nulls.Map != nil {
  2239  		t.Errorf("Unmarshal of null did not clear nulls.Map")
  2240  	}
  2241  	if nulls.Slice != nil {
  2242  		t.Errorf("Unmarshal of null did not clear nulls.Slice")
  2243  	}
  2244  	if nulls.Interface != nil {
  2245  		t.Errorf("Unmarshal of null did not clear nulls.Interface")
  2246  	}
  2247  	if nulls.PRaw != nil {
  2248  		t.Errorf("Unmarshal of null did not clear nulls.PRaw")
  2249  	}
  2250  	if nulls.PTime != nil {
  2251  		t.Errorf("Unmarshal of null did not clear nulls.PTime")
  2252  	}
  2253  	if nulls.PBigInt != nil {
  2254  		t.Errorf("Unmarshal of null did not clear nulls.PBigInt")
  2255  	}
  2256  	if nulls.PText != nil {
  2257  		t.Errorf("Unmarshal of null did not clear nulls.PText")
  2258  	}
  2259  	if nulls.PBuffer != nil {
  2260  		t.Errorf("Unmarshal of null did not clear nulls.PBuffer")
  2261  	}
  2262  	if nulls.PStruct != nil {
  2263  		t.Errorf("Unmarshal of null did not clear nulls.PStruct")
  2264  	}
  2265  
  2266  	if string(nulls.Raw) != "null" {
  2267  		t.Errorf("Unmarshal of RawMessage null did not record null: %v", string(nulls.Raw))
  2268  	}
  2269  	if nulls.Time.String() != before {
  2270  		t.Errorf("Unmarshal of time.Time null set time to %v", nulls.Time.String())
  2271  	}
  2272  	if nulls.BigInt.String() != "123" {
  2273  		t.Errorf("Unmarshal of big.Int null set int to %v", nulls.BigInt.String())
  2274  	}
  2275  }
  2276  
  2277  func TestStringKind(t *testing.T) {
  2278  	type stringKind string
  2279  
  2280  	var m1, m2 map[stringKind]int
  2281  	m1 = map[stringKind]int{
  2282  		"foo": 42,
  2283  	}
  2284  
  2285  	data, err := json.Marshal(m1)
  2286  	if err != nil {
  2287  		t.Errorf("Unexpected error marshaling: %v", err)
  2288  	}
  2289  
  2290  	err = json.Unmarshal(data, &m2)
  2291  	if err != nil {
  2292  		t.Errorf("Unexpected error unmarshaling: %v", err)
  2293  	}
  2294  
  2295  	if !reflect.DeepEqual(m1, m2) {
  2296  		t.Error("Items should be equal after encoding and then decoding")
  2297  	}
  2298  }
  2299  
  2300  // Custom types with []byte as underlying type could not be marshaled
  2301  // and then unmarshaled.
  2302  // Issue 8962.
  2303  func TestByteKind(t *testing.T) {
  2304  	type byteKind []byte
  2305  
  2306  	a := byteKind("hello")
  2307  
  2308  	data, err := json.Marshal(a)
  2309  	if err != nil {
  2310  		t.Error(err)
  2311  	}
  2312  	var b byteKind
  2313  	err = json.Unmarshal(data, &b)
  2314  	if err != nil {
  2315  		t.Fatal(err)
  2316  	}
  2317  	if !reflect.DeepEqual(a, b) {
  2318  		t.Errorf("expected %v == %v", a, b)
  2319  	}
  2320  }
  2321  
  2322  // The fix for issue 8962 introduced a regression.
  2323  // Issue 12921.
  2324  func TestSliceOfCustomByte(t *testing.T) {
  2325  	type Uint8 uint8
  2326  
  2327  	a := []Uint8("hello")
  2328  
  2329  	data, err := json.Marshal(a)
  2330  	if err != nil {
  2331  		t.Fatal(err)
  2332  	}
  2333  	var b []Uint8
  2334  	err = json.Unmarshal(data, &b)
  2335  	if err != nil {
  2336  		t.Fatal(err)
  2337  	}
  2338  	if !reflect.DeepEqual(a, b) {
  2339  		t.Fatalf("expected %v == %v", a, b)
  2340  	}
  2341  }
  2342  
  2343  var decodeTypeErrorTests = []struct {
  2344  	dest any
  2345  	src  string
  2346  }{
  2347  	{dest: new(string), src: `{"user": "name"}`}, // issue 4628.
  2348  	{dest: new(error), src: `{}`},                // issue 4222
  2349  	{dest: new(error), src: `[]`},
  2350  	{dest: new(error), src: `""`},
  2351  	{dest: new(error), src: `123`},
  2352  	{dest: new(error), src: `true`},
  2353  }
  2354  
  2355  func TestUnmarshalTypeError(t *testing.T) {
  2356  	for _, item := range decodeTypeErrorTests {
  2357  		err := json.Unmarshal([]byte(item.src), item.dest)
  2358  		if _, ok := err.(*json.UnmarshalTypeError); !ok {
  2359  			t.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
  2360  				item.src, item.dest, err)
  2361  		}
  2362  	}
  2363  }
  2364  
  2365  var unmarshalSyntaxTests = []string{
  2366  	"tru",
  2367  	"fals",
  2368  	"nul",
  2369  	"123e",
  2370  	`"hello`,
  2371  	`[1,2,3`,
  2372  	`{"key":1`,
  2373  	`{"key":1,`,
  2374  }
  2375  
  2376  func TestUnmarshalSyntax(t *testing.T) {
  2377  	var x any
  2378  	for _, src := range unmarshalSyntaxTests {
  2379  		err := json.Unmarshal([]byte(src), &x)
  2380  		if _, ok := err.(*json.SyntaxError); !ok {
  2381  			t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err)
  2382  		}
  2383  	}
  2384  }
  2385  
  2386  // Test handling of unexported fields that should be ignored.
  2387  // Issue 4660
  2388  type unexportedFields struct {
  2389  	Name string
  2390  	m    map[string]any `json:"-"`
  2391  	m2   map[string]any `json:"abcd"`
  2392  
  2393  	s []int `json:"-"`
  2394  }
  2395  
  2396  func TestUnmarshalUnexported(t *testing.T) {
  2397  	input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}, "s": [2, 3]}`
  2398  	want := &unexportedFields{Name: "Bob"}
  2399  
  2400  	out := &unexportedFields{}
  2401  	err := json.Unmarshal([]byte(input), out)
  2402  	if err != nil {
  2403  		t.Errorf("got error %v, expected nil", err)
  2404  	}
  2405  	if !reflect.DeepEqual(out, want) {
  2406  		t.Errorf("got %q, want %q", out, want)
  2407  	}
  2408  }
  2409  
  2410  // Time3339 is a time.Time which encodes to and from JSON
  2411  // as an RFC 3339 time in UTC.
  2412  type Time3339 time.Time
  2413  
  2414  func (t *Time3339) UnmarshalJSON(b []byte) error {
  2415  	if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
  2416  		return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b)
  2417  	}
  2418  	tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1]))
  2419  	if err != nil {
  2420  		return err
  2421  	}
  2422  	*t = Time3339(tm)
  2423  	return nil
  2424  }
  2425  
  2426  func TestUnmarshalJSONLiteralError(t *testing.T) {
  2427  	var t3 Time3339
  2428  	err := json.Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3)
  2429  	if err == nil {
  2430  		t.Fatalf("expected error; got time %v", time.Time(t3))
  2431  	}
  2432  	if !strings.Contains(err.Error(), "range") {
  2433  		t.Errorf("got err = %v; want out of range error", err)
  2434  	}
  2435  }
  2436  
  2437  // Test that extra object elements in an array do not result in a
  2438  // "data changing underfoot" error.
  2439  // Issue 3717
  2440  func TestSkipArrayObjects(t *testing.T) {
  2441  	data := `[{}]`
  2442  	var dest [0]any
  2443  
  2444  	err := json.Unmarshal([]byte(data), &dest)
  2445  	if err != nil {
  2446  		t.Errorf("got error %q, want nil", err)
  2447  	}
  2448  }
  2449  
  2450  // Test semantics of pre-filled data, such as struct fields, map elements,
  2451  // slices, and arrays.
  2452  // Issues 4900 and 8837, among others.
  2453  func TestPrefilled(t *testing.T) {
  2454  	// Values here change, cannot reuse table across runs.
  2455  	var prefillTests = []struct {
  2456  		in  string
  2457  		ptr any
  2458  		out any
  2459  	}{
  2460  		{
  2461  			in:  `{"X": 1, "Y": 2}`,
  2462  			ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5},
  2463  			out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5},
  2464  		},
  2465  		{
  2466  			in:  `{"X": 1, "Y": 2}`,
  2467  			ptr: &map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5},
  2468  			out: &map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5},
  2469  		},
  2470  		{
  2471  			in:  `[2]`,
  2472  			ptr: &[]int{1},
  2473  			out: &[]int{2},
  2474  		},
  2475  		{
  2476  			in:  `[2, 3]`,
  2477  			ptr: &[]int{1},
  2478  			out: &[]int{2, 3},
  2479  		},
  2480  		{
  2481  			in:  `[2, 3]`,
  2482  			ptr: &[...]int{1},
  2483  			out: &[...]int{2},
  2484  		},
  2485  		{
  2486  			in:  `[3]`,
  2487  			ptr: &[...]int{1, 2},
  2488  			out: &[...]int{3, 0},
  2489  		},
  2490  	}
  2491  
  2492  	for _, tt := range prefillTests {
  2493  		ptrstr := fmt.Sprintf("%v", tt.ptr)
  2494  		err := json.Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here
  2495  		if err != nil {
  2496  			t.Errorf("Unmarshal: %v", err)
  2497  		}
  2498  		if !reflect.DeepEqual(tt.ptr, tt.out) {
  2499  			t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out)
  2500  		}
  2501  	}
  2502  }
  2503  
  2504  var invalidUnmarshalTests = []struct {
  2505  	v    any
  2506  	want string
  2507  }{
  2508  	{v: nil, want: "json: Unmarshal(nil)"},
  2509  	{v: struct{}{}, want: "json: Unmarshal(non-pointer struct {})"},
  2510  	{v: (*int)(nil), want: "json: Unmarshal(nil *int)"},
  2511  }
  2512  
  2513  func TestInvalidUnmarshal(t *testing.T) {
  2514  	buf := []byte(`{"a":"1"}`)
  2515  	for _, tt := range invalidUnmarshalTests {
  2516  		err := json.Unmarshal(buf, tt.v)
  2517  		if err == nil {
  2518  			t.Errorf("Unmarshal expecting error, got nil")
  2519  			continue
  2520  		}
  2521  		if got := err.Error(); got != tt.want {
  2522  			t.Errorf("Unmarshal = %q; want %q", got, tt.want)
  2523  		}
  2524  	}
  2525  }
  2526  
  2527  var invalidUnmarshalTextTests = []struct {
  2528  	v    any
  2529  	want string
  2530  }{
  2531  	{v: nil, want: "json: Unmarshal(nil)"},
  2532  	{v: struct{}{}, want: "json: Unmarshal(non-pointer struct {})"},
  2533  	{v: (*int)(nil), want: "json: Unmarshal(nil *int)"},
  2534  	{v: new(net.IP), want: "json: cannot unmarshal number into Go value of type *net.IP"},
  2535  }
  2536  
  2537  func TestInvalidUnmarshalText(t *testing.T) {
  2538  	buf := []byte(`123`)
  2539  	for _, tt := range invalidUnmarshalTextTests {
  2540  		err := json.Unmarshal(buf, tt.v)
  2541  		if err == nil {
  2542  			t.Errorf("Unmarshal expecting error, got nil")
  2543  			continue
  2544  		}
  2545  		if got := err.Error(); got != tt.want {
  2546  			t.Errorf("Unmarshal = %q; want %q", got, tt.want)
  2547  		}
  2548  	}
  2549  }
  2550  
  2551  // Test that string option is ignored for invalid types.
  2552  // Issue 9812.
  2553  func TestInvalidStringOption(t *testing.T) {
  2554  	num := 0
  2555  	item := struct {
  2556  		T time.Time         `json:",string"`
  2557  		M map[string]string `json:",string"`
  2558  		S []string          `json:",string"`
  2559  		A [1]string         `json:",string"`
  2560  		I any               `json:",string"`
  2561  		P *int              `json:",string"`
  2562  	}{M: make(map[string]string), S: make([]string, 0), I: num, P: &num}
  2563  
  2564  	data, err := json.Marshal(item)
  2565  	if err != nil {
  2566  		t.Fatalf("Marshal: %v", err)
  2567  	}
  2568  	err = json.Unmarshal(data, &item)
  2569  	if err != nil {
  2570  		t.Fatalf("Unmarshal: %v", err)
  2571  	}
  2572  }
  2573  
  2574  // Test unmarshal behavior with regards to embedded unexported structs.
  2575  //
  2576  // (Issue 21357) If the embedded struct is a pointer and is unallocated,
  2577  // this returns an error because unmarshal cannot set the field.
  2578  //
  2579  // (Issue 24152) If the embedded struct is given an explicit name,
  2580  // ensure that the normal unmarshal logic does not panic in reflect.
  2581  //
  2582  // (Issue 28145) If the embedded struct is given an explicit name and has
  2583  // exported methods, don't cause a panic trying to get its value.
  2584  func TestUnmarshalEmbeddedUnexported(t *testing.T) {
  2585  	type (
  2586  		embed1 struct{ Q int }
  2587  		embed2 struct{ Q int }
  2588  		embed3 struct {
  2589  			Q int64 `json:",string"`
  2590  		}
  2591  		S1 struct {
  2592  			*embed1
  2593  			R int
  2594  		}
  2595  		S2 struct {
  2596  			*embed1
  2597  			Q int
  2598  		}
  2599  		S3 struct {
  2600  			embed1
  2601  			R int
  2602  		}
  2603  		S4 struct {
  2604  			*embed1
  2605  			embed2
  2606  		}
  2607  		S5 struct {
  2608  			*embed3
  2609  			R int
  2610  		}
  2611  		S6 struct {
  2612  			embed1 `json:"embed1"`
  2613  		}
  2614  		S7 struct {
  2615  			embed1 `json:"embed1"`
  2616  			embed2
  2617  		}
  2618  		S8 struct {
  2619  			embed1 `json:"embed1"`
  2620  			embed2 `json:"embed2"`
  2621  			Q      int
  2622  		}
  2623  		S9 struct {
  2624  			unexportedWithMethods `json:"embed"`
  2625  		}
  2626  	)
  2627  
  2628  	tests := []struct {
  2629  		in  string
  2630  		ptr any
  2631  		out any
  2632  		err error
  2633  	}{{
  2634  		// Error since we cannot set S1.embed1, but still able to set S1.R.
  2635  		in:  `{"R":2,"Q":1}`,
  2636  		ptr: new(S1),
  2637  		out: &S1{R: 2},
  2638  		err: errors.New("json: cannot set embedded pointer to unexported struct: json_test.embed1"),
  2639  	}, {
  2640  		// The top level Q field takes precedence.
  2641  		in:  `{"Q":1}`,
  2642  		ptr: new(S2),
  2643  		out: &S2{Q: 1},
  2644  	}, {
  2645  		// No issue with non-pointer variant.
  2646  		in:  `{"R":2,"Q":1}`,
  2647  		ptr: new(S3),
  2648  		out: &S3{embed1: embed1{Q: 1}, R: 2},
  2649  	}, {
  2650  		// No error since both embedded structs have field R, which annihilate each other.
  2651  		// Thus, no attempt is made at setting S4.embed1.
  2652  		in:  `{"R":2}`,
  2653  		ptr: new(S4),
  2654  		out: new(S4),
  2655  	}, {
  2656  		// Error since we cannot set S5.embed1, but still able to set S5.R.
  2657  		in:  `{"R":2,"Q":1}`,
  2658  		ptr: new(S5),
  2659  		out: &S5{R: 2},
  2660  		err: errors.New("json: cannot set embedded pointer to unexported struct: json_test.embed3"),
  2661  	}, {
  2662  		// Issue 24152, ensure decodeState.indirect does not panic.
  2663  		in:  `{"embed1": {"Q": 1}}`,
  2664  		ptr: new(S6),
  2665  		out: &S6{embed1: embed1{Q: 1}},
  2666  	}, {
  2667  		// Issue 24153, check that we can still set forwarded fields even in
  2668  		// the presence of a name conflict.
  2669  		//
  2670  		// This relies on obscure behavior of reflect where it is possible
  2671  		// to set a forwarded exported field on an unexported embedded struct
  2672  		// even though there is a name conflict, even when it would have been
  2673  		// impossible to do so according to Go visibility rules.
  2674  		// Go forbids this because it is ambiguous whether S7.Q refers to
  2675  		// S7.embed1.Q or S7.embed2.Q. Since embed1 and embed2 are unexported,
  2676  		// it should be impossible for an external package to set either Q.
  2677  		//
  2678  		// It is probably okay for a future reflect change to break this.
  2679  		in:  `{"embed1": {"Q": 1}, "Q": 2}`,
  2680  		ptr: new(S7),
  2681  		out: &S7{embed1: embed1{Q: 1}, embed2: embed2{Q: 2}},
  2682  	}, {
  2683  		// Issue 24153, similar to the S7 case.
  2684  		in:  `{"embed1": {"Q": 1}, "embed2": {"Q": 2}, "Q": 3}`,
  2685  		ptr: new(S8),
  2686  		out: &S8{embed1: embed1{Q: 1}, embed2: embed2{Q: 2}, Q: 3},
  2687  	}, {
  2688  		// Issue 228145, similar to the cases above.
  2689  		in:  `{"embed": {}}`,
  2690  		ptr: new(S9),
  2691  		out: &S9{},
  2692  	}}
  2693  
  2694  	for i, tt := range tests {
  2695  		err := json.Unmarshal([]byte(tt.in), tt.ptr)
  2696  		if !equalError(err, tt.err) {
  2697  			t.Errorf("#%d: %v, want %v", i, err, tt.err)
  2698  		}
  2699  		if !reflect.DeepEqual(tt.ptr, tt.out) {
  2700  			t.Errorf("#%d: mismatch\ngot:  %#+v\nwant: %#+v", i, tt.ptr, tt.out)
  2701  		}
  2702  	}
  2703  }
  2704  
  2705  func TestUnmarshalErrorAfterMultipleJSON(t *testing.T) {
  2706  	tests := []struct {
  2707  		in  string
  2708  		err error
  2709  	}{{
  2710  		in:  `1 false null :`,
  2711  		err: json.NewSyntaxError("invalid character '\x00' looking for beginning of value", 14),
  2712  	}, {
  2713  		in:  `1 [] [,]`,
  2714  		err: json.NewSyntaxError("invalid character ',' looking for beginning of value", 6),
  2715  	}, {
  2716  		in:  `1 [] [true:]`,
  2717  		err: json.NewSyntaxError("json: slice unexpected end of JSON input", 10),
  2718  	}, {
  2719  		in:  `1  {}    {"x"=}`,
  2720  		err: json.NewSyntaxError("expected colon after object key", 13),
  2721  	}, {
  2722  		in:  `falsetruenul#`,
  2723  		err: json.NewSyntaxError("json: invalid character # as null", 12),
  2724  	}}
  2725  	for i, tt := range tests {
  2726  		dec := json.NewDecoder(strings.NewReader(tt.in))
  2727  		var err error
  2728  		for {
  2729  			var v any
  2730  			if err = dec.Decode(&v); err != nil {
  2731  				break
  2732  			}
  2733  		}
  2734  		if !reflect.DeepEqual(err, tt.err) {
  2735  			t.Errorf("#%d: got %#v, want %#v", i, err, tt.err)
  2736  		}
  2737  	}
  2738  }
  2739  
  2740  type unmarshalPanic struct{}
  2741  
  2742  func (unmarshalPanic) UnmarshalJSON([]byte) error { panic(0xdead) }
  2743  
  2744  func TestUnmarshalPanic(t *testing.T) {
  2745  	defer func() {
  2746  		if got := recover(); !reflect.DeepEqual(got, 0xdead) {
  2747  			t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
  2748  		}
  2749  	}()
  2750  	json.Unmarshal([]byte("{}"), &unmarshalPanic{})
  2751  	t.Fatalf("Unmarshal should have panicked")
  2752  }
  2753  
  2754  // The decoder used to hang if decoding into an interface pointing to its own address.
  2755  // See golang.org/issues/31740.
  2756  func TestUnmarshalRecursivePointer(t *testing.T) {
  2757  	var v any
  2758  	v = &v
  2759  	data := []byte(`{"a": "b"}`)
  2760  
  2761  	if err := json.Unmarshal(data, v); err != nil {
  2762  		t.Fatal(err)
  2763  	}
  2764  }
  2765  
  2766  type textUnmarshalerString string
  2767  
  2768  func (m *textUnmarshalerString) UnmarshalText(text []byte) error {
  2769  	*m = textUnmarshalerString(strings.ToLower(string(text)))
  2770  	return nil
  2771  }
  2772  
  2773  // Test unmarshal to a map, where the map key is a user defined type.
  2774  // See golang.org/issues/34437.
  2775  func TestUnmarshalMapWithTextUnmarshalerStringKey(t *testing.T) {
  2776  	var p map[textUnmarshalerString]string
  2777  	if err := json.Unmarshal([]byte(`{"FOO": "1"}`), &p); err != nil {
  2778  		t.Fatalf("Unmarshal unexpected error: %v", err)
  2779  	}
  2780  
  2781  	if _, ok := p["foo"]; !ok {
  2782  		t.Errorf(`Key "foo" does not exist in map: %v`, p)
  2783  	}
  2784  }
  2785  
  2786  func TestUnmarshalRescanLiteralMangledUnquote(t *testing.T) {
  2787  	// See golang.org/issues/38105.
  2788  	var p map[textUnmarshalerString]string
  2789  	if err := json.Unmarshal([]byte(`{"开源":"12345开源"}`), &p); err != nil {
  2790  		t.Fatalf("Unmarshal unexpected error: %v", err)
  2791  	}
  2792  	if _, ok := p["开源"]; !ok {
  2793  		t.Errorf(`Key "开源" does not exist in map: %v`, p)
  2794  	}
  2795  
  2796  	// See golang.org/issues/38126.
  2797  	type T struct {
  2798  		F1 string `json:"F1,string"`
  2799  	}
  2800  	t1 := T{F1: "aaa\tbbb"}
  2801  
  2802  	b, err := json.Marshal(t1)
  2803  	if err != nil {
  2804  		t.Fatalf("Marshal unexpected error: %v", err)
  2805  	}
  2806  	var t2 T
  2807  	if err := json.Unmarshal(b, &t2); err != nil {
  2808  		t.Fatalf("Unmarshal unexpected error: %v", err)
  2809  	}
  2810  	if t1 != t2 {
  2811  		t.Errorf("Marshal and Unmarshal roundtrip mismatch: want %q got %q", t1, t2)
  2812  	}
  2813  
  2814  	// See golang.org/issues/39555.
  2815  	input := map[textUnmarshalerString]string{"FOO": "", `"`: ""}
  2816  
  2817  	encoded, err := json.Marshal(input)
  2818  	if err != nil {
  2819  		t.Fatalf("Marshal unexpected error: %v", err)
  2820  	}
  2821  	var got map[textUnmarshalerString]string
  2822  	if err := json.Unmarshal(encoded, &got); err != nil {
  2823  		t.Fatalf("Unmarshal unexpected error: %v", err)
  2824  	}
  2825  	want := map[textUnmarshalerString]string{"foo": "", `"`: ""}
  2826  	if !reflect.DeepEqual(want, got) {
  2827  		t.Fatalf("Unexpected roundtrip result:\nwant: %q\ngot:  %q", want, got)
  2828  	}
  2829  }
  2830  
  2831  func TestUnmarshalMaxDepth(t *testing.T) {
  2832  	testcases := []struct {
  2833  		name        string
  2834  		data        string
  2835  		errMaxDepth bool
  2836  	}{
  2837  		{
  2838  			name:        "ArrayUnderMaxNestingDepth",
  2839  			data:        `{"a":` + strings.Repeat(`[`, 10000-1) + strings.Repeat(`]`, 10000-1) + `}`,
  2840  			errMaxDepth: false,
  2841  		},
  2842  		{
  2843  			name:        "ArrayOverMaxNestingDepth",
  2844  			data:        `{"a":` + strings.Repeat(`[`, 10000) + strings.Repeat(`]`, 10000) + `}`,
  2845  			errMaxDepth: true,
  2846  		},
  2847  		{
  2848  			name:        "ArrayOverStackDepth",
  2849  			data:        `{"a":` + strings.Repeat(`[`, 3000000) + strings.Repeat(`]`, 3000000) + `}`,
  2850  			errMaxDepth: true,
  2851  		},
  2852  		{
  2853  			name:        "ObjectUnderMaxNestingDepth",
  2854  			data:        `{"a":` + strings.Repeat(`{"a":`, 10000-1) + `0` + strings.Repeat(`}`, 10000-1) + `}`,
  2855  			errMaxDepth: false,
  2856  		},
  2857  		{
  2858  			name:        "ObjectOverMaxNestingDepth",
  2859  			data:        `{"a":` + strings.Repeat(`{"a":`, 10000) + `0` + strings.Repeat(`}`, 10000) + `}`,
  2860  			errMaxDepth: true,
  2861  		},
  2862  		{
  2863  			name:        "ObjectOverStackDepth",
  2864  			data:        `{"a":` + strings.Repeat(`{"a":`, 3000000) + `0` + strings.Repeat(`}`, 3000000) + `}`,
  2865  			errMaxDepth: true,
  2866  		},
  2867  	}
  2868  
  2869  	targets := []struct {
  2870  		name     string
  2871  		newValue func() any
  2872  	}{
  2873  		{
  2874  			name: "unstructured",
  2875  			newValue: func() any {
  2876  				var v any
  2877  				return &v
  2878  			},
  2879  		},
  2880  		{
  2881  			name: "typed named field",
  2882  			newValue: func() any {
  2883  				v := struct {
  2884  					A any `json:"a"`
  2885  				}{}
  2886  				return &v
  2887  			},
  2888  		},
  2889  		{
  2890  			name: "typed missing field",
  2891  			newValue: func() any {
  2892  				v := struct {
  2893  					B any `json:"b"`
  2894  				}{}
  2895  				return &v
  2896  			},
  2897  		},
  2898  		{
  2899  			name: "custom unmarshaler",
  2900  			newValue: func() any {
  2901  				v := unmarshaler{}
  2902  				return &v
  2903  			},
  2904  		},
  2905  	}
  2906  
  2907  	for _, tc := range testcases {
  2908  		for _, target := range targets {
  2909  			t.Run(target.name+"-"+tc.name, func(t *testing.T) {
  2910  				t.Run("unmarshal", func(t *testing.T) {
  2911  					err := json.Unmarshal([]byte(tc.data), target.newValue())
  2912  					if !tc.errMaxDepth {
  2913  						if err != nil {
  2914  							t.Errorf("unexpected error: %v", err)
  2915  						}
  2916  					} else {
  2917  						if err == nil {
  2918  							t.Errorf("expected error containing 'exceeded max depth', got none")
  2919  						} else if !strings.Contains(err.Error(), "exceeded max depth") {
  2920  							t.Errorf("expected error containing 'exceeded max depth', got: %v", err)
  2921  						}
  2922  					}
  2923  				})
  2924  				t.Run("stream", func(t *testing.T) {
  2925  					err := json.NewDecoder(strings.NewReader(tc.data)).Decode(target.newValue())
  2926  					if !tc.errMaxDepth {
  2927  						if err != nil {
  2928  							t.Errorf("unexpected error: %v", err)
  2929  						}
  2930  					} else {
  2931  						if err == nil {
  2932  							t.Errorf("expected error containing 'exceeded max depth', got none")
  2933  						} else if !strings.Contains(err.Error(), "exceeded max depth") {
  2934  							t.Errorf("expected error containing 'exceeded max depth', got: %v", err)
  2935  						}
  2936  					}
  2937  				})
  2938  			})
  2939  		}
  2940  	}
  2941  }
  2942  
  2943  func TestDecodeSlice(t *testing.T) {
  2944  	type B struct{ Int int32 }
  2945  	type A struct{ B *B }
  2946  	type X struct{ A []*A }
  2947  
  2948  	w1 := &X{}
  2949  	w2 := &X{}
  2950  
  2951  	if err := json.Unmarshal([]byte(`{"a": [ {"b":{"int": 42} } ] }`), w1); err != nil {
  2952  		t.Fatal(err)
  2953  	}
  2954  	w1addr := uintptr(unsafe.Pointer(w1.A[0].B))
  2955  
  2956  	if err := json.Unmarshal([]byte(`{"a": [ {"b":{"int": 112} } ] }`), w2); err != nil {
  2957  		t.Fatal(err)
  2958  	}
  2959  	if uintptr(unsafe.Pointer(w1.A[0].B)) != w1addr {
  2960  		t.Fatal("wrong addr")
  2961  	}
  2962  	w2addr := uintptr(unsafe.Pointer(w2.A[0].B))
  2963  	if w1addr == w2addr {
  2964  		t.Fatal("invaid address")
  2965  	}
  2966  }
  2967  
  2968  func TestDecodeMultipleUnmarshal(t *testing.T) {
  2969  	data := []byte(`[{"AA":{"X":[{"a": "A"},{"b": "B"}],"Y":"y","Z":"z"},"BB":"bb"},{"AA":{"X":[],"Y":"y","Z":"z"},"BB":"bb"}]`)
  2970  	var a []json.RawMessage
  2971  	if err := json.Unmarshal(data, &a); err != nil {
  2972  		t.Fatal(err)
  2973  	}
  2974  	if len(a) != 2 {
  2975  		t.Fatalf("failed to decode: got %v", a)
  2976  	}
  2977  	t.Run("first", func(t *testing.T) {
  2978  		data := a[0]
  2979  		var v map[string]json.RawMessage
  2980  		if err := json.Unmarshal(data, &v); err != nil {
  2981  			t.Fatal(err)
  2982  		}
  2983  		if string(v["AA"]) != `{"X":[{"a": "A"},{"b": "B"}],"Y":"y","Z":"z"}` {
  2984  			t.Fatalf("failed to decode. got %q", v["AA"])
  2985  		}
  2986  		var aa map[string]json.RawMessage
  2987  		if err := json.Unmarshal(v["AA"], &aa); err != nil {
  2988  			t.Fatal(err)
  2989  		}
  2990  		if string(aa["X"]) != `[{"a": "A"},{"b": "B"}]` {
  2991  			t.Fatalf("failed to decode. got %q", v["X"])
  2992  		}
  2993  		var x []json.RawMessage
  2994  		if err := json.Unmarshal(aa["X"], &x); err != nil {
  2995  			t.Fatal(err)
  2996  		}
  2997  		if len(x) != 2 {
  2998  			t.Fatalf("failed to decode: %v", x)
  2999  		}
  3000  		if string(x[0]) != `{"a": "A"}` {
  3001  			t.Fatal("failed to decode")
  3002  		}
  3003  		if string(x[1]) != `{"b": "B"}` {
  3004  			t.Fatal("failed to decode")
  3005  		}
  3006  	})
  3007  	t.Run("second", func(t *testing.T) {
  3008  		data := a[1]
  3009  		var v map[string]json.RawMessage
  3010  		if err := json.Unmarshal(data, &v); err != nil {
  3011  			t.Fatal(err)
  3012  		}
  3013  		if string(v["AA"]) != `{"X":[],"Y":"y","Z":"z"}` {
  3014  			t.Fatalf("failed to decode. got %q", v["AA"])
  3015  		}
  3016  		var aa map[string]json.RawMessage
  3017  		if err := json.Unmarshal(v["AA"], &aa); err != nil {
  3018  			t.Fatal(err)
  3019  		}
  3020  		if string(aa["X"]) != `[]` {
  3021  			t.Fatalf("failed to decode. got %q", v["X"])
  3022  		}
  3023  		var x []json.RawMessage
  3024  		if err := json.Unmarshal(aa["X"], &x); err != nil {
  3025  			t.Fatal(err)
  3026  		}
  3027  		if len(x) != 0 {
  3028  			t.Fatalf("failed to decode: %v", x)
  3029  		}
  3030  	})
  3031  }
  3032  
  3033  func TestMultipleDecodeWithRawMessage(t *testing.T) {
  3034  	original := []byte(`{
  3035  		"Body": {
  3036  			"List": [
  3037  				{
  3038  					"Returns": [
  3039  						{
  3040  							"Value": "10",
  3041  							"nodeType": "Literal"
  3042  						}
  3043  					],
  3044  					"nodeKind": "Return",
  3045  					"nodeType": "Statement"
  3046  				}
  3047  			],
  3048  			"nodeKind": "Block",
  3049  			"nodeType": "Statement"
  3050  		},
  3051  		"nodeType": "Function"
  3052  	}`)
  3053  
  3054  	var a map[string]json.RawMessage
  3055  	if err := json.Unmarshal(original, &a); err != nil {
  3056  		t.Fatal(err)
  3057  	}
  3058  	var b map[string]json.RawMessage
  3059  	if err := json.Unmarshal(a["Body"], &b); err != nil {
  3060  		t.Fatal(err)
  3061  	}
  3062  	var c []json.RawMessage
  3063  	if err := json.Unmarshal(b["List"], &c); err != nil {
  3064  		t.Fatal(err)
  3065  	}
  3066  	var d map[string]json.RawMessage
  3067  	if err := json.Unmarshal(c[0], &d); err != nil {
  3068  		t.Fatal(err)
  3069  	}
  3070  	var e []json.RawMessage
  3071  	if err := json.Unmarshal(d["Returns"], &e); err != nil {
  3072  		t.Fatal(err)
  3073  	}
  3074  	var f map[string]json.RawMessage
  3075  	if err := json.Unmarshal(e[0], &f); err != nil {
  3076  		t.Fatal(err)
  3077  	}
  3078  }
  3079  
  3080  type intUnmarshaler int
  3081  
  3082  func (u *intUnmarshaler) UnmarshalJSON(b []byte) error {
  3083  	if *u != 0 && *u != 10 {
  3084  		return errors.New("failed to decode of slice with int unmarshaler")
  3085  	}
  3086  	*u = 10
  3087  	return nil
  3088  }
  3089  
  3090  type arrayUnmarshaler [5]int
  3091  
  3092  func (u *arrayUnmarshaler) UnmarshalJSON(b []byte) error {
  3093  	if (*u)[0] != 0 && (*u)[0] != 10 {
  3094  		return errors.New("failed to decode of slice with array unmarshaler")
  3095  	}
  3096  	(*u)[0] = 10
  3097  	return nil
  3098  }
  3099  
  3100  type mapUnmarshaler map[string]int
  3101  
  3102  func (u *mapUnmarshaler) UnmarshalJSON(b []byte) error {
  3103  	if len(*u) != 0 && len(*u) != 1 {
  3104  		return errors.New("failed to decode of slice with map unmarshaler")
  3105  	}
  3106  	*u = map[string]int{"a": 10}
  3107  	return nil
  3108  }
  3109  
  3110  type structUnmarshaler struct {
  3111  	A        int
  3112  	notFirst bool
  3113  }
  3114  
  3115  func (u *structUnmarshaler) UnmarshalJSON(b []byte) error {
  3116  	if !u.notFirst && u.A != 0 {
  3117  		return errors.New("failed to decode of slice with struct unmarshaler")
  3118  	}
  3119  	u.A = 10
  3120  	u.notFirst = true
  3121  	return nil
  3122  }
  3123  
  3124  func TestSliceElemUnmarshaler(t *testing.T) {
  3125  	t.Run("int", func(t *testing.T) {
  3126  		var v []intUnmarshaler
  3127  		if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil {
  3128  			t.Fatal(err)
  3129  		}
  3130  		if len(v) != 5 {
  3131  			t.Fatalf("failed to decode of slice with int unmarshaler: %v", v)
  3132  		}
  3133  		if v[0] != 10 {
  3134  			t.Fatalf("failed to decode of slice with int unmarshaler: %v", v)
  3135  		}
  3136  		if err := json.Unmarshal([]byte(`[6]`), &v); err != nil {
  3137  			t.Fatal(err)
  3138  		}
  3139  		if len(v) != 1 {
  3140  			t.Fatalf("failed to decode of slice with int unmarshaler: %v", v)
  3141  		}
  3142  		if v[0] != 10 {
  3143  			t.Fatalf("failed to decode of slice with int unmarshaler: %v", v)
  3144  		}
  3145  	})
  3146  	t.Run("slice", func(t *testing.T) {
  3147  		var v []json.RawMessage
  3148  		if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil {
  3149  			t.Fatal(err)
  3150  		}
  3151  		if len(v) != 5 {
  3152  			t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v)
  3153  		}
  3154  		if len(v[0]) != 1 {
  3155  			t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v)
  3156  		}
  3157  		if err := json.Unmarshal([]byte(`[6]`), &v); err != nil {
  3158  			t.Fatal(err)
  3159  		}
  3160  		if len(v) != 1 {
  3161  			t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v)
  3162  		}
  3163  		if len(v[0]) != 1 {
  3164  			t.Fatalf("failed to decode of slice with slice unmarshaler: %v", v)
  3165  		}
  3166  	})
  3167  	t.Run("array", func(t *testing.T) {
  3168  		var v []arrayUnmarshaler
  3169  		if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil {
  3170  			t.Fatal(err)
  3171  		}
  3172  		if len(v) != 5 {
  3173  			t.Fatalf("failed to decode of slice with array unmarshaler: %v", v)
  3174  		}
  3175  		if v[0][0] != 10 {
  3176  			t.Fatalf("failed to decode of slice with array unmarshaler: %v", v)
  3177  		}
  3178  		if err := json.Unmarshal([]byte(`[6]`), &v); err != nil {
  3179  			t.Fatal(err)
  3180  		}
  3181  		if len(v) != 1 {
  3182  			t.Fatalf("failed to decode of slice with array unmarshaler: %v", v)
  3183  		}
  3184  		if v[0][0] != 10 {
  3185  			t.Fatalf("failed to decode of slice with array unmarshaler: %v", v)
  3186  		}
  3187  	})
  3188  	t.Run("map", func(t *testing.T) {
  3189  		var v []mapUnmarshaler
  3190  		if err := json.Unmarshal([]byte(`[{"a":1},{"b":2},{"c":3},{"d":4},{"e":5}]`), &v); err != nil {
  3191  			t.Fatal(err)
  3192  		}
  3193  		if len(v) != 5 {
  3194  			t.Fatalf("failed to decode of slice with map unmarshaler: %v", v)
  3195  		}
  3196  		if v[0]["a"] != 10 {
  3197  			t.Fatalf("failed to decode of slice with map unmarshaler: %v", v)
  3198  		}
  3199  		if err := json.Unmarshal([]byte(`[6]`), &v); err != nil {
  3200  			t.Fatal(err)
  3201  		}
  3202  		if len(v) != 1 {
  3203  			t.Fatalf("failed to decode of slice with map unmarshaler: %v", v)
  3204  		}
  3205  		if v[0]["a"] != 10 {
  3206  			t.Fatalf("failed to decode of slice with map unmarshaler: %v", v)
  3207  		}
  3208  	})
  3209  	t.Run("struct", func(t *testing.T) {
  3210  		var v []structUnmarshaler
  3211  		if err := json.Unmarshal([]byte(`[1,2,3,4,5]`), &v); err != nil {
  3212  			t.Fatal(err)
  3213  		}
  3214  		if len(v) != 5 {
  3215  			t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v)
  3216  		}
  3217  		if v[0].A != 10 {
  3218  			t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v)
  3219  		}
  3220  		if err := json.Unmarshal([]byte(`[6]`), &v); err != nil {
  3221  			t.Fatal(err)
  3222  		}
  3223  		if len(v) != 1 {
  3224  			t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v)
  3225  		}
  3226  		if v[0].A != 10 {
  3227  			t.Fatalf("failed to decode of slice with struct unmarshaler: %v", v)
  3228  		}
  3229  	})
  3230  }
  3231  
  3232  type keepRefTest struct {
  3233  	A int
  3234  	B string
  3235  }
  3236  
  3237  func (t *keepRefTest) UnmarshalJSON(data []byte) error {
  3238  	v := []any{&t.A, &t.B}
  3239  	return json.Unmarshal(data, &v)
  3240  }
  3241  
  3242  func TestKeepReferenceSlice(t *testing.T) {
  3243  	var v keepRefTest
  3244  	if err := json.Unmarshal([]byte(`[54,"hello"]`), &v); err != nil {
  3245  		t.Fatal(err)
  3246  	}
  3247  	if v.A != 54 {
  3248  		t.Fatal("failed to keep reference for slice")
  3249  	}
  3250  	if v.B != "hello" {
  3251  		t.Fatal("failed to keep reference for slice")
  3252  	}
  3253  }
  3254  
  3255  func TestInvalidTopLevelValue(t *testing.T) {
  3256  	t.Run("invalid end of buffer", func(t *testing.T) {
  3257  		var v struct{}
  3258  		if err := stdjson.Unmarshal([]byte(`{}0`), &v); err == nil {
  3259  			t.Fatal("expected error")
  3260  		}
  3261  		if err := json.Unmarshal([]byte(`{}0`), &v); err == nil {
  3262  			t.Fatal("expected error")
  3263  		}
  3264  	})
  3265  	t.Run("invalid object", func(t *testing.T) {
  3266  		var v any
  3267  		if err := stdjson.Unmarshal([]byte(`{"a":4}{"a"5}`), &v); err == nil {
  3268  			t.Fatal("expected error")
  3269  		}
  3270  		if err := json.Unmarshal([]byte(`{"a":4}{"a"5}`), &v); err == nil {
  3271  			t.Fatal("expected error")
  3272  		}
  3273  	})
  3274  }
  3275  
  3276  func TestInvalidNumber(t *testing.T) {
  3277  	t.Run("invalid length of number", func(t *testing.T) {
  3278  		invalidNum := strings.Repeat("1", 30)
  3279  		t.Run("int", func(t *testing.T) {
  3280  			var v int64
  3281  			stdErr := stdjson.Unmarshal([]byte(invalidNum), &v)
  3282  			if stdErr == nil {
  3283  				t.Fatal("expected error")
  3284  			}
  3285  			err := json.Unmarshal([]byte(invalidNum), &v)
  3286  			if err == nil {
  3287  				t.Fatal("expected error")
  3288  			}
  3289  			if stdErr.Error() != err.Error() {
  3290  				t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error())
  3291  			}
  3292  		})
  3293  		t.Run("uint", func(t *testing.T) {
  3294  			var v uint64
  3295  			stdErr := stdjson.Unmarshal([]byte(invalidNum), &v)
  3296  			if stdErr == nil {
  3297  				t.Fatal("expected error")
  3298  			}
  3299  			err := json.Unmarshal([]byte(invalidNum), &v)
  3300  			if err == nil {
  3301  				t.Fatal("expected error")
  3302  			}
  3303  			if stdErr.Error() != err.Error() {
  3304  				t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error())
  3305  			}
  3306  		})
  3307  	})
  3308  	t.Run("invalid number of zero", func(t *testing.T) {
  3309  		t.Run("int", func(t *testing.T) {
  3310  			invalidNum := strings.Repeat("0", 10)
  3311  			var v int64
  3312  			stdErr := stdjson.Unmarshal([]byte(invalidNum), &v)
  3313  			if stdErr == nil {
  3314  				t.Fatal("expected error")
  3315  			}
  3316  			err := json.Unmarshal([]byte(invalidNum), &v)
  3317  			if err == nil {
  3318  				t.Fatal("expected error")
  3319  			}
  3320  			if stdErr.Error() != err.Error() {
  3321  				t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error())
  3322  			}
  3323  		})
  3324  		t.Run("uint", func(t *testing.T) {
  3325  			invalidNum := strings.Repeat("0", 10)
  3326  			var v uint64
  3327  			stdErr := stdjson.Unmarshal([]byte(invalidNum), &v)
  3328  			if stdErr == nil {
  3329  				t.Fatal("expected error")
  3330  			}
  3331  			err := json.Unmarshal([]byte(invalidNum), &v)
  3332  			if err == nil {
  3333  				t.Fatal("expected error")
  3334  			}
  3335  			if stdErr.Error() != err.Error() {
  3336  				t.Fatalf("unexpected error message. expected: %q but got %q", stdErr.Error(), err.Error())
  3337  			}
  3338  		})
  3339  	})
  3340  	t.Run("invalid number", func(t *testing.T) {
  3341  		t.Run("int", func(t *testing.T) {
  3342  			t.Run("-0", func(t *testing.T) {
  3343  				var v int64
  3344  				if err := stdjson.Unmarshal([]byte(`-0`), &v); err != nil {
  3345  					t.Fatal(err)
  3346  				}
  3347  				if err := json.Unmarshal([]byte(`-0`), &v); err != nil {
  3348  					t.Fatal(err)
  3349  				}
  3350  			})
  3351  			t.Run("+0", func(t *testing.T) {
  3352  				var v int64
  3353  				if err := stdjson.Unmarshal([]byte(`+0`), &v); err == nil {
  3354  					t.Error("expected error")
  3355  				}
  3356  				if err := json.Unmarshal([]byte(`+0`), &v); err == nil {
  3357  					t.Error("expected error")
  3358  				}
  3359  			})
  3360  		})
  3361  		t.Run("uint", func(t *testing.T) {
  3362  			t.Run("-0", func(t *testing.T) {
  3363  				var v uint64
  3364  				if err := stdjson.Unmarshal([]byte(`-0`), &v); err == nil {
  3365  					t.Error("expected error")
  3366  				}
  3367  				if err := json.Unmarshal([]byte(`-0`), &v); err == nil {
  3368  					t.Error("expected error")
  3369  				}
  3370  			})
  3371  			t.Run("+0", func(t *testing.T) {
  3372  				var v uint64
  3373  				if err := stdjson.Unmarshal([]byte(`+0`), &v); err == nil {
  3374  					t.Error("expected error")
  3375  				}
  3376  				if err := json.Unmarshal([]byte(`+0`), &v); err == nil {
  3377  					t.Error("expected error")
  3378  				}
  3379  			})
  3380  		})
  3381  		t.Run("float", func(t *testing.T) {
  3382  			t.Run("0.0", func(t *testing.T) {
  3383  				var f float64
  3384  				if err := stdjson.Unmarshal([]byte(`0.0`), &f); err != nil {
  3385  					t.Fatal(err)
  3386  				}
  3387  				if err := json.Unmarshal([]byte(`0.0`), &f); err != nil {
  3388  					t.Fatal(err)
  3389  				}
  3390  			})
  3391  			t.Run("0.000000000", func(t *testing.T) {
  3392  				var f float64
  3393  				if err := stdjson.Unmarshal([]byte(`0.000000000`), &f); err != nil {
  3394  					t.Fatal(err)
  3395  				}
  3396  				if err := json.Unmarshal([]byte(`0.000000000`), &f); err != nil {
  3397  					t.Fatal(err)
  3398  				}
  3399  			})
  3400  			t.Run("repeat zero a lot with float value", func(t *testing.T) {
  3401  				var f float64
  3402  				if err := stdjson.Unmarshal([]byte("0."+strings.Repeat("0", 30)), &f); err != nil {
  3403  					t.Fatal(err)
  3404  				}
  3405  				if err := json.Unmarshal([]byte("0."+strings.Repeat("0", 30)), &f); err != nil {
  3406  					t.Fatal(err)
  3407  				}
  3408  			})
  3409  		})
  3410  	})
  3411  }
  3412  
  3413  type someInterface interface {
  3414  	DoesNotMatter()
  3415  }
  3416  
  3417  func TestDecodeUnknownInterface(t *testing.T) {
  3418  	t.Run("unmarshal", func(t *testing.T) {
  3419  		var v map[string]someInterface
  3420  		if err := json.Unmarshal([]byte(`{"a":null,"b":null}`), &v); err != nil {
  3421  			t.Fatal(err)
  3422  		}
  3423  		if len(v) != 2 {
  3424  			t.Fatalf("failed to decode: %v", v)
  3425  		}
  3426  		if a, exists := v["a"]; a != nil || !exists {
  3427  			t.Fatalf("failed to decode: %v", v)
  3428  		}
  3429  		if b, exists := v["b"]; b != nil || !exists {
  3430  			t.Fatalf("failed to decode: %v", v)
  3431  		}
  3432  	})
  3433  	t.Run("stream", func(t *testing.T) {
  3434  		var v map[string]someInterface
  3435  		if err := json.NewDecoder(strings.NewReader(`{"a":null,"b":null}`)).Decode(&v); err != nil {
  3436  			t.Fatal(err)
  3437  		}
  3438  		if len(v) != 2 {
  3439  			t.Fatalf("failed to decode: %v", v)
  3440  		}
  3441  		if a, exists := v["a"]; a != nil || !exists {
  3442  			t.Fatalf("failed to decode: %v", v)
  3443  		}
  3444  		if b, exists := v["b"]; b != nil || !exists {
  3445  			t.Fatalf("failed to decode: %v", v)
  3446  		}
  3447  	})
  3448  }
  3449  
  3450  func TestDecodeByteSliceNull(t *testing.T) {
  3451  	t.Run("unmarshal", func(t *testing.T) {
  3452  		var v1 []byte
  3453  		if err := stdjson.Unmarshal([]byte(`null`), &v1); err != nil {
  3454  			t.Fatal(err)
  3455  		}
  3456  		var v2 []byte
  3457  		if err := json.Unmarshal([]byte(`null`), &v2); err != nil {
  3458  			t.Fatal(err)
  3459  		}
  3460  		if v1 == nil && v2 != nil || len(v1) != len(v2) {
  3461  			t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2)
  3462  		}
  3463  	})
  3464  	t.Run("stream", func(t *testing.T) {
  3465  		var v1 []byte
  3466  		if err := stdjson.NewDecoder(strings.NewReader(`null`)).Decode(&v1); err != nil {
  3467  			t.Fatal(err)
  3468  		}
  3469  		var v2 []byte
  3470  		if err := json.NewDecoder(strings.NewReader(`null`)).Decode(&v2); err != nil {
  3471  			t.Fatal(err)
  3472  		}
  3473  		if v1 == nil && v2 != nil || len(v1) != len(v2) {
  3474  			t.Fatalf("failed to decode null to []byte. expected:%#v but got %#v", v1, v2)
  3475  		}
  3476  	})
  3477  }
  3478  
  3479  func TestDecodeBackSlash(t *testing.T) {
  3480  	t.Run("unmarshal", func(t *testing.T) {
  3481  		t.Run("string", func(t *testing.T) {
  3482  			var v1 map[string]stdjson.RawMessage
  3483  			if err := stdjson.Unmarshal([]byte(`{"c":"\\"}`), &v1); err != nil {
  3484  				t.Fatal(err)
  3485  			}
  3486  			var v2 map[string]json.RawMessage
  3487  			if err := json.Unmarshal([]byte(`{"c":"\\"}`), &v2); err != nil {
  3488  				t.Fatal(err)
  3489  			}
  3490  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3491  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3492  			}
  3493  		})
  3494  		t.Run("array", func(t *testing.T) {
  3495  			var v1 map[string]stdjson.RawMessage
  3496  			if err := stdjson.Unmarshal([]byte(`{"c":["\\"]}`), &v1); err != nil {
  3497  				t.Fatal(err)
  3498  			}
  3499  			var v2 map[string]json.RawMessage
  3500  			if err := json.Unmarshal([]byte(`{"c":["\\"]}`), &v2); err != nil {
  3501  				t.Fatal(err)
  3502  			}
  3503  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3504  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3505  			}
  3506  		})
  3507  		t.Run("object", func(t *testing.T) {
  3508  			var v1 map[string]stdjson.RawMessage
  3509  			if err := stdjson.Unmarshal([]byte(`{"c":{"\\":"\\"}}`), &v1); err != nil {
  3510  				t.Fatal(err)
  3511  			}
  3512  			var v2 map[string]json.RawMessage
  3513  			if err := json.Unmarshal([]byte(`{"c":{"\\":"\\"}}`), &v2); err != nil {
  3514  				t.Fatal(err)
  3515  			}
  3516  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3517  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3518  			}
  3519  		})
  3520  	})
  3521  	t.Run("stream", func(t *testing.T) {
  3522  		t.Run("string", func(t *testing.T) {
  3523  			var v1 map[string]stdjson.RawMessage
  3524  			if err := stdjson.NewDecoder(strings.NewReader(`{"c":"\\"}`)).Decode(&v1); err != nil {
  3525  				t.Fatal(err)
  3526  			}
  3527  			var v2 map[string]json.RawMessage
  3528  			if err := json.NewDecoder(strings.NewReader(`{"c":"\\"}`)).Decode(&v2); err != nil {
  3529  				t.Fatal(err)
  3530  			}
  3531  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3532  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3533  			}
  3534  		})
  3535  		t.Run("array", func(t *testing.T) {
  3536  			var v1 map[string]stdjson.RawMessage
  3537  			if err := stdjson.NewDecoder(strings.NewReader(`{"c":["\\"]}`)).Decode(&v1); err != nil {
  3538  				t.Fatal(err)
  3539  			}
  3540  			var v2 map[string]json.RawMessage
  3541  			if err := json.NewDecoder(strings.NewReader(`{"c":["\\"]}`)).Decode(&v2); err != nil {
  3542  				t.Fatal(err)
  3543  			}
  3544  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3545  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3546  			}
  3547  		})
  3548  		t.Run("object", func(t *testing.T) {
  3549  			var v1 map[string]stdjson.RawMessage
  3550  			if err := stdjson.NewDecoder(strings.NewReader(`{"c":{"\\":"\\"}}`)).Decode(&v1); err != nil {
  3551  				t.Fatal(err)
  3552  			}
  3553  			var v2 map[string]json.RawMessage
  3554  			if err := json.NewDecoder(strings.NewReader(`{"c":{"\\":"\\"}}`)).Decode(&v2); err != nil {
  3555  				t.Fatal(err)
  3556  			}
  3557  			if len(v1) != len(v2) || !bytes.Equal(v1["c"], v2["c"]) {
  3558  				t.Fatalf("failed to decode backslash: expected %#v but got %#v", v1, v2)
  3559  			}
  3560  		})
  3561  	})
  3562  }
  3563  
  3564  func TestIssue218(t *testing.T) {
  3565  	type A struct {
  3566  		X int
  3567  	}
  3568  	type B struct {
  3569  		Y int
  3570  	}
  3571  	type S struct {
  3572  		A *A `json:"a,omitempty"`
  3573  		B *B `json:"b,omitempty"`
  3574  	}
  3575  	tests := []struct {
  3576  		name     string
  3577  		given    []S
  3578  		expected []S
  3579  	}{
  3580  		{
  3581  			name: "A should be correct",
  3582  			given: []S{{
  3583  				A: &A{
  3584  					X: 1,
  3585  				},
  3586  			}},
  3587  			expected: []S{{
  3588  				A: &A{
  3589  					X: 1,
  3590  				},
  3591  			}},
  3592  		},
  3593  		{
  3594  			name: "B should be correct",
  3595  			given: []S{{
  3596  				B: &B{
  3597  					Y: 2,
  3598  				},
  3599  			}},
  3600  			expected: []S{{
  3601  				B: &B{
  3602  					Y: 2,
  3603  				},
  3604  			}},
  3605  		},
  3606  	}
  3607  	for _, test := range tests {
  3608  		test := test
  3609  		t.Run(test.name, func(t *testing.T) {
  3610  			var buf bytes.Buffer
  3611  			if err := json.NewEncoder(&buf).Encode(test.given); err != nil {
  3612  				t.Fatal(err)
  3613  			}
  3614  			var actual []S
  3615  			if err := json.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&actual); err != nil {
  3616  				t.Fatal(err)
  3617  			}
  3618  			if !reflect.DeepEqual(test.expected, actual) {
  3619  				t.Fatalf("mismatch value: expected %v but got %v", test.expected, actual)
  3620  			}
  3621  		})
  3622  	}
  3623  }
  3624  
  3625  func TestDecodeEscapedCharField(t *testing.T) {
  3626  	b := []byte(`{"\u6D88\u606F":"\u6D88\u606F"}`)
  3627  	t.Run("unmarshal", func(t *testing.T) {
  3628  		v := struct {
  3629  			Msg string `json:"消息"`
  3630  		}{}
  3631  		if err := json.Unmarshal(b, &v); err != nil {
  3632  			t.Fatal(err)
  3633  		}
  3634  		if !bytes.Equal([]byte(v.Msg), []byte("消息")) {
  3635  			t.Fatal("failed to decode unicode char")
  3636  		}
  3637  	})
  3638  	t.Run("stream", func(t *testing.T) {
  3639  		v := struct {
  3640  			Msg string `json:"消息"`
  3641  		}{}
  3642  		if err := json.NewDecoder(bytes.NewBuffer(b)).Decode(&v); err != nil {
  3643  			t.Fatal(err)
  3644  		}
  3645  		if !bytes.Equal([]byte(v.Msg), []byte("消息")) {
  3646  			t.Fatal("failed to decode unicode char")
  3647  		}
  3648  	})
  3649  }
  3650  
  3651  type unmarshalContextKey struct{}
  3652  
  3653  type unmarshalContextStructType struct {
  3654  	v int
  3655  }
  3656  
  3657  func (t *unmarshalContextStructType) UnmarshalJSON(ctx context.Context, b []byte) error {
  3658  	v := ctx.Value(unmarshalContextKey{})
  3659  	s, ok := v.(string)
  3660  	if !ok {
  3661  		return errors.New("failed to propagate parent context.Context")
  3662  	}
  3663  	if s != "hello" {
  3664  		return errors.New("failed to propagate parent context.Context")
  3665  	}
  3666  	t.v = 100
  3667  	return nil
  3668  }
  3669  
  3670  func TestDecodeContextOption(t *testing.T) {
  3671  	src := []byte("10")
  3672  	buf := bytes.NewBuffer(src)
  3673  
  3674  	t.Run("UnmarshalContext", func(t *testing.T) {
  3675  		ctx := context.WithValue(context.Background(), unmarshalContextKey{}, "hello")
  3676  		var v unmarshalContextStructType
  3677  		if err := json.UnmarshalContext(ctx, src, &v); err != nil {
  3678  			t.Fatal(err)
  3679  		}
  3680  		if v.v != 100 {
  3681  			t.Fatal("failed to decode with context")
  3682  		}
  3683  	})
  3684  	t.Run("DecodeContext", func(t *testing.T) {
  3685  		ctx := context.WithValue(context.Background(), unmarshalContextKey{}, "hello")
  3686  		var v unmarshalContextStructType
  3687  		if err := json.NewDecoder(buf).DecodeContext(ctx, &v); err != nil {
  3688  			t.Fatal(err)
  3689  		}
  3690  		if v.v != 100 {
  3691  			t.Fatal("failed to decode with context")
  3692  		}
  3693  	})
  3694  }
  3695  
  3696  func TestIssue251(t *testing.T) {
  3697  	array := [3]int{1, 2, 3}
  3698  	err := stdjson.Unmarshal([]byte("[ ]"), &array)
  3699  	if err != nil {
  3700  		t.Fatal(err)
  3701  	}
  3702  	t.Log(array)
  3703  
  3704  	array = [3]int{1, 2, 3}
  3705  	err = json.Unmarshal([]byte("[ ]"), &array)
  3706  	if err != nil {
  3707  		t.Fatal(err)
  3708  	}
  3709  	t.Log(array)
  3710  
  3711  	array = [3]int{1, 2, 3}
  3712  	err = json.NewDecoder(strings.NewReader(`[ ]`)).Decode(&array)
  3713  	if err != nil {
  3714  		t.Fatal(err)
  3715  	}
  3716  	t.Log(array)
  3717  }
  3718  
  3719  func TestDecodeBinaryTypeWithEscapedChar(t *testing.T) {
  3720  	type T struct {
  3721  		Msg []byte `json:"msg"`
  3722  	}
  3723  	content := []byte(`{"msg":"aGVsbG8K\n"}`)
  3724  	t.Run("unmarshal", func(t *testing.T) {
  3725  		var expected T
  3726  		if err := stdjson.Unmarshal(content, &expected); err != nil {
  3727  			t.Fatal(err)
  3728  		}
  3729  		var got T
  3730  		if err := json.Unmarshal(content, &got); err != nil {
  3731  			t.Fatal(err)
  3732  		}
  3733  		if !bytes.Equal(expected.Msg, got.Msg) {
  3734  			t.Fatalf("failed to decode binary type with escaped char. expected %q but got %q", expected.Msg, got.Msg)
  3735  		}
  3736  	})
  3737  	t.Run("stream", func(t *testing.T) {
  3738  		var expected T
  3739  		if err := stdjson.NewDecoder(bytes.NewBuffer(content)).Decode(&expected); err != nil {
  3740  			t.Fatal(err)
  3741  		}
  3742  		var got T
  3743  		if err := json.NewDecoder(bytes.NewBuffer(content)).Decode(&got); err != nil {
  3744  			t.Fatal(err)
  3745  		}
  3746  		if !bytes.Equal(expected.Msg, got.Msg) {
  3747  			t.Fatalf("failed to decode binary type with escaped char. expected %q but got %q", expected.Msg, got.Msg)
  3748  		}
  3749  	})
  3750  }
  3751  
  3752  func TestIssue282(t *testing.T) {
  3753  	var J = []byte(`{
  3754    "a": {},
  3755    "b": {},
  3756    "c": {},
  3757    "d": {},
  3758    "e": {},
  3759    "f": {},
  3760    "g": {},
  3761    "h": {
  3762      "m": "1"
  3763    },
  3764    "i": {}
  3765  }`)
  3766  
  3767  	type T4 struct {
  3768  		F0 string
  3769  		F1 string
  3770  		F2 string
  3771  		F3 string
  3772  		F4 string
  3773  		F5 string
  3774  		F6 int
  3775  	}
  3776  	type T3 struct {
  3777  		F0 string
  3778  		F1 T4
  3779  	}
  3780  	type T2 struct {
  3781  		F0 string `json:"m"`
  3782  		F1 T3
  3783  	}
  3784  	type T0 map[string]T2
  3785  
  3786  	// T2 size is 136 bytes. This is indirect type.
  3787  	var v T0
  3788  	if err := json.Unmarshal(J, &v); err != nil {
  3789  		t.Fatal(err)
  3790  	}
  3791  	if v["h"].F0 != "1" {
  3792  		t.Fatalf("failed to assign map value")
  3793  	}
  3794  }
  3795  
  3796  func TestDecodeStructFieldMap(t *testing.T) {
  3797  	type Foo struct {
  3798  		Bar map[float64]float64 `json:"bar,omitempty"`
  3799  	}
  3800  	var v Foo
  3801  	if err := json.Unmarshal([]byte(`{"name":"test"}`), &v); err != nil {
  3802  		t.Fatal(err)
  3803  	}
  3804  	if v.Bar != nil {
  3805  		t.Fatalf("failed to decode v.Bar = %+v", v.Bar)
  3806  	}
  3807  }
  3808  
  3809  type issue303 struct {
  3810  	Count int
  3811  	Type  string
  3812  	Value any
  3813  }
  3814  
  3815  func (t *issue303) UnmarshalJSON(b []byte) error {
  3816  	type tmpType issue303
  3817  
  3818  	wrapped := struct {
  3819  		Value json.RawMessage
  3820  		tmpType
  3821  	}{}
  3822  	if err := json.Unmarshal(b, &wrapped); err != nil {
  3823  		return err
  3824  	}
  3825  	*t = issue303(wrapped.tmpType)
  3826  
  3827  	switch wrapped.Type {
  3828  	case "string":
  3829  		var str string
  3830  		if err := json.Unmarshal(wrapped.Value, &str); err != nil {
  3831  			return err
  3832  		}
  3833  		t.Value = str
  3834  	}
  3835  	return nil
  3836  }
  3837  
  3838  func TestIssue303(t *testing.T) {
  3839  	var v issue303
  3840  	if err := json.Unmarshal([]byte(`{"Count":7,"Type":"string","Value":"hello"}`), &v); err != nil {
  3841  		t.Fatal(err)
  3842  	}
  3843  	if v.Count != 7 || v.Type != "string" || v.Value != "hello" {
  3844  		t.Fatalf("failed to decode. count = %d type = %s value = %v", v.Count, v.Type, v.Value)
  3845  	}
  3846  }
  3847  
  3848  func TestIssue327(t *testing.T) {
  3849  	var v struct {
  3850  		Date time.Time `json:"date"`
  3851  	}
  3852  	dec := json.NewDecoder(strings.NewReader(`{"date": "2021-11-23T13:47:30+01:00"})`))
  3853  	if err := dec.DecodeContext(context.Background(), &v); err != nil {
  3854  		t.Fatal(err)
  3855  	}
  3856  	expected := "2021-11-23T13:47:30+01:00"
  3857  	if got := v.Date.Format(time.RFC3339); got != expected {
  3858  		t.Fatalf("failed to decode. expected %q but got %q", expected, got)
  3859  	}
  3860  }
  3861  
  3862  func TestIssue337(t *testing.T) {
  3863  	in := strings.Repeat(" ", 510) + "{}"
  3864  	var m map[string]string
  3865  	if err := json.NewDecoder(strings.NewReader(in)).Decode(&m); err != nil {
  3866  		t.Fatal("unexpected error:", err)
  3867  	}
  3868  	if len(m) != 0 {
  3869  		t.Fatal("unexpected result", m)
  3870  	}
  3871  }
  3872  
  3873  func Benchmark306(b *testing.B) {
  3874  	type T0 struct {
  3875  		Str string
  3876  	}
  3877  	in := []byte(`{"Str":"` + strings.Repeat(`abcd\"`, 10000) + `"}`)
  3878  	b.Run("stdjson", func(b *testing.B) {
  3879  		var x T0
  3880  		for i := 0; i < b.N; i++ {
  3881  			stdjson.Unmarshal(in, &x)
  3882  		}
  3883  	})
  3884  	b.Run("go-json", func(b *testing.B) {
  3885  		var x T0
  3886  		for i := 0; i < b.N; i++ {
  3887  			json.Unmarshal(in, &x)
  3888  		}
  3889  	})
  3890  }
  3891  
  3892  func TestIssue348(t *testing.T) {
  3893  	in := strings.Repeat("["+strings.Repeat(",1000", 500)[1:]+"]", 2)
  3894  	dec := json.NewDecoder(strings.NewReader(in))
  3895  	for dec.More() {
  3896  		var foo any
  3897  		if err := dec.Decode(&foo); err != nil {
  3898  			t.Error(err)
  3899  		}
  3900  	}
  3901  }
  3902  
  3903  type issue342 string
  3904  
  3905  func (t *issue342) UnmarshalJSON(b []byte) error {
  3906  	panic("unreachable")
  3907  }
  3908  
  3909  func TestIssue342(t *testing.T) {
  3910  	var v map[issue342]int
  3911  	in := []byte(`{"a":1}`)
  3912  	if err := json.Unmarshal(in, &v); err != nil {
  3913  		t.Errorf("unexpected error: %v", err)
  3914  	}
  3915  	expected := 1
  3916  	if got := v["a"]; got != expected {
  3917  		t.Errorf("unexpected result: got(%v) != expected(%v)", got, expected)
  3918  	}
  3919  }
  3920  
  3921  func TestIssue360(t *testing.T) {
  3922  	var uints []uint8
  3923  	err := json.Unmarshal([]byte(`[0, 1, 2]`), &uints)
  3924  	if err != nil {
  3925  		t.Errorf("unexpected error: %v", err)
  3926  	}
  3927  	if len(uints) != 3 || !(uints[0] == 0 && uints[1] == 1 && uints[2] == 2) {
  3928  		t.Errorf("unexpected result: %v", uints)
  3929  	}
  3930  }
  3931  
  3932  func TestIssue359(t *testing.T) {
  3933  	var a any = 1
  3934  	var b any = &a
  3935  	var c any = &b
  3936  	v, err := json.Marshal(c)
  3937  	if err != nil {
  3938  		t.Errorf("unexpected error: %v", err)
  3939  	}
  3940  	if string(v) != "1" {
  3941  		t.Errorf("unexpected result: %v", string(v))
  3942  	}
  3943  }
  3944  
  3945  func TestIssue364(t *testing.T) {
  3946  	var v struct {
  3947  		Description string `json:"description"`
  3948  	}
  3949  	err := json.Unmarshal([]byte(`{"description":"\uD83D\uDE87 Toledo is a metro station"}`), &v)
  3950  	if err != nil {
  3951  		t.Errorf("unexpected error: %v", err)
  3952  	}
  3953  	if v.Description != "🚇 Toledo is a metro station" {
  3954  		t.Errorf("unexpected result: %v", v.Description)
  3955  	}
  3956  }
  3957  
  3958  func TestIssue362(t *testing.T) {
  3959  	type AliasedPrimitive int
  3960  	type Combiner struct {
  3961  		SomeField int
  3962  		AliasedPrimitive
  3963  	}
  3964  	originalCombiner := Combiner{AliasedPrimitive: 7}
  3965  	b, err := json.Marshal(originalCombiner)
  3966  	assertErr(t, err)
  3967  	newCombiner := Combiner{}
  3968  	err = json.Unmarshal(b, &newCombiner)
  3969  	assertErr(t, err)
  3970  	assertEq(t, "TestEmbeddedPrimitiveAlias", originalCombiner, newCombiner)
  3971  }
  3972  
  3973  func TestIssue335(t *testing.T) {
  3974  	var v []string
  3975  	in := []byte(`["\u","A"]`)
  3976  	err := json.Unmarshal(in, &v)
  3977  	if err == nil {
  3978  		t.Errorf("unexpected success")
  3979  	}
  3980  }
  3981  
  3982  func TestIssue372(t *testing.T) {
  3983  	type A int
  3984  	type T struct {
  3985  		_ int
  3986  		*A
  3987  	}
  3988  	var v T
  3989  	err := json.Unmarshal([]byte(`{"A":7}`), &v)
  3990  	assertErr(t, err)
  3991  
  3992  	got := *v.A
  3993  	expected := A(7)
  3994  	if got != expected {
  3995  		t.Errorf("unexpected result: %v != %v", got, expected)
  3996  	}
  3997  }
  3998  
  3999  type issue384 struct{}
  4000  
  4001  func (t *issue384) UnmarshalJSON(b []byte) error {
  4002  	return nil
  4003  }
  4004  
  4005  func TestIssue384(t *testing.T) {
  4006  	testcases := []string{
  4007  		`{"data": "` + strings.Repeat("-", 500) + `\""}`,
  4008  		`["` + strings.Repeat("-", 508) + `\""]`,
  4009  	}
  4010  	for _, tc := range testcases {
  4011  		dec := json.NewDecoder(strings.NewReader(tc))
  4012  		var v issue384
  4013  		if err := dec.Decode(&v); err != nil {
  4014  			t.Errorf("unexpected error: %v", err)
  4015  		}
  4016  	}
  4017  }
  4018  
  4019  func TestIssue408(t *testing.T) {
  4020  	type T struct {
  4021  		Arr [2]int32 `json:"arr"`
  4022  	}
  4023  	var v T
  4024  	if err := json.Unmarshal([]byte(`{"arr": [1,2]}`), &v); err != nil {
  4025  		t.Fatal(err)
  4026  	}
  4027  }
  4028  
  4029  func TestIssue416(t *testing.T) {
  4030  	b := []byte(`{"Сообщение":"Текст"}`)
  4031  
  4032  	type T struct {
  4033  		Msg string `json:"Сообщение"`
  4034  	}
  4035  	var x T
  4036  	err := json.Unmarshal(b, &x)
  4037  	assertErr(t, err)
  4038  	assertEq(t, "unexpected result", "Текст", x.Msg)
  4039  }
  4040  
  4041  func TestIssue429(t *testing.T) {
  4042  	var x struct {
  4043  		N int32
  4044  	}
  4045  	for _, b := range []string{
  4046  		`{"\u"`,
  4047  		`{"\u0"`,
  4048  		`{"\u00"`,
  4049  	} {
  4050  		if err := json.Unmarshal([]byte(b), &x); err == nil {
  4051  			t.Errorf("unexpected success")
  4052  		}
  4053  	}
  4054  }