github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/encoding/gob/codec_test.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gob
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"flag"
    11  	"math"
    12  	"math/rand"
    13  	"reflect"
    14  	"strings"
    15  	"testing"
    16  	"time"
    17  )
    18  
    19  var doFuzzTests = flag.Bool("gob.fuzz", false, "run the fuzz tests, which are large and very slow")
    20  
    21  // Guarantee encoding format by comparing some encodings to hand-written values
    22  type EncodeT struct {
    23  	x uint64
    24  	b []byte
    25  }
    26  
    27  var encodeT = []EncodeT{
    28  	{0x00, []byte{0x00}},
    29  	{0x0F, []byte{0x0F}},
    30  	{0xFF, []byte{0xFF, 0xFF}},
    31  	{0xFFFF, []byte{0xFE, 0xFF, 0xFF}},
    32  	{0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}},
    33  	{0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}},
    34  	{0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
    35  	{0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
    36  	{0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
    37  	{0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
    38  	{0x1111, []byte{0xFE, 0x11, 0x11}},
    39  	{0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
    40  	{0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}},
    41  	{1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
    42  }
    43  
    44  // testError is meant to be used as a deferred function to turn a panic(gobError) into a
    45  // plain test.Error call.
    46  func testError(t *testing.T) {
    47  	if e := recover(); e != nil {
    48  		t.Error(e.(gobError).err) // Will re-panic if not one of our errors, such as a runtime error.
    49  	}
    50  }
    51  
    52  func newDecBuffer(data []byte) *decBuffer {
    53  	return &decBuffer{
    54  		data: data,
    55  	}
    56  }
    57  
    58  // Test basic encode/decode routines for unsigned integers
    59  func TestUintCodec(t *testing.T) {
    60  	defer testError(t)
    61  	b := new(encBuffer)
    62  	encState := newEncoderState(b)
    63  	for _, tt := range encodeT {
    64  		b.Reset()
    65  		encState.encodeUint(tt.x)
    66  		if !bytes.Equal(tt.b, b.Bytes()) {
    67  			t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
    68  		}
    69  	}
    70  	for u := uint64(0); ; u = (u + 1) * 7 {
    71  		b.Reset()
    72  		encState.encodeUint(u)
    73  		decState := newDecodeState(newDecBuffer(b.Bytes()))
    74  		v := decState.decodeUint()
    75  		if u != v {
    76  			t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
    77  		}
    78  		if u&(1<<63) != 0 {
    79  			break
    80  		}
    81  	}
    82  }
    83  
    84  func verifyInt(i int64, t *testing.T) {
    85  	defer testError(t)
    86  	var b = new(encBuffer)
    87  	encState := newEncoderState(b)
    88  	encState.encodeInt(i)
    89  	decState := newDecodeState(newDecBuffer(b.Bytes()))
    90  	j := decState.decodeInt()
    91  	if i != j {
    92  		t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
    93  	}
    94  }
    95  
    96  // Test basic encode/decode routines for signed integers
    97  func TestIntCodec(t *testing.T) {
    98  	for u := uint64(0); ; u = (u + 1) * 7 {
    99  		// Do positive and negative values
   100  		i := int64(u)
   101  		verifyInt(i, t)
   102  		verifyInt(-i, t)
   103  		verifyInt(^i, t)
   104  		if u&(1<<63) != 0 {
   105  			break
   106  		}
   107  	}
   108  	verifyInt(-1<<63, t) // a tricky case
   109  }
   110  
   111  // The result of encoding a true boolean with field number 7
   112  var boolResult = []byte{0x07, 0x01}
   113  
   114  // The result of encoding a number 17 with field number 7
   115  var signedResult = []byte{0x07, 2 * 17}
   116  var unsignedResult = []byte{0x07, 17}
   117  var floatResult = []byte{0x07, 0xFE, 0x31, 0x40}
   118  
   119  // The result of encoding a number 17+19i with field number 7
   120  var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
   121  
   122  // The result of encoding "hello" with field number 7
   123  var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
   124  
   125  func newDecodeState(buf *decBuffer) *decoderState {
   126  	d := new(decoderState)
   127  	d.b = buf
   128  	return d
   129  }
   130  
   131  func newEncoderState(b *encBuffer) *encoderState {
   132  	b.Reset()
   133  	state := &encoderState{enc: nil, b: b}
   134  	state.fieldnum = -1
   135  	return state
   136  }
   137  
   138  // Test instruction execution for encoding.
   139  // Do not run the machine yet; instead do individual instructions crafted by hand.
   140  func TestScalarEncInstructions(t *testing.T) {
   141  	var b = new(encBuffer)
   142  
   143  	// bool
   144  	{
   145  		var data bool = true
   146  		instr := &encInstr{encBool, 6, nil, 0}
   147  		state := newEncoderState(b)
   148  		instr.op(instr, state, reflect.ValueOf(data))
   149  		if !bytes.Equal(boolResult, b.Bytes()) {
   150  			t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
   151  		}
   152  	}
   153  
   154  	// int
   155  	{
   156  		b.Reset()
   157  		var data int = 17
   158  		instr := &encInstr{encInt, 6, nil, 0}
   159  		state := newEncoderState(b)
   160  		instr.op(instr, state, reflect.ValueOf(data))
   161  		if !bytes.Equal(signedResult, b.Bytes()) {
   162  			t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
   163  		}
   164  	}
   165  
   166  	// uint
   167  	{
   168  		b.Reset()
   169  		var data uint = 17
   170  		instr := &encInstr{encUint, 6, nil, 0}
   171  		state := newEncoderState(b)
   172  		instr.op(instr, state, reflect.ValueOf(data))
   173  		if !bytes.Equal(unsignedResult, b.Bytes()) {
   174  			t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
   175  		}
   176  	}
   177  
   178  	// int8
   179  	{
   180  		b.Reset()
   181  		var data int8 = 17
   182  		instr := &encInstr{encInt, 6, nil, 0}
   183  		state := newEncoderState(b)
   184  		instr.op(instr, state, reflect.ValueOf(data))
   185  		if !bytes.Equal(signedResult, b.Bytes()) {
   186  			t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
   187  		}
   188  	}
   189  
   190  	// uint8
   191  	{
   192  		b.Reset()
   193  		var data uint8 = 17
   194  		instr := &encInstr{encUint, 6, nil, 0}
   195  		state := newEncoderState(b)
   196  		instr.op(instr, state, reflect.ValueOf(data))
   197  		if !bytes.Equal(unsignedResult, b.Bytes()) {
   198  			t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
   199  		}
   200  	}
   201  
   202  	// int16
   203  	{
   204  		b.Reset()
   205  		var data int16 = 17
   206  		instr := &encInstr{encInt, 6, nil, 0}
   207  		state := newEncoderState(b)
   208  		instr.op(instr, state, reflect.ValueOf(data))
   209  		if !bytes.Equal(signedResult, b.Bytes()) {
   210  			t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
   211  		}
   212  	}
   213  
   214  	// uint16
   215  	{
   216  		b.Reset()
   217  		var data uint16 = 17
   218  		instr := &encInstr{encUint, 6, nil, 0}
   219  		state := newEncoderState(b)
   220  		instr.op(instr, state, reflect.ValueOf(data))
   221  		if !bytes.Equal(unsignedResult, b.Bytes()) {
   222  			t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
   223  		}
   224  	}
   225  
   226  	// int32
   227  	{
   228  		b.Reset()
   229  		var data int32 = 17
   230  		instr := &encInstr{encInt, 6, nil, 0}
   231  		state := newEncoderState(b)
   232  		instr.op(instr, state, reflect.ValueOf(data))
   233  		if !bytes.Equal(signedResult, b.Bytes()) {
   234  			t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
   235  		}
   236  	}
   237  
   238  	// uint32
   239  	{
   240  		b.Reset()
   241  		var data uint32 = 17
   242  		instr := &encInstr{encUint, 6, nil, 0}
   243  		state := newEncoderState(b)
   244  		instr.op(instr, state, reflect.ValueOf(data))
   245  		if !bytes.Equal(unsignedResult, b.Bytes()) {
   246  			t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
   247  		}
   248  	}
   249  
   250  	// int64
   251  	{
   252  		b.Reset()
   253  		var data int64 = 17
   254  		instr := &encInstr{encInt, 6, nil, 0}
   255  		state := newEncoderState(b)
   256  		instr.op(instr, state, reflect.ValueOf(data))
   257  		if !bytes.Equal(signedResult, b.Bytes()) {
   258  			t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
   259  		}
   260  	}
   261  
   262  	// uint64
   263  	{
   264  		b.Reset()
   265  		var data uint64 = 17
   266  		instr := &encInstr{encUint, 6, nil, 0}
   267  		state := newEncoderState(b)
   268  		instr.op(instr, state, reflect.ValueOf(data))
   269  		if !bytes.Equal(unsignedResult, b.Bytes()) {
   270  			t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
   271  		}
   272  	}
   273  
   274  	// float32
   275  	{
   276  		b.Reset()
   277  		var data float32 = 17
   278  		instr := &encInstr{encFloat, 6, nil, 0}
   279  		state := newEncoderState(b)
   280  		instr.op(instr, state, reflect.ValueOf(data))
   281  		if !bytes.Equal(floatResult, b.Bytes()) {
   282  			t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
   283  		}
   284  	}
   285  
   286  	// float64
   287  	{
   288  		b.Reset()
   289  		var data float64 = 17
   290  		instr := &encInstr{encFloat, 6, nil, 0}
   291  		state := newEncoderState(b)
   292  		instr.op(instr, state, reflect.ValueOf(data))
   293  		if !bytes.Equal(floatResult, b.Bytes()) {
   294  			t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
   295  		}
   296  	}
   297  
   298  	// bytes == []uint8
   299  	{
   300  		b.Reset()
   301  		data := []byte("hello")
   302  		instr := &encInstr{encUint8Array, 6, nil, 0}
   303  		state := newEncoderState(b)
   304  		instr.op(instr, state, reflect.ValueOf(data))
   305  		if !bytes.Equal(bytesResult, b.Bytes()) {
   306  			t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
   307  		}
   308  	}
   309  
   310  	// string
   311  	{
   312  		b.Reset()
   313  		var data string = "hello"
   314  		instr := &encInstr{encString, 6, nil, 0}
   315  		state := newEncoderState(b)
   316  		instr.op(instr, state, reflect.ValueOf(data))
   317  		if !bytes.Equal(bytesResult, b.Bytes()) {
   318  			t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
   319  		}
   320  	}
   321  }
   322  
   323  func execDec(instr *decInstr, state *decoderState, t *testing.T, value reflect.Value) {
   324  	defer testError(t)
   325  	v := int(state.decodeUint())
   326  	if v+state.fieldnum != 6 {
   327  		t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
   328  	}
   329  	instr.op(instr, state, value.Elem())
   330  	state.fieldnum = 6
   331  }
   332  
   333  func newDecodeStateFromData(data []byte) *decoderState {
   334  	b := newDecBuffer(data)
   335  	state := newDecodeState(b)
   336  	state.fieldnum = -1
   337  	return state
   338  }
   339  
   340  // Test instruction execution for decoding.
   341  // Do not run the machine yet; instead do individual instructions crafted by hand.
   342  func TestScalarDecInstructions(t *testing.T) {
   343  	ovfl := errors.New("overflow")
   344  
   345  	// bool
   346  	{
   347  		var data bool
   348  		instr := &decInstr{decBool, 6, nil, ovfl}
   349  		state := newDecodeStateFromData(boolResult)
   350  		execDec(instr, state, t, reflect.ValueOf(&data))
   351  		if data != true {
   352  			t.Errorf("bool a = %v not true", data)
   353  		}
   354  	}
   355  	// int
   356  	{
   357  		var data int
   358  		instr := &decInstr{decOpTable[reflect.Int], 6, nil, ovfl}
   359  		state := newDecodeStateFromData(signedResult)
   360  		execDec(instr, state, t, reflect.ValueOf(&data))
   361  		if data != 17 {
   362  			t.Errorf("int a = %v not 17", data)
   363  		}
   364  	}
   365  
   366  	// uint
   367  	{
   368  		var data uint
   369  		instr := &decInstr{decOpTable[reflect.Uint], 6, nil, ovfl}
   370  		state := newDecodeStateFromData(unsignedResult)
   371  		execDec(instr, state, t, reflect.ValueOf(&data))
   372  		if data != 17 {
   373  			t.Errorf("uint a = %v not 17", data)
   374  		}
   375  	}
   376  
   377  	// int8
   378  	{
   379  		var data int8
   380  		instr := &decInstr{decInt8, 6, nil, ovfl}
   381  		state := newDecodeStateFromData(signedResult)
   382  		execDec(instr, state, t, reflect.ValueOf(&data))
   383  		if data != 17 {
   384  			t.Errorf("int8 a = %v not 17", data)
   385  		}
   386  	}
   387  
   388  	// uint8
   389  	{
   390  		var data uint8
   391  		instr := &decInstr{decUint8, 6, nil, ovfl}
   392  		state := newDecodeStateFromData(unsignedResult)
   393  		execDec(instr, state, t, reflect.ValueOf(&data))
   394  		if data != 17 {
   395  			t.Errorf("uint8 a = %v not 17", data)
   396  		}
   397  	}
   398  
   399  	// int16
   400  	{
   401  		var data int16
   402  		instr := &decInstr{decInt16, 6, nil, ovfl}
   403  		state := newDecodeStateFromData(signedResult)
   404  		execDec(instr, state, t, reflect.ValueOf(&data))
   405  		if data != 17 {
   406  			t.Errorf("int16 a = %v not 17", data)
   407  		}
   408  	}
   409  
   410  	// uint16
   411  	{
   412  		var data uint16
   413  		instr := &decInstr{decUint16, 6, nil, ovfl}
   414  		state := newDecodeStateFromData(unsignedResult)
   415  		execDec(instr, state, t, reflect.ValueOf(&data))
   416  		if data != 17 {
   417  			t.Errorf("uint16 a = %v not 17", data)
   418  		}
   419  	}
   420  
   421  	// int32
   422  	{
   423  		var data int32
   424  		instr := &decInstr{decInt32, 6, nil, ovfl}
   425  		state := newDecodeStateFromData(signedResult)
   426  		execDec(instr, state, t, reflect.ValueOf(&data))
   427  		if data != 17 {
   428  			t.Errorf("int32 a = %v not 17", data)
   429  		}
   430  	}
   431  
   432  	// uint32
   433  	{
   434  		var data uint32
   435  		instr := &decInstr{decUint32, 6, nil, ovfl}
   436  		state := newDecodeStateFromData(unsignedResult)
   437  		execDec(instr, state, t, reflect.ValueOf(&data))
   438  		if data != 17 {
   439  			t.Errorf("uint32 a = %v not 17", data)
   440  		}
   441  	}
   442  
   443  	// uintptr
   444  	{
   445  		var data uintptr
   446  		instr := &decInstr{decOpTable[reflect.Uintptr], 6, nil, ovfl}
   447  		state := newDecodeStateFromData(unsignedResult)
   448  		execDec(instr, state, t, reflect.ValueOf(&data))
   449  		if data != 17 {
   450  			t.Errorf("uintptr a = %v not 17", data)
   451  		}
   452  	}
   453  
   454  	// int64
   455  	{
   456  		var data int64
   457  		instr := &decInstr{decInt64, 6, nil, ovfl}
   458  		state := newDecodeStateFromData(signedResult)
   459  		execDec(instr, state, t, reflect.ValueOf(&data))
   460  		if data != 17 {
   461  			t.Errorf("int64 a = %v not 17", data)
   462  		}
   463  	}
   464  
   465  	// uint64
   466  	{
   467  		var data uint64
   468  		instr := &decInstr{decUint64, 6, nil, ovfl}
   469  		state := newDecodeStateFromData(unsignedResult)
   470  		execDec(instr, state, t, reflect.ValueOf(&data))
   471  		if data != 17 {
   472  			t.Errorf("uint64 a = %v not 17", data)
   473  		}
   474  	}
   475  
   476  	// float32
   477  	{
   478  		var data float32
   479  		instr := &decInstr{decFloat32, 6, nil, ovfl}
   480  		state := newDecodeStateFromData(floatResult)
   481  		execDec(instr, state, t, reflect.ValueOf(&data))
   482  		if data != 17 {
   483  			t.Errorf("float32 a = %v not 17", data)
   484  		}
   485  	}
   486  
   487  	// float64
   488  	{
   489  		var data float64
   490  		instr := &decInstr{decFloat64, 6, nil, ovfl}
   491  		state := newDecodeStateFromData(floatResult)
   492  		execDec(instr, state, t, reflect.ValueOf(&data))
   493  		if data != 17 {
   494  			t.Errorf("float64 a = %v not 17", data)
   495  		}
   496  	}
   497  
   498  	// complex64
   499  	{
   500  		var data complex64
   501  		instr := &decInstr{decOpTable[reflect.Complex64], 6, nil, ovfl}
   502  		state := newDecodeStateFromData(complexResult)
   503  		execDec(instr, state, t, reflect.ValueOf(&data))
   504  		if data != 17+19i {
   505  			t.Errorf("complex a = %v not 17+19i", data)
   506  		}
   507  	}
   508  
   509  	// complex128
   510  	{
   511  		var data complex128
   512  		instr := &decInstr{decOpTable[reflect.Complex128], 6, nil, ovfl}
   513  		state := newDecodeStateFromData(complexResult)
   514  		execDec(instr, state, t, reflect.ValueOf(&data))
   515  		if data != 17+19i {
   516  			t.Errorf("complex a = %v not 17+19i", data)
   517  		}
   518  	}
   519  
   520  	// bytes == []uint8
   521  	{
   522  		var data []byte
   523  		instr := &decInstr{decUint8Slice, 6, nil, ovfl}
   524  		state := newDecodeStateFromData(bytesResult)
   525  		execDec(instr, state, t, reflect.ValueOf(&data))
   526  		if string(data) != "hello" {
   527  			t.Errorf(`bytes a = %q not "hello"`, string(data))
   528  		}
   529  	}
   530  
   531  	// string
   532  	{
   533  		var data string
   534  		instr := &decInstr{decString, 6, nil, ovfl}
   535  		state := newDecodeStateFromData(bytesResult)
   536  		execDec(instr, state, t, reflect.ValueOf(&data))
   537  		if data != "hello" {
   538  			t.Errorf(`bytes a = %q not "hello"`, data)
   539  		}
   540  	}
   541  }
   542  
   543  func TestEndToEnd(t *testing.T) {
   544  	type T2 struct {
   545  		T string
   546  	}
   547  	type T3 struct {
   548  		X float64
   549  		Z *int
   550  	}
   551  	s1 := "string1"
   552  	s2 := "string2"
   553  	type T1 struct {
   554  		A, B, C  int
   555  		M        map[string]*float64
   556  		M2       map[int]T3
   557  		EmptyMap map[string]int // to check that we receive a non-nil map.
   558  		N        *[3]float64
   559  		Strs     *[2]string
   560  		Int64s   *[]int64
   561  		RI       complex64
   562  		S        string
   563  		Y        []byte
   564  		T        *T2
   565  	}
   566  	pi := 3.14159
   567  	e := 2.71828
   568  	meaning := 42
   569  	fingers := 5
   570  	t1 := &T1{
   571  		A:        17,
   572  		B:        18,
   573  		C:        -5,
   574  		M:        map[string]*float64{"pi": &pi, "e": &e},
   575  		M2:       map[int]T3{4: T3{X: pi, Z: &meaning}, 10: T3{X: e, Z: &fingers}},
   576  		EmptyMap: make(map[string]int),
   577  		N:        &[3]float64{1.5, 2.5, 3.5},
   578  		Strs:     &[2]string{s1, s2},
   579  		Int64s:   &[]int64{77, 89, 123412342134},
   580  		RI:       17 - 23i,
   581  		S:        "Now is the time",
   582  		Y:        []byte("hello, sailor"),
   583  		T:        &T2{"this is T2"},
   584  	}
   585  	b := new(bytes.Buffer)
   586  	err := NewEncoder(b).Encode(t1)
   587  	if err != nil {
   588  		t.Error("encode:", err)
   589  	}
   590  	var _t1 T1
   591  	err = NewDecoder(b).Decode(&_t1)
   592  	if err != nil {
   593  		t.Fatal("decode:", err)
   594  	}
   595  	if !reflect.DeepEqual(t1, &_t1) {
   596  		t.Errorf("encode expected %v got %v", *t1, _t1)
   597  	}
   598  	// Be absolutely sure the received map is non-nil.
   599  	if t1.EmptyMap == nil {
   600  		t.Errorf("nil map sent")
   601  	}
   602  	if _t1.EmptyMap == nil {
   603  		t.Errorf("nil map received")
   604  	}
   605  }
   606  
   607  func TestOverflow(t *testing.T) {
   608  	type inputT struct {
   609  		Maxi int64
   610  		Mini int64
   611  		Maxu uint64
   612  		Maxf float64
   613  		Minf float64
   614  		Maxc complex128
   615  		Minc complex128
   616  	}
   617  	var it inputT
   618  	var err error
   619  	b := new(bytes.Buffer)
   620  	enc := NewEncoder(b)
   621  	dec := NewDecoder(b)
   622  
   623  	// int8
   624  	b.Reset()
   625  	it = inputT{
   626  		Maxi: math.MaxInt8 + 1,
   627  	}
   628  	type outi8 struct {
   629  		Maxi int8
   630  		Mini int8
   631  	}
   632  	var o1 outi8
   633  	enc.Encode(it)
   634  	err = dec.Decode(&o1)
   635  	if err == nil || err.Error() != `value for "Maxi" out of range` {
   636  		t.Error("wrong overflow error for int8:", err)
   637  	}
   638  	it = inputT{
   639  		Mini: math.MinInt8 - 1,
   640  	}
   641  	b.Reset()
   642  	enc.Encode(it)
   643  	err = dec.Decode(&o1)
   644  	if err == nil || err.Error() != `value for "Mini" out of range` {
   645  		t.Error("wrong underflow error for int8:", err)
   646  	}
   647  
   648  	// int16
   649  	b.Reset()
   650  	it = inputT{
   651  		Maxi: math.MaxInt16 + 1,
   652  	}
   653  	type outi16 struct {
   654  		Maxi int16
   655  		Mini int16
   656  	}
   657  	var o2 outi16
   658  	enc.Encode(it)
   659  	err = dec.Decode(&o2)
   660  	if err == nil || err.Error() != `value for "Maxi" out of range` {
   661  		t.Error("wrong overflow error for int16:", err)
   662  	}
   663  	it = inputT{
   664  		Mini: math.MinInt16 - 1,
   665  	}
   666  	b.Reset()
   667  	enc.Encode(it)
   668  	err = dec.Decode(&o2)
   669  	if err == nil || err.Error() != `value for "Mini" out of range` {
   670  		t.Error("wrong underflow error for int16:", err)
   671  	}
   672  
   673  	// int32
   674  	b.Reset()
   675  	it = inputT{
   676  		Maxi: math.MaxInt32 + 1,
   677  	}
   678  	type outi32 struct {
   679  		Maxi int32
   680  		Mini int32
   681  	}
   682  	var o3 outi32
   683  	enc.Encode(it)
   684  	err = dec.Decode(&o3)
   685  	if err == nil || err.Error() != `value for "Maxi" out of range` {
   686  		t.Error("wrong overflow error for int32:", err)
   687  	}
   688  	it = inputT{
   689  		Mini: math.MinInt32 - 1,
   690  	}
   691  	b.Reset()
   692  	enc.Encode(it)
   693  	err = dec.Decode(&o3)
   694  	if err == nil || err.Error() != `value for "Mini" out of range` {
   695  		t.Error("wrong underflow error for int32:", err)
   696  	}
   697  
   698  	// uint8
   699  	b.Reset()
   700  	it = inputT{
   701  		Maxu: math.MaxUint8 + 1,
   702  	}
   703  	type outu8 struct {
   704  		Maxu uint8
   705  	}
   706  	var o4 outu8
   707  	enc.Encode(it)
   708  	err = dec.Decode(&o4)
   709  	if err == nil || err.Error() != `value for "Maxu" out of range` {
   710  		t.Error("wrong overflow error for uint8:", err)
   711  	}
   712  
   713  	// uint16
   714  	b.Reset()
   715  	it = inputT{
   716  		Maxu: math.MaxUint16 + 1,
   717  	}
   718  	type outu16 struct {
   719  		Maxu uint16
   720  	}
   721  	var o5 outu16
   722  	enc.Encode(it)
   723  	err = dec.Decode(&o5)
   724  	if err == nil || err.Error() != `value for "Maxu" out of range` {
   725  		t.Error("wrong overflow error for uint16:", err)
   726  	}
   727  
   728  	// uint32
   729  	b.Reset()
   730  	it = inputT{
   731  		Maxu: math.MaxUint32 + 1,
   732  	}
   733  	type outu32 struct {
   734  		Maxu uint32
   735  	}
   736  	var o6 outu32
   737  	enc.Encode(it)
   738  	err = dec.Decode(&o6)
   739  	if err == nil || err.Error() != `value for "Maxu" out of range` {
   740  		t.Error("wrong overflow error for uint32:", err)
   741  	}
   742  
   743  	// float32
   744  	b.Reset()
   745  	it = inputT{
   746  		Maxf: math.MaxFloat32 * 2,
   747  	}
   748  	type outf32 struct {
   749  		Maxf float32
   750  		Minf float32
   751  	}
   752  	var o7 outf32
   753  	enc.Encode(it)
   754  	err = dec.Decode(&o7)
   755  	if err == nil || err.Error() != `value for "Maxf" out of range` {
   756  		t.Error("wrong overflow error for float32:", err)
   757  	}
   758  
   759  	// complex64
   760  	b.Reset()
   761  	it = inputT{
   762  		Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
   763  	}
   764  	type outc64 struct {
   765  		Maxc complex64
   766  		Minc complex64
   767  	}
   768  	var o8 outc64
   769  	enc.Encode(it)
   770  	err = dec.Decode(&o8)
   771  	if err == nil || err.Error() != `value for "Maxc" out of range` {
   772  		t.Error("wrong overflow error for complex64:", err)
   773  	}
   774  }
   775  
   776  func TestNesting(t *testing.T) {
   777  	type RT struct {
   778  		A    string
   779  		Next *RT
   780  	}
   781  	rt := new(RT)
   782  	rt.A = "level1"
   783  	rt.Next = new(RT)
   784  	rt.Next.A = "level2"
   785  	b := new(bytes.Buffer)
   786  	NewEncoder(b).Encode(rt)
   787  	var drt RT
   788  	dec := NewDecoder(b)
   789  	err := dec.Decode(&drt)
   790  	if err != nil {
   791  		t.Fatal("decoder error:", err)
   792  	}
   793  	if drt.A != rt.A {
   794  		t.Errorf("nesting: encode expected %v got %v", *rt, drt)
   795  	}
   796  	if drt.Next == nil {
   797  		t.Errorf("nesting: recursion failed")
   798  	}
   799  	if drt.Next.A != rt.Next.A {
   800  		t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
   801  	}
   802  }
   803  
   804  // These three structures have the same data with different indirections
   805  type T0 struct {
   806  	A int
   807  	B int
   808  	C int
   809  	D int
   810  }
   811  type T1 struct {
   812  	A int
   813  	B *int
   814  	C **int
   815  	D ***int
   816  }
   817  type T2 struct {
   818  	A ***int
   819  	B **int
   820  	C *int
   821  	D int
   822  }
   823  
   824  func TestAutoIndirection(t *testing.T) {
   825  	// First transfer t1 into t0
   826  	var t1 T1
   827  	t1.A = 17
   828  	t1.B = new(int)
   829  	*t1.B = 177
   830  	t1.C = new(*int)
   831  	*t1.C = new(int)
   832  	**t1.C = 1777
   833  	t1.D = new(**int)
   834  	*t1.D = new(*int)
   835  	**t1.D = new(int)
   836  	***t1.D = 17777
   837  	b := new(bytes.Buffer)
   838  	enc := NewEncoder(b)
   839  	enc.Encode(t1)
   840  	dec := NewDecoder(b)
   841  	var t0 T0
   842  	dec.Decode(&t0)
   843  	if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
   844  		t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
   845  	}
   846  
   847  	// Now transfer t2 into t0
   848  	var t2 T2
   849  	t2.D = 17777
   850  	t2.C = new(int)
   851  	*t2.C = 1777
   852  	t2.B = new(*int)
   853  	*t2.B = new(int)
   854  	**t2.B = 177
   855  	t2.A = new(**int)
   856  	*t2.A = new(*int)
   857  	**t2.A = new(int)
   858  	***t2.A = 17
   859  	b.Reset()
   860  	enc.Encode(t2)
   861  	t0 = T0{}
   862  	dec.Decode(&t0)
   863  	if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
   864  		t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
   865  	}
   866  
   867  	// Now transfer t0 into t1
   868  	t0 = T0{17, 177, 1777, 17777}
   869  	b.Reset()
   870  	enc.Encode(t0)
   871  	t1 = T1{}
   872  	dec.Decode(&t1)
   873  	if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
   874  		t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
   875  	}
   876  
   877  	// Now transfer t0 into t2
   878  	b.Reset()
   879  	enc.Encode(t0)
   880  	t2 = T2{}
   881  	dec.Decode(&t2)
   882  	if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
   883  		t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
   884  	}
   885  
   886  	// Now do t2 again but without pre-allocated pointers.
   887  	b.Reset()
   888  	enc.Encode(t0)
   889  	***t2.A = 0
   890  	**t2.B = 0
   891  	*t2.C = 0
   892  	t2.D = 0
   893  	dec.Decode(&t2)
   894  	if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
   895  		t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
   896  	}
   897  }
   898  
   899  type RT0 struct {
   900  	A int
   901  	B string
   902  	C float64
   903  }
   904  type RT1 struct {
   905  	C      float64
   906  	B      string
   907  	A      int
   908  	NotSet string
   909  }
   910  
   911  func TestReorderedFields(t *testing.T) {
   912  	var rt0 RT0
   913  	rt0.A = 17
   914  	rt0.B = "hello"
   915  	rt0.C = 3.14159
   916  	b := new(bytes.Buffer)
   917  	NewEncoder(b).Encode(rt0)
   918  	dec := NewDecoder(b)
   919  	var rt1 RT1
   920  	// Wire type is RT0, local type is RT1.
   921  	err := dec.Decode(&rt1)
   922  	if err != nil {
   923  		t.Fatal("decode error:", err)
   924  	}
   925  	if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
   926  		t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
   927  	}
   928  }
   929  
   930  // Like an RT0 but with fields we'll ignore on the decode side.
   931  type IT0 struct {
   932  	A        int64
   933  	B        string
   934  	Ignore_d []int
   935  	Ignore_e [3]float64
   936  	Ignore_f bool
   937  	Ignore_g string
   938  	Ignore_h []byte
   939  	Ignore_i *RT1
   940  	Ignore_m map[string]int
   941  	C        float64
   942  }
   943  
   944  func TestIgnoredFields(t *testing.T) {
   945  	var it0 IT0
   946  	it0.A = 17
   947  	it0.B = "hello"
   948  	it0.C = 3.14159
   949  	it0.Ignore_d = []int{1, 2, 3}
   950  	it0.Ignore_e[0] = 1.0
   951  	it0.Ignore_e[1] = 2.0
   952  	it0.Ignore_e[2] = 3.0
   953  	it0.Ignore_f = true
   954  	it0.Ignore_g = "pay no attention"
   955  	it0.Ignore_h = []byte("to the curtain")
   956  	it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
   957  	it0.Ignore_m = map[string]int{"one": 1, "two": 2}
   958  
   959  	b := new(bytes.Buffer)
   960  	NewEncoder(b).Encode(it0)
   961  	dec := NewDecoder(b)
   962  	var rt1 RT1
   963  	// Wire type is IT0, local type is RT1.
   964  	err := dec.Decode(&rt1)
   965  	if err != nil {
   966  		t.Error("error: ", err)
   967  	}
   968  	if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
   969  		t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
   970  	}
   971  }
   972  
   973  func TestBadRecursiveType(t *testing.T) {
   974  	type Rec ***Rec
   975  	var rec Rec
   976  	b := new(bytes.Buffer)
   977  	err := NewEncoder(b).Encode(&rec)
   978  	if err == nil {
   979  		t.Error("expected error; got none")
   980  	} else if !strings.Contains(err.Error(), "recursive") {
   981  		t.Error("expected recursive type error; got", err)
   982  	}
   983  	// Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
   984  }
   985  
   986  type Indirect struct {
   987  	A ***[3]int
   988  	S ***[]int
   989  	M ****map[string]int
   990  }
   991  
   992  type Direct struct {
   993  	A [3]int
   994  	S []int
   995  	M map[string]int
   996  }
   997  
   998  func TestIndirectSliceMapArray(t *testing.T) {
   999  	// Marshal indirect, unmarshal to direct.
  1000  	i := new(Indirect)
  1001  	i.A = new(**[3]int)
  1002  	*i.A = new(*[3]int)
  1003  	**i.A = new([3]int)
  1004  	***i.A = [3]int{1, 2, 3}
  1005  	i.S = new(**[]int)
  1006  	*i.S = new(*[]int)
  1007  	**i.S = new([]int)
  1008  	***i.S = []int{4, 5, 6}
  1009  	i.M = new(***map[string]int)
  1010  	*i.M = new(**map[string]int)
  1011  	**i.M = new(*map[string]int)
  1012  	***i.M = new(map[string]int)
  1013  	****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
  1014  	b := new(bytes.Buffer)
  1015  	NewEncoder(b).Encode(i)
  1016  	dec := NewDecoder(b)
  1017  	var d Direct
  1018  	err := dec.Decode(&d)
  1019  	if err != nil {
  1020  		t.Error("error: ", err)
  1021  	}
  1022  	if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
  1023  		t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
  1024  	}
  1025  	if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
  1026  		t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
  1027  	}
  1028  	if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
  1029  		t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
  1030  	}
  1031  	// Marshal direct, unmarshal to indirect.
  1032  	d.A = [3]int{11, 22, 33}
  1033  	d.S = []int{44, 55, 66}
  1034  	d.M = map[string]int{"four": 4, "five": 5, "six": 6}
  1035  	i = new(Indirect)
  1036  	b.Reset()
  1037  	NewEncoder(b).Encode(d)
  1038  	dec = NewDecoder(b)
  1039  	err = dec.Decode(&i)
  1040  	if err != nil {
  1041  		t.Fatal("error: ", err)
  1042  	}
  1043  	if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
  1044  		t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
  1045  	}
  1046  	if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
  1047  		t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
  1048  	}
  1049  	if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
  1050  		t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
  1051  	}
  1052  }
  1053  
  1054  // An interface with several implementations
  1055  type Squarer interface {
  1056  	Square() int
  1057  }
  1058  
  1059  type Int int
  1060  
  1061  func (i Int) Square() int {
  1062  	return int(i * i)
  1063  }
  1064  
  1065  type Float float64
  1066  
  1067  func (f Float) Square() int {
  1068  	return int(f * f)
  1069  }
  1070  
  1071  type Vector []int
  1072  
  1073  func (v Vector) Square() int {
  1074  	sum := 0
  1075  	for _, x := range v {
  1076  		sum += x * x
  1077  	}
  1078  	return sum
  1079  }
  1080  
  1081  type Point struct {
  1082  	X, Y int
  1083  }
  1084  
  1085  func (p Point) Square() int {
  1086  	return p.X*p.X + p.Y*p.Y
  1087  }
  1088  
  1089  // A struct with interfaces in it.
  1090  type InterfaceItem struct {
  1091  	I             int
  1092  	Sq1, Sq2, Sq3 Squarer
  1093  	F             float64
  1094  	Sq            []Squarer
  1095  }
  1096  
  1097  // The same struct without interfaces
  1098  type NoInterfaceItem struct {
  1099  	I int
  1100  	F float64
  1101  }
  1102  
  1103  func TestInterface(t *testing.T) {
  1104  	iVal := Int(3)
  1105  	fVal := Float(5)
  1106  	// Sending a Vector will require that the receiver define a type in the middle of
  1107  	// receiving the value for item2.
  1108  	vVal := Vector{1, 2, 3}
  1109  	b := new(bytes.Buffer)
  1110  	item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
  1111  	// Register the types.
  1112  	Register(Int(0))
  1113  	Register(Float(0))
  1114  	Register(Vector{})
  1115  	err := NewEncoder(b).Encode(item1)
  1116  	if err != nil {
  1117  		t.Error("expected no encode error; got", err)
  1118  	}
  1119  
  1120  	item2 := InterfaceItem{}
  1121  	err = NewDecoder(b).Decode(&item2)
  1122  	if err != nil {
  1123  		t.Fatal("decode:", err)
  1124  	}
  1125  	if item2.I != item1.I {
  1126  		t.Error("normal int did not decode correctly")
  1127  	}
  1128  	if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
  1129  		t.Error("Int did not decode correctly")
  1130  	}
  1131  	if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
  1132  		t.Error("Float did not decode correctly")
  1133  	}
  1134  	if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
  1135  		t.Error("Vector did not decode correctly")
  1136  	}
  1137  	if item2.F != item1.F {
  1138  		t.Error("normal float did not decode correctly")
  1139  	}
  1140  	// Now check that we received a slice of Squarers correctly, including a nil element
  1141  	if len(item1.Sq) != len(item2.Sq) {
  1142  		t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
  1143  	}
  1144  	for i, v1 := range item1.Sq {
  1145  		v2 := item2.Sq[i]
  1146  		if v1 == nil || v2 == nil {
  1147  			if v1 != nil || v2 != nil {
  1148  				t.Errorf("item %d inconsistent nils", i)
  1149  			}
  1150  		} else if v1.Square() != v2.Square() {
  1151  			t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
  1152  		}
  1153  	}
  1154  }
  1155  
  1156  // A struct with all basic types, stored in interfaces.
  1157  type BasicInterfaceItem struct {
  1158  	Int, Int8, Int16, Int32, Int64      interface{}
  1159  	Uint, Uint8, Uint16, Uint32, Uint64 interface{}
  1160  	Float32, Float64                    interface{}
  1161  	Complex64, Complex128               interface{}
  1162  	Bool                                interface{}
  1163  	String                              interface{}
  1164  	Bytes                               interface{}
  1165  }
  1166  
  1167  func TestInterfaceBasic(t *testing.T) {
  1168  	b := new(bytes.Buffer)
  1169  	item1 := &BasicInterfaceItem{
  1170  		int(1), int8(1), int16(1), int32(1), int64(1),
  1171  		uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
  1172  		float32(1), 1.0,
  1173  		complex64(1i), complex128(1i),
  1174  		true,
  1175  		"hello",
  1176  		[]byte("sailor"),
  1177  	}
  1178  	err := NewEncoder(b).Encode(item1)
  1179  	if err != nil {
  1180  		t.Error("expected no encode error; got", err)
  1181  	}
  1182  
  1183  	item2 := &BasicInterfaceItem{}
  1184  	err = NewDecoder(b).Decode(&item2)
  1185  	if err != nil {
  1186  		t.Fatal("decode:", err)
  1187  	}
  1188  	if !reflect.DeepEqual(item1, item2) {
  1189  		t.Errorf("encode expected %v got %v", item1, item2)
  1190  	}
  1191  	// Hand check a couple for correct types.
  1192  	if v, ok := item2.Bool.(bool); !ok || !v {
  1193  		t.Error("boolean should be true")
  1194  	}
  1195  	if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
  1196  		t.Errorf("string should be %v is %v", item1.String, v)
  1197  	}
  1198  }
  1199  
  1200  type String string
  1201  
  1202  type PtrInterfaceItem struct {
  1203  	Str1 interface{} // basic
  1204  	Str2 interface{} // derived
  1205  }
  1206  
  1207  // We'll send pointers; should receive values.
  1208  // Also check that we can register T but send *T.
  1209  func TestInterfacePointer(t *testing.T) {
  1210  	b := new(bytes.Buffer)
  1211  	str1 := "howdy"
  1212  	str2 := String("kiddo")
  1213  	item1 := &PtrInterfaceItem{
  1214  		&str1,
  1215  		&str2,
  1216  	}
  1217  	// Register the type.
  1218  	Register(str2)
  1219  	err := NewEncoder(b).Encode(item1)
  1220  	if err != nil {
  1221  		t.Error("expected no encode error; got", err)
  1222  	}
  1223  
  1224  	item2 := &PtrInterfaceItem{}
  1225  	err = NewDecoder(b).Decode(&item2)
  1226  	if err != nil {
  1227  		t.Fatal("decode:", err)
  1228  	}
  1229  	// Hand test for correct types and values.
  1230  	if v, ok := item2.Str1.(string); !ok || v != str1 {
  1231  		t.Errorf("basic string failed: %q should be %q", v, str1)
  1232  	}
  1233  	if v, ok := item2.Str2.(String); !ok || v != str2 {
  1234  		t.Errorf("derived type String failed: %q should be %q", v, str2)
  1235  	}
  1236  }
  1237  
  1238  func TestIgnoreInterface(t *testing.T) {
  1239  	iVal := Int(3)
  1240  	fVal := Float(5)
  1241  	// Sending a Point will require that the receiver define a type in the middle of
  1242  	// receiving the value for item2.
  1243  	pVal := Point{2, 3}
  1244  	b := new(bytes.Buffer)
  1245  	item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
  1246  	// Register the types.
  1247  	Register(Int(0))
  1248  	Register(Float(0))
  1249  	Register(Point{})
  1250  	err := NewEncoder(b).Encode(item1)
  1251  	if err != nil {
  1252  		t.Error("expected no encode error; got", err)
  1253  	}
  1254  
  1255  	item2 := NoInterfaceItem{}
  1256  	err = NewDecoder(b).Decode(&item2)
  1257  	if err != nil {
  1258  		t.Fatal("decode:", err)
  1259  	}
  1260  	if item2.I != item1.I {
  1261  		t.Error("normal int did not decode correctly")
  1262  	}
  1263  	if item2.F != item1.F {
  1264  		t.Error("normal float did not decode correctly")
  1265  	}
  1266  }
  1267  
  1268  type U struct {
  1269  	A int
  1270  	B string
  1271  	c float64
  1272  	D uint
  1273  }
  1274  
  1275  func TestUnexportedFields(t *testing.T) {
  1276  	var u0 U
  1277  	u0.A = 17
  1278  	u0.B = "hello"
  1279  	u0.c = 3.14159
  1280  	u0.D = 23
  1281  	b := new(bytes.Buffer)
  1282  	NewEncoder(b).Encode(u0)
  1283  	dec := NewDecoder(b)
  1284  	var u1 U
  1285  	u1.c = 1234.
  1286  	err := dec.Decode(&u1)
  1287  	if err != nil {
  1288  		t.Fatal("decode error:", err)
  1289  	}
  1290  	if u0.A != u1.A || u0.B != u1.B || u0.D != u1.D {
  1291  		t.Errorf("u1->u0: expected %v; got %v", u0, u1)
  1292  	}
  1293  	if u1.c != 1234. {
  1294  		t.Error("u1.c modified")
  1295  	}
  1296  }
  1297  
  1298  var singletons = []interface{}{
  1299  	true,
  1300  	7,
  1301  	3.2,
  1302  	"hello",
  1303  	[3]int{11, 22, 33},
  1304  	[]float32{0.5, 0.25, 0.125},
  1305  	map[string]int{"one": 1, "two": 2},
  1306  }
  1307  
  1308  func TestDebugSingleton(t *testing.T) {
  1309  	if debugFunc == nil {
  1310  		return
  1311  	}
  1312  	b := new(bytes.Buffer)
  1313  	// Accumulate a number of values and print them out all at once.
  1314  	for _, x := range singletons {
  1315  		err := NewEncoder(b).Encode(x)
  1316  		if err != nil {
  1317  			t.Fatal("encode:", err)
  1318  		}
  1319  	}
  1320  	debugFunc(b)
  1321  }
  1322  
  1323  // A type that won't be defined in the gob until we send it in an interface value.
  1324  type OnTheFly struct {
  1325  	A int
  1326  }
  1327  
  1328  type DT struct {
  1329  	//	X OnTheFly
  1330  	A     int
  1331  	B     string
  1332  	C     float64
  1333  	I     interface{}
  1334  	J     interface{}
  1335  	I_nil interface{}
  1336  	M     map[string]int
  1337  	T     [3]int
  1338  	S     []string
  1339  }
  1340  
  1341  func newDT() DT {
  1342  	var dt DT
  1343  	dt.A = 17
  1344  	dt.B = "hello"
  1345  	dt.C = 3.14159
  1346  	dt.I = 271828
  1347  	dt.J = OnTheFly{3}
  1348  	dt.I_nil = nil
  1349  	dt.M = map[string]int{"one": 1, "two": 2}
  1350  	dt.T = [3]int{11, 22, 33}
  1351  	dt.S = []string{"hi", "joe"}
  1352  	return dt
  1353  }
  1354  
  1355  func TestDebugStruct(t *testing.T) {
  1356  	if debugFunc == nil {
  1357  		return
  1358  	}
  1359  	Register(OnTheFly{})
  1360  	dt := newDT()
  1361  	b := new(bytes.Buffer)
  1362  	err := NewEncoder(b).Encode(dt)
  1363  	if err != nil {
  1364  		t.Fatal("encode:", err)
  1365  	}
  1366  	debugBuffer := bytes.NewBuffer(b.Bytes())
  1367  	dt2 := &DT{}
  1368  	err = NewDecoder(b).Decode(&dt2)
  1369  	if err != nil {
  1370  		t.Error("decode:", err)
  1371  	}
  1372  	debugFunc(debugBuffer)
  1373  }
  1374  
  1375  func encFuzzDec(rng *rand.Rand, in interface{}) error {
  1376  	buf := new(bytes.Buffer)
  1377  	enc := NewEncoder(buf)
  1378  	if err := enc.Encode(&in); err != nil {
  1379  		return err
  1380  	}
  1381  
  1382  	b := buf.Bytes()
  1383  	for i, bi := range b {
  1384  		if rng.Intn(10) < 3 {
  1385  			b[i] = bi + uint8(rng.Intn(256))
  1386  		}
  1387  	}
  1388  
  1389  	dec := NewDecoder(buf)
  1390  	var e interface{}
  1391  	if err := dec.Decode(&e); err != nil {
  1392  		return err
  1393  	}
  1394  	return nil
  1395  }
  1396  
  1397  // This does some "fuzz testing" by attempting to decode a sequence of random bytes.
  1398  func TestFuzz(t *testing.T) {
  1399  	if !*doFuzzTests {
  1400  		t.Logf("disabled; run with -gob.fuzz to enable")
  1401  		return
  1402  	}
  1403  
  1404  	// all possible inputs
  1405  	input := []interface{}{
  1406  		new(int),
  1407  		new(float32),
  1408  		new(float64),
  1409  		new(complex128),
  1410  		&ByteStruct{255},
  1411  		&ArrayStruct{},
  1412  		&StringStruct{"hello"},
  1413  		&GobTest1{0, &StringStruct{"hello"}},
  1414  	}
  1415  	testFuzz(t, time.Now().UnixNano(), 100, input...)
  1416  }
  1417  
  1418  func TestFuzzRegressions(t *testing.T) {
  1419  	if !*doFuzzTests {
  1420  		t.Logf("disabled; run with -gob.fuzz to enable")
  1421  		return
  1422  	}
  1423  
  1424  	// An instance triggering a type name of length ~102 GB.
  1425  	testFuzz(t, 1328492090837718000, 100, new(float32))
  1426  	// An instance triggering a type name of 1.6 GB.
  1427  	// Note: can take several minutes to run.
  1428  	testFuzz(t, 1330522872628565000, 100, new(int))
  1429  }
  1430  
  1431  func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) {
  1432  	for _, e := range input {
  1433  		t.Logf("seed=%d n=%d e=%T", seed, n, e)
  1434  		rng := rand.New(rand.NewSource(seed))
  1435  		for i := 0; i < n; i++ {
  1436  			encFuzzDec(rng, e)
  1437  		}
  1438  	}
  1439  }
  1440  
  1441  // TestFuzzOneByte tries to decode corrupted input sequences
  1442  // and checks that no panic occurs.
  1443  func TestFuzzOneByte(t *testing.T) {
  1444  	buf := new(bytes.Buffer)
  1445  	Register(OnTheFly{})
  1446  	dt := newDT()
  1447  	if err := NewEncoder(buf).Encode(dt); err != nil {
  1448  		t.Fatal(err)
  1449  	}
  1450  	s := buf.String()
  1451  
  1452  	indices := make([]int, 0, len(s))
  1453  	for i := 0; i < len(s); i++ {
  1454  		switch i {
  1455  		case 14, 167, 231, 265: // a slice length, corruptions are not handled yet.
  1456  			continue
  1457  		}
  1458  		indices = append(indices, i)
  1459  	}
  1460  	if testing.Short() {
  1461  		indices = []int{1, 111, 178} // known fixed panics
  1462  	}
  1463  	for _, i := range indices {
  1464  		for j := 0; j < 256; j += 3 {
  1465  			b := []byte(s)
  1466  			b[i] ^= byte(j)
  1467  			var e DT
  1468  			func() {
  1469  				defer func() {
  1470  					if p := recover(); p != nil {
  1471  						t.Errorf("crash for b[%d] ^= 0x%x", i, j)
  1472  						panic(p)
  1473  					}
  1474  				}()
  1475  				err := NewDecoder(bytes.NewReader(b)).Decode(&e)
  1476  				_ = err
  1477  			}()
  1478  		}
  1479  	}
  1480  }
  1481  
  1482  // Don't crash, just give error with invalid type id.
  1483  // Issue 9649.
  1484  func TestErrorInvalidTypeId(t *testing.T) {
  1485  	data := []byte{0x01, 0x00, 0x01, 0x00}
  1486  	d := NewDecoder(bytes.NewReader(data))
  1487  	// When running d.Decode(&foo) the first time the decoder stops
  1488  	// after []byte{0x01, 0x00} and reports an errBadType. Running
  1489  	// d.Decode(&foo) again on exactly the same input sequence should
  1490  	// give another errBadType, but instead caused a panic because
  1491  	// decoderMap wasn't cleaned up properly after the first error.
  1492  	for i := 0; i < 2; i++ {
  1493  		var foo struct{}
  1494  		err := d.Decode(&foo)
  1495  		if err != errBadType {
  1496  			t.Fatalf("decode: expected %s, got %s", errBadType, err)
  1497  		}
  1498  	}
  1499  }