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