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