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