...

Source file src/encoding/gob/codec_test.go

Documentation: encoding/gob

		 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  	type T1 struct {
	 552  		A, B, C	int
	 553  		M				map[string]*float64
	 554  		M2			 map[int]T3
	 555  		Mstring	map[string]string
	 556  		Mintptr	map[int]*int
	 557  		Mcomp		map[complex128]complex128
	 558  		Marr		 map[[2]string][2]*float64
	 559  		EmptyMap map[string]int // to check that we receive a non-nil map.
	 560  		N				*[3]float64
	 561  		Strs		 *[2]string
	 562  		Int64s	 *[]int64
	 563  		RI			 complex64
	 564  		S				string
	 565  		Y				[]byte
	 566  		T				*T2
	 567  	}
	 568  	pi := 3.14159
	 569  	e := 2.71828
	 570  	two := 2.0
	 571  	meaning := 42
	 572  	fingers := 5
	 573  	s1 := "string1"
	 574  	s2 := "string2"
	 575  	var comp1 complex128 = complex(1.0, 1.0)
	 576  	var comp2 complex128 = complex(1.0, 1.0)
	 577  	var arr1 [2]string
	 578  	arr1[0] = s1
	 579  	arr1[1] = s2
	 580  	var arr2 [2]string
	 581  	arr2[0] = s2
	 582  	arr2[1] = s1
	 583  	var floatArr1 [2]*float64
	 584  	floatArr1[0] = &pi
	 585  	floatArr1[1] = &e
	 586  	var floatArr2 [2]*float64
	 587  	floatArr2[0] = &e
	 588  	floatArr2[1] = &two
	 589  	t1 := &T1{
	 590  		A:				17,
	 591  		B:				18,
	 592  		C:				-5,
	 593  		M:				map[string]*float64{"pi": &pi, "e": &e},
	 594  		M2:			 map[int]T3{4: {X: pi, Z: &meaning}, 10: {X: e, Z: &fingers}},
	 595  		Mstring:	map[string]string{"pi": "3.14", "e": "2.71"},
	 596  		Mintptr:	map[int]*int{meaning: &fingers, fingers: &meaning},
	 597  		Mcomp:		map[complex128]complex128{comp1: comp2, comp2: comp1},
	 598  		Marr:		 map[[2]string][2]*float64{arr1: floatArr1, arr2: floatArr2},
	 599  		EmptyMap: make(map[string]int),
	 600  		N:				&[3]float64{1.5, 2.5, 3.5},
	 601  		Strs:		 &[2]string{s1, s2},
	 602  		Int64s:	 &[]int64{77, 89, 123412342134},
	 603  		RI:			 17 - 23i,
	 604  		S:				"Now is the time",
	 605  		Y:				[]byte("hello, sailor"),
	 606  		T:				&T2{"this is T2"},
	 607  	}
	 608  	b := new(bytes.Buffer)
	 609  	err := NewEncoder(b).Encode(t1)
	 610  	if err != nil {
	 611  		t.Error("encode:", err)
	 612  	}
	 613  	var _t1 T1
	 614  	err = NewDecoder(b).Decode(&_t1)
	 615  	if err != nil {
	 616  		t.Fatal("decode:", err)
	 617  	}
	 618  	if !reflect.DeepEqual(t1, &_t1) {
	 619  		t.Errorf("encode expected %v got %v", *t1, _t1)
	 620  	}
	 621  	// Be absolutely sure the received map is non-nil.
	 622  	if t1.EmptyMap == nil {
	 623  		t.Errorf("nil map sent")
	 624  	}
	 625  	if _t1.EmptyMap == nil {
	 626  		t.Errorf("nil map received")
	 627  	}
	 628  }
	 629  
	 630  func TestOverflow(t *testing.T) {
	 631  	type inputT struct {
	 632  		Maxi int64
	 633  		Mini int64
	 634  		Maxu uint64
	 635  		Maxf float64
	 636  		Minf float64
	 637  		Maxc complex128
	 638  		Minc complex128
	 639  	}
	 640  	var it inputT
	 641  	var err error
	 642  	b := new(bytes.Buffer)
	 643  	enc := NewEncoder(b)
	 644  	dec := NewDecoder(b)
	 645  
	 646  	// int8
	 647  	b.Reset()
	 648  	it = inputT{
	 649  		Maxi: math.MaxInt8 + 1,
	 650  	}
	 651  	type outi8 struct {
	 652  		Maxi int8
	 653  		Mini int8
	 654  	}
	 655  	var o1 outi8
	 656  	enc.Encode(it)
	 657  	err = dec.Decode(&o1)
	 658  	if err == nil || err.Error() != `value for "Maxi" out of range` {
	 659  		t.Error("wrong overflow error for int8:", err)
	 660  	}
	 661  	it = inputT{
	 662  		Mini: math.MinInt8 - 1,
	 663  	}
	 664  	b.Reset()
	 665  	enc.Encode(it)
	 666  	err = dec.Decode(&o1)
	 667  	if err == nil || err.Error() != `value for "Mini" out of range` {
	 668  		t.Error("wrong underflow error for int8:", err)
	 669  	}
	 670  
	 671  	// int16
	 672  	b.Reset()
	 673  	it = inputT{
	 674  		Maxi: math.MaxInt16 + 1,
	 675  	}
	 676  	type outi16 struct {
	 677  		Maxi int16
	 678  		Mini int16
	 679  	}
	 680  	var o2 outi16
	 681  	enc.Encode(it)
	 682  	err = dec.Decode(&o2)
	 683  	if err == nil || err.Error() != `value for "Maxi" out of range` {
	 684  		t.Error("wrong overflow error for int16:", err)
	 685  	}
	 686  	it = inputT{
	 687  		Mini: math.MinInt16 - 1,
	 688  	}
	 689  	b.Reset()
	 690  	enc.Encode(it)
	 691  	err = dec.Decode(&o2)
	 692  	if err == nil || err.Error() != `value for "Mini" out of range` {
	 693  		t.Error("wrong underflow error for int16:", err)
	 694  	}
	 695  
	 696  	// int32
	 697  	b.Reset()
	 698  	it = inputT{
	 699  		Maxi: math.MaxInt32 + 1,
	 700  	}
	 701  	type outi32 struct {
	 702  		Maxi int32
	 703  		Mini int32
	 704  	}
	 705  	var o3 outi32
	 706  	enc.Encode(it)
	 707  	err = dec.Decode(&o3)
	 708  	if err == nil || err.Error() != `value for "Maxi" out of range` {
	 709  		t.Error("wrong overflow error for int32:", err)
	 710  	}
	 711  	it = inputT{
	 712  		Mini: math.MinInt32 - 1,
	 713  	}
	 714  	b.Reset()
	 715  	enc.Encode(it)
	 716  	err = dec.Decode(&o3)
	 717  	if err == nil || err.Error() != `value for "Mini" out of range` {
	 718  		t.Error("wrong underflow error for int32:", err)
	 719  	}
	 720  
	 721  	// uint8
	 722  	b.Reset()
	 723  	it = inputT{
	 724  		Maxu: math.MaxUint8 + 1,
	 725  	}
	 726  	type outu8 struct {
	 727  		Maxu uint8
	 728  	}
	 729  	var o4 outu8
	 730  	enc.Encode(it)
	 731  	err = dec.Decode(&o4)
	 732  	if err == nil || err.Error() != `value for "Maxu" out of range` {
	 733  		t.Error("wrong overflow error for uint8:", err)
	 734  	}
	 735  
	 736  	// uint16
	 737  	b.Reset()
	 738  	it = inputT{
	 739  		Maxu: math.MaxUint16 + 1,
	 740  	}
	 741  	type outu16 struct {
	 742  		Maxu uint16
	 743  	}
	 744  	var o5 outu16
	 745  	enc.Encode(it)
	 746  	err = dec.Decode(&o5)
	 747  	if err == nil || err.Error() != `value for "Maxu" out of range` {
	 748  		t.Error("wrong overflow error for uint16:", err)
	 749  	}
	 750  
	 751  	// uint32
	 752  	b.Reset()
	 753  	it = inputT{
	 754  		Maxu: math.MaxUint32 + 1,
	 755  	}
	 756  	type outu32 struct {
	 757  		Maxu uint32
	 758  	}
	 759  	var o6 outu32
	 760  	enc.Encode(it)
	 761  	err = dec.Decode(&o6)
	 762  	if err == nil || err.Error() != `value for "Maxu" out of range` {
	 763  		t.Error("wrong overflow error for uint32:", err)
	 764  	}
	 765  
	 766  	// float32
	 767  	b.Reset()
	 768  	it = inputT{
	 769  		Maxf: math.MaxFloat32 * 2,
	 770  	}
	 771  	type outf32 struct {
	 772  		Maxf float32
	 773  		Minf float32
	 774  	}
	 775  	var o7 outf32
	 776  	enc.Encode(it)
	 777  	err = dec.Decode(&o7)
	 778  	if err == nil || err.Error() != `value for "Maxf" out of range` {
	 779  		t.Error("wrong overflow error for float32:", err)
	 780  	}
	 781  
	 782  	// complex64
	 783  	b.Reset()
	 784  	it = inputT{
	 785  		Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
	 786  	}
	 787  	type outc64 struct {
	 788  		Maxc complex64
	 789  		Minc complex64
	 790  	}
	 791  	var o8 outc64
	 792  	enc.Encode(it)
	 793  	err = dec.Decode(&o8)
	 794  	if err == nil || err.Error() != `value for "Maxc" out of range` {
	 795  		t.Error("wrong overflow error for complex64:", err)
	 796  	}
	 797  }
	 798  
	 799  func TestNesting(t *testing.T) {
	 800  	type RT struct {
	 801  		A		string
	 802  		Next *RT
	 803  	}
	 804  	rt := new(RT)
	 805  	rt.A = "level1"
	 806  	rt.Next = new(RT)
	 807  	rt.Next.A = "level2"
	 808  	b := new(bytes.Buffer)
	 809  	NewEncoder(b).Encode(rt)
	 810  	var drt RT
	 811  	dec := NewDecoder(b)
	 812  	err := dec.Decode(&drt)
	 813  	if err != nil {
	 814  		t.Fatal("decoder error:", err)
	 815  	}
	 816  	if drt.A != rt.A {
	 817  		t.Errorf("nesting: encode expected %v got %v", *rt, drt)
	 818  	}
	 819  	if drt.Next == nil {
	 820  		t.Errorf("nesting: recursion failed")
	 821  	}
	 822  	if drt.Next.A != rt.Next.A {
	 823  		t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
	 824  	}
	 825  }
	 826  
	 827  // These three structures have the same data with different indirections
	 828  type T0 struct {
	 829  	A int
	 830  	B int
	 831  	C int
	 832  	D int
	 833  }
	 834  type T1 struct {
	 835  	A int
	 836  	B *int
	 837  	C **int
	 838  	D ***int
	 839  }
	 840  type T2 struct {
	 841  	A ***int
	 842  	B **int
	 843  	C *int
	 844  	D int
	 845  }
	 846  
	 847  func TestAutoIndirection(t *testing.T) {
	 848  	// First transfer t1 into t0
	 849  	var t1 T1
	 850  	t1.A = 17
	 851  	t1.B = new(int)
	 852  	*t1.B = 177
	 853  	t1.C = new(*int)
	 854  	*t1.C = new(int)
	 855  	**t1.C = 1777
	 856  	t1.D = new(**int)
	 857  	*t1.D = new(*int)
	 858  	**t1.D = new(int)
	 859  	***t1.D = 17777
	 860  	b := new(bytes.Buffer)
	 861  	enc := NewEncoder(b)
	 862  	enc.Encode(t1)
	 863  	dec := NewDecoder(b)
	 864  	var t0 T0
	 865  	dec.Decode(&t0)
	 866  	if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
	 867  		t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
	 868  	}
	 869  
	 870  	// Now transfer t2 into t0
	 871  	var t2 T2
	 872  	t2.D = 17777
	 873  	t2.C = new(int)
	 874  	*t2.C = 1777
	 875  	t2.B = new(*int)
	 876  	*t2.B = new(int)
	 877  	**t2.B = 177
	 878  	t2.A = new(**int)
	 879  	*t2.A = new(*int)
	 880  	**t2.A = new(int)
	 881  	***t2.A = 17
	 882  	b.Reset()
	 883  	enc.Encode(t2)
	 884  	t0 = T0{}
	 885  	dec.Decode(&t0)
	 886  	if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
	 887  		t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
	 888  	}
	 889  
	 890  	// Now transfer t0 into t1
	 891  	t0 = T0{17, 177, 1777, 17777}
	 892  	b.Reset()
	 893  	enc.Encode(t0)
	 894  	t1 = T1{}
	 895  	dec.Decode(&t1)
	 896  	if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
	 897  		t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
	 898  	}
	 899  
	 900  	// Now transfer t0 into t2
	 901  	b.Reset()
	 902  	enc.Encode(t0)
	 903  	t2 = T2{}
	 904  	dec.Decode(&t2)
	 905  	if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
	 906  		t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
	 907  	}
	 908  
	 909  	// Now do t2 again but without pre-allocated pointers.
	 910  	b.Reset()
	 911  	enc.Encode(t0)
	 912  	***t2.A = 0
	 913  	**t2.B = 0
	 914  	*t2.C = 0
	 915  	t2.D = 0
	 916  	dec.Decode(&t2)
	 917  	if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
	 918  		t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
	 919  	}
	 920  }
	 921  
	 922  type RT0 struct {
	 923  	A int
	 924  	B string
	 925  	C float64
	 926  }
	 927  type RT1 struct {
	 928  	C			float64
	 929  	B			string
	 930  	A			int
	 931  	NotSet string
	 932  }
	 933  
	 934  func TestReorderedFields(t *testing.T) {
	 935  	var rt0 RT0
	 936  	rt0.A = 17
	 937  	rt0.B = "hello"
	 938  	rt0.C = 3.14159
	 939  	b := new(bytes.Buffer)
	 940  	NewEncoder(b).Encode(rt0)
	 941  	dec := NewDecoder(b)
	 942  	var rt1 RT1
	 943  	// Wire type is RT0, local type is RT1.
	 944  	err := dec.Decode(&rt1)
	 945  	if err != nil {
	 946  		t.Fatal("decode error:", err)
	 947  	}
	 948  	if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
	 949  		t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
	 950  	}
	 951  }
	 952  
	 953  // Like an RT0 but with fields we'll ignore on the decode side.
	 954  type IT0 struct {
	 955  	A				int64
	 956  	B				string
	 957  	Ignore_d []int
	 958  	Ignore_e [3]float64
	 959  	Ignore_f bool
	 960  	Ignore_g string
	 961  	Ignore_h []byte
	 962  	Ignore_i *RT1
	 963  	Ignore_m map[string]int
	 964  	C				float64
	 965  }
	 966  
	 967  func TestIgnoredFields(t *testing.T) {
	 968  	var it0 IT0
	 969  	it0.A = 17
	 970  	it0.B = "hello"
	 971  	it0.C = 3.14159
	 972  	it0.Ignore_d = []int{1, 2, 3}
	 973  	it0.Ignore_e[0] = 1.0
	 974  	it0.Ignore_e[1] = 2.0
	 975  	it0.Ignore_e[2] = 3.0
	 976  	it0.Ignore_f = true
	 977  	it0.Ignore_g = "pay no attention"
	 978  	it0.Ignore_h = []byte("to the curtain")
	 979  	it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
	 980  	it0.Ignore_m = map[string]int{"one": 1, "two": 2}
	 981  
	 982  	b := new(bytes.Buffer)
	 983  	NewEncoder(b).Encode(it0)
	 984  	dec := NewDecoder(b)
	 985  	var rt1 RT1
	 986  	// Wire type is IT0, local type is RT1.
	 987  	err := dec.Decode(&rt1)
	 988  	if err != nil {
	 989  		t.Error("error: ", err)
	 990  	}
	 991  	if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
	 992  		t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
	 993  	}
	 994  }
	 995  
	 996  func TestBadRecursiveType(t *testing.T) {
	 997  	type Rec ***Rec
	 998  	var rec Rec
	 999  	b := new(bytes.Buffer)
	1000  	err := NewEncoder(b).Encode(&rec)
	1001  	if err == nil {
	1002  		t.Error("expected error; got none")
	1003  	} else if !strings.Contains(err.Error(), "recursive") {
	1004  		t.Error("expected recursive type error; got", err)
	1005  	}
	1006  	// Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
	1007  }
	1008  
	1009  type Indirect struct {
	1010  	A ***[3]int
	1011  	S ***[]int
	1012  	M ****map[string]int
	1013  }
	1014  
	1015  type Direct struct {
	1016  	A [3]int
	1017  	S []int
	1018  	M map[string]int
	1019  }
	1020  
	1021  func TestIndirectSliceMapArray(t *testing.T) {
	1022  	// Marshal indirect, unmarshal to direct.
	1023  	i := new(Indirect)
	1024  	i.A = new(**[3]int)
	1025  	*i.A = new(*[3]int)
	1026  	**i.A = new([3]int)
	1027  	***i.A = [3]int{1, 2, 3}
	1028  	i.S = new(**[]int)
	1029  	*i.S = new(*[]int)
	1030  	**i.S = new([]int)
	1031  	***i.S = []int{4, 5, 6}
	1032  	i.M = new(***map[string]int)
	1033  	*i.M = new(**map[string]int)
	1034  	**i.M = new(*map[string]int)
	1035  	***i.M = new(map[string]int)
	1036  	****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
	1037  	b := new(bytes.Buffer)
	1038  	NewEncoder(b).Encode(i)
	1039  	dec := NewDecoder(b)
	1040  	var d Direct
	1041  	err := dec.Decode(&d)
	1042  	if err != nil {
	1043  		t.Error("error: ", err)
	1044  	}
	1045  	if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
	1046  		t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
	1047  	}
	1048  	if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
	1049  		t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
	1050  	}
	1051  	if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
	1052  		t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
	1053  	}
	1054  	// Marshal direct, unmarshal to indirect.
	1055  	d.A = [3]int{11, 22, 33}
	1056  	d.S = []int{44, 55, 66}
	1057  	d.M = map[string]int{"four": 4, "five": 5, "six": 6}
	1058  	i = new(Indirect)
	1059  	b.Reset()
	1060  	NewEncoder(b).Encode(d)
	1061  	dec = NewDecoder(b)
	1062  	err = dec.Decode(&i)
	1063  	if err != nil {
	1064  		t.Fatal("error: ", err)
	1065  	}
	1066  	if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
	1067  		t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
	1068  	}
	1069  	if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
	1070  		t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
	1071  	}
	1072  	if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
	1073  		t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
	1074  	}
	1075  }
	1076  
	1077  // An interface with several implementations
	1078  type Squarer interface {
	1079  	Square() int
	1080  }
	1081  
	1082  type Int int
	1083  
	1084  func (i Int) Square() int {
	1085  	return int(i * i)
	1086  }
	1087  
	1088  type Float float64
	1089  
	1090  func (f Float) Square() int {
	1091  	return int(f * f)
	1092  }
	1093  
	1094  type Vector []int
	1095  
	1096  func (v Vector) Square() int {
	1097  	sum := 0
	1098  	for _, x := range v {
	1099  		sum += x * x
	1100  	}
	1101  	return sum
	1102  }
	1103  
	1104  type Point struct {
	1105  	X, Y int
	1106  }
	1107  
	1108  func (p Point) Square() int {
	1109  	return p.X*p.X + p.Y*p.Y
	1110  }
	1111  
	1112  // A struct with interfaces in it.
	1113  type InterfaceItem struct {
	1114  	I						 int
	1115  	Sq1, Sq2, Sq3 Squarer
	1116  	F						 float64
	1117  	Sq						[]Squarer
	1118  }
	1119  
	1120  // The same struct without interfaces
	1121  type NoInterfaceItem struct {
	1122  	I int
	1123  	F float64
	1124  }
	1125  
	1126  func TestInterface(t *testing.T) {
	1127  	iVal := Int(3)
	1128  	fVal := Float(5)
	1129  	// Sending a Vector will require that the receiver define a type in the middle of
	1130  	// receiving the value for item2.
	1131  	vVal := Vector{1, 2, 3}
	1132  	b := new(bytes.Buffer)
	1133  	item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
	1134  	// Register the types.
	1135  	Register(Int(0))
	1136  	Register(Float(0))
	1137  	Register(Vector{})
	1138  	err := NewEncoder(b).Encode(item1)
	1139  	if err != nil {
	1140  		t.Error("expected no encode error; got", err)
	1141  	}
	1142  
	1143  	item2 := InterfaceItem{}
	1144  	err = NewDecoder(b).Decode(&item2)
	1145  	if err != nil {
	1146  		t.Fatal("decode:", err)
	1147  	}
	1148  	if item2.I != item1.I {
	1149  		t.Error("normal int did not decode correctly")
	1150  	}
	1151  	if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
	1152  		t.Error("Int did not decode correctly")
	1153  	}
	1154  	if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
	1155  		t.Error("Float did not decode correctly")
	1156  	}
	1157  	if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
	1158  		t.Error("Vector did not decode correctly")
	1159  	}
	1160  	if item2.F != item1.F {
	1161  		t.Error("normal float did not decode correctly")
	1162  	}
	1163  	// Now check that we received a slice of Squarers correctly, including a nil element
	1164  	if len(item1.Sq) != len(item2.Sq) {
	1165  		t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
	1166  	}
	1167  	for i, v1 := range item1.Sq {
	1168  		v2 := item2.Sq[i]
	1169  		if v1 == nil || v2 == nil {
	1170  			if v1 != nil || v2 != nil {
	1171  				t.Errorf("item %d inconsistent nils", i)
	1172  			}
	1173  		} else if v1.Square() != v2.Square() {
	1174  			t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
	1175  		}
	1176  	}
	1177  }
	1178  
	1179  // A struct with all basic types, stored in interfaces.
	1180  type BasicInterfaceItem struct {
	1181  	Int, Int8, Int16, Int32, Int64			interface{}
	1182  	Uint, Uint8, Uint16, Uint32, Uint64 interface{}
	1183  	Float32, Float64										interface{}
	1184  	Complex64, Complex128							 interface{}
	1185  	Bool																interface{}
	1186  	String															interface{}
	1187  	Bytes															 interface{}
	1188  }
	1189  
	1190  func TestInterfaceBasic(t *testing.T) {
	1191  	b := new(bytes.Buffer)
	1192  	item1 := &BasicInterfaceItem{
	1193  		int(1), int8(1), int16(1), int32(1), int64(1),
	1194  		uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
	1195  		float32(1), 1.0,
	1196  		complex64(1i), complex128(1i),
	1197  		true,
	1198  		"hello",
	1199  		[]byte("sailor"),
	1200  	}
	1201  	err := NewEncoder(b).Encode(item1)
	1202  	if err != nil {
	1203  		t.Error("expected no encode error; got", err)
	1204  	}
	1205  
	1206  	item2 := &BasicInterfaceItem{}
	1207  	err = NewDecoder(b).Decode(&item2)
	1208  	if err != nil {
	1209  		t.Fatal("decode:", err)
	1210  	}
	1211  	if !reflect.DeepEqual(item1, item2) {
	1212  		t.Errorf("encode expected %v got %v", item1, item2)
	1213  	}
	1214  	// Hand check a couple for correct types.
	1215  	if v, ok := item2.Bool.(bool); !ok || !v {
	1216  		t.Error("boolean should be true")
	1217  	}
	1218  	if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
	1219  		t.Errorf("string should be %v is %v", item1.String, v)
	1220  	}
	1221  }
	1222  
	1223  type String string
	1224  
	1225  type PtrInterfaceItem struct {
	1226  	Str1 interface{} // basic
	1227  	Str2 interface{} // derived
	1228  }
	1229  
	1230  // We'll send pointers; should receive values.
	1231  // Also check that we can register T but send *T.
	1232  func TestInterfacePointer(t *testing.T) {
	1233  	b := new(bytes.Buffer)
	1234  	str1 := "howdy"
	1235  	str2 := String("kiddo")
	1236  	item1 := &PtrInterfaceItem{
	1237  		&str1,
	1238  		&str2,
	1239  	}
	1240  	// Register the type.
	1241  	Register(str2)
	1242  	err := NewEncoder(b).Encode(item1)
	1243  	if err != nil {
	1244  		t.Error("expected no encode error; got", err)
	1245  	}
	1246  
	1247  	item2 := &PtrInterfaceItem{}
	1248  	err = NewDecoder(b).Decode(&item2)
	1249  	if err != nil {
	1250  		t.Fatal("decode:", err)
	1251  	}
	1252  	// Hand test for correct types and values.
	1253  	if v, ok := item2.Str1.(string); !ok || v != str1 {
	1254  		t.Errorf("basic string failed: %q should be %q", v, str1)
	1255  	}
	1256  	if v, ok := item2.Str2.(String); !ok || v != str2 {
	1257  		t.Errorf("derived type String failed: %q should be %q", v, str2)
	1258  	}
	1259  }
	1260  
	1261  func TestIgnoreInterface(t *testing.T) {
	1262  	iVal := Int(3)
	1263  	fVal := Float(5)
	1264  	// Sending a Point will require that the receiver define a type in the middle of
	1265  	// receiving the value for item2.
	1266  	pVal := Point{2, 3}
	1267  	b := new(bytes.Buffer)
	1268  	item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
	1269  	// Register the types.
	1270  	Register(Int(0))
	1271  	Register(Float(0))
	1272  	Register(Point{})
	1273  	err := NewEncoder(b).Encode(item1)
	1274  	if err != nil {
	1275  		t.Error("expected no encode error; got", err)
	1276  	}
	1277  
	1278  	item2 := NoInterfaceItem{}
	1279  	err = NewDecoder(b).Decode(&item2)
	1280  	if err != nil {
	1281  		t.Fatal("decode:", err)
	1282  	}
	1283  	if item2.I != item1.I {
	1284  		t.Error("normal int did not decode correctly")
	1285  	}
	1286  	if item2.F != item1.F {
	1287  		t.Error("normal float did not decode correctly")
	1288  	}
	1289  }
	1290  
	1291  type U struct {
	1292  	A int
	1293  	B string
	1294  	c float64
	1295  	D uint
	1296  }
	1297  
	1298  func TestUnexportedFields(t *testing.T) {
	1299  	var u0 U
	1300  	u0.A = 17
	1301  	u0.B = "hello"
	1302  	u0.c = 3.14159
	1303  	u0.D = 23
	1304  	b := new(bytes.Buffer)
	1305  	NewEncoder(b).Encode(u0)
	1306  	dec := NewDecoder(b)
	1307  	var u1 U
	1308  	u1.c = 1234.
	1309  	err := dec.Decode(&u1)
	1310  	if err != nil {
	1311  		t.Fatal("decode error:", err)
	1312  	}
	1313  	if u0.A != u1.A || u0.B != u1.B || u0.D != u1.D {
	1314  		t.Errorf("u1->u0: expected %v; got %v", u0, u1)
	1315  	}
	1316  	if u1.c != 1234. {
	1317  		t.Error("u1.c modified")
	1318  	}
	1319  }
	1320  
	1321  var singletons = []interface{}{
	1322  	true,
	1323  	7,
	1324  	uint(10),
	1325  	3.2,
	1326  	"hello",
	1327  	[3]int{11, 22, 33},
	1328  	[]float32{0.5, 0.25, 0.125},
	1329  	map[string]int{"one": 1, "two": 2},
	1330  }
	1331  
	1332  func TestDebugSingleton(t *testing.T) {
	1333  	if debugFunc == nil {
	1334  		return
	1335  	}
	1336  	b := new(bytes.Buffer)
	1337  	// Accumulate a number of values and print them out all at once.
	1338  	for _, x := range singletons {
	1339  		err := NewEncoder(b).Encode(x)
	1340  		if err != nil {
	1341  			t.Fatal("encode:", err)
	1342  		}
	1343  	}
	1344  	debugFunc(b)
	1345  }
	1346  
	1347  // A type that won't be defined in the gob until we send it in an interface value.
	1348  type OnTheFly struct {
	1349  	A int
	1350  }
	1351  
	1352  type DT struct {
	1353  	//	X OnTheFly
	1354  	A		 int
	1355  	B		 string
	1356  	C		 float64
	1357  	I		 interface{}
	1358  	J		 interface{}
	1359  	I_nil interface{}
	1360  	M		 map[string]int
	1361  	T		 [3]int
	1362  	S		 []string
	1363  }
	1364  
	1365  func newDT() DT {
	1366  	var dt DT
	1367  	dt.A = 17
	1368  	dt.B = "hello"
	1369  	dt.C = 3.14159
	1370  	dt.I = 271828
	1371  	dt.J = OnTheFly{3}
	1372  	dt.I_nil = nil
	1373  	dt.M = map[string]int{"one": 1, "two": 2}
	1374  	dt.T = [3]int{11, 22, 33}
	1375  	dt.S = []string{"hi", "joe"}
	1376  	return dt
	1377  }
	1378  
	1379  func TestDebugStruct(t *testing.T) {
	1380  	if debugFunc == nil {
	1381  		return
	1382  	}
	1383  	Register(OnTheFly{})
	1384  	dt := newDT()
	1385  	b := new(bytes.Buffer)
	1386  	err := NewEncoder(b).Encode(dt)
	1387  	if err != nil {
	1388  		t.Fatal("encode:", err)
	1389  	}
	1390  	debugBuffer := bytes.NewBuffer(b.Bytes())
	1391  	dt2 := &DT{}
	1392  	err = NewDecoder(b).Decode(&dt2)
	1393  	if err != nil {
	1394  		t.Error("decode:", err)
	1395  	}
	1396  	debugFunc(debugBuffer)
	1397  }
	1398  
	1399  func encFuzzDec(rng *rand.Rand, in interface{}) error {
	1400  	buf := new(bytes.Buffer)
	1401  	enc := NewEncoder(buf)
	1402  	if err := enc.Encode(&in); err != nil {
	1403  		return err
	1404  	}
	1405  
	1406  	b := buf.Bytes()
	1407  	for i, bi := range b {
	1408  		if rng.Intn(10) < 3 {
	1409  			b[i] = bi + uint8(rng.Intn(256))
	1410  		}
	1411  	}
	1412  
	1413  	dec := NewDecoder(buf)
	1414  	var e interface{}
	1415  	if err := dec.Decode(&e); err != nil {
	1416  		return err
	1417  	}
	1418  	return nil
	1419  }
	1420  
	1421  // This does some "fuzz testing" by attempting to decode a sequence of random bytes.
	1422  func TestFuzz(t *testing.T) {
	1423  	if !*doFuzzTests {
	1424  		t.Skipf("disabled; run with -gob.fuzz to enable")
	1425  	}
	1426  
	1427  	// all possible inputs
	1428  	input := []interface{}{
	1429  		new(int),
	1430  		new(float32),
	1431  		new(float64),
	1432  		new(complex128),
	1433  		&ByteStruct{255},
	1434  		&ArrayStruct{},
	1435  		&StringStruct{"hello"},
	1436  		&GobTest1{0, &StringStruct{"hello"}},
	1437  	}
	1438  	testFuzz(t, time.Now().UnixNano(), 100, input...)
	1439  }
	1440  
	1441  func TestFuzzRegressions(t *testing.T) {
	1442  	if !*doFuzzTests {
	1443  		t.Skipf("disabled; run with -gob.fuzz to enable")
	1444  	}
	1445  
	1446  	// An instance triggering a type name of length ~102 GB.
	1447  	testFuzz(t, 1328492090837718000, 100, new(float32))
	1448  	// An instance triggering a type name of 1.6 GB.
	1449  	// Note: can take several minutes to run.
	1450  	testFuzz(t, 1330522872628565000, 100, new(int))
	1451  }
	1452  
	1453  func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) {
	1454  	for _, e := range input {
	1455  		t.Logf("seed=%d n=%d e=%T", seed, n, e)
	1456  		rng := rand.New(rand.NewSource(seed))
	1457  		for i := 0; i < n; i++ {
	1458  			encFuzzDec(rng, e)
	1459  		}
	1460  	}
	1461  }
	1462  
	1463  // TestFuzzOneByte tries to decode corrupted input sequences
	1464  // and checks that no panic occurs.
	1465  func TestFuzzOneByte(t *testing.T) {
	1466  	if !*doFuzzTests {
	1467  		t.Skipf("disabled; run with -gob.fuzz to enable")
	1468  	}
	1469  
	1470  	buf := new(bytes.Buffer)
	1471  	Register(OnTheFly{})
	1472  	dt := newDT()
	1473  	if err := NewEncoder(buf).Encode(dt); err != nil {
	1474  		t.Fatal(err)
	1475  	}
	1476  	s := buf.String()
	1477  
	1478  	indices := make([]int, 0, len(s))
	1479  	for i := 0; i < len(s); i++ {
	1480  		switch i {
	1481  		case 14, 167, 231, 265: // a slice length, corruptions are not handled yet.
	1482  			continue
	1483  		case 248:
	1484  			// Large map size, which currently causes an out of memory panic.
	1485  			// See golang.org/issue/24308 and golang.org/issue/20221.
	1486  			continue
	1487  		}
	1488  		indices = append(indices, i)
	1489  	}
	1490  	if testing.Short() {
	1491  		indices = []int{1, 111, 178} // known fixed panics
	1492  	}
	1493  	for _, i := range indices {
	1494  		for j := 0; j < 256; j += 3 {
	1495  			b := []byte(s)
	1496  			b[i] ^= byte(j)
	1497  			var e DT
	1498  			func() {
	1499  				defer func() {
	1500  					if p := recover(); p != nil {
	1501  						t.Errorf("crash for b[%d] ^= 0x%x", i, j)
	1502  						panic(p)
	1503  					}
	1504  				}()
	1505  				err := NewDecoder(bytes.NewReader(b)).Decode(&e)
	1506  				_ = err
	1507  			}()
	1508  		}
	1509  	}
	1510  }
	1511  
	1512  // Don't crash, just give error with invalid type id.
	1513  // Issue 9649.
	1514  func TestErrorInvalidTypeId(t *testing.T) {
	1515  	data := []byte{0x01, 0x00, 0x01, 0x00}
	1516  	d := NewDecoder(bytes.NewReader(data))
	1517  	// When running d.Decode(&foo) the first time the decoder stops
	1518  	// after []byte{0x01, 0x00} and reports an errBadType. Running
	1519  	// d.Decode(&foo) again on exactly the same input sequence should
	1520  	// give another errBadType, but instead caused a panic because
	1521  	// decoderMap wasn't cleaned up properly after the first error.
	1522  	for i := 0; i < 2; i++ {
	1523  		var foo struct{}
	1524  		err := d.Decode(&foo)
	1525  		if err != errBadType {
	1526  			t.Fatalf("decode: expected %s, got %s", errBadType, err)
	1527  		}
	1528  	}
	1529  }
	1530  

View as plain text