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.
19 var doFuzzTests = flag.Bool("gob.fuzz", false, "run the fuzz tests, which are large and very slow")
21 // Guarantee encoding format by comparing some encodings to hand-written values
27 var encodeT = []EncodeT{
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}},
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.
52 func newDecBuffer(data []byte) *decBuffer {
58 // Test basic encode/decode routines for unsigned integers
59 func TestUintCodec(t *testing.T) {
62 encState := newEncoderState(b)
63 for _, tt := range encodeT {
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())
70 for u := uint64(0); ; u = (u + 1) * 7 {
72 encState.encodeUint(u)
73 decState := newDecodeState(newDecBuffer(b.Bytes()))
74 v := decState.decodeUint()
76 t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
84 func verifyInt(i int64, t *testing.T) {
86 var b = new(encBuffer)
87 encState := newEncoderState(b)
89 decState := newDecodeState(newDecBuffer(b.Bytes()))
90 j := decState.decodeInt()
92 t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
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
108 verifyInt(-1<<63, t) // a tricky case
111 // The result of encoding a true boolean with field number 7
112 var boolResult = []byte{0x07, 0x01}
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}
119 // The result of encoding a number 17+19i with field number 7
120 var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
122 // The result of encoding "hello" with field number 7
123 var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
125 func newDecodeState(buf *decBuffer) *decoderState {
126 d := new(decoderState)
131 func newEncoderState(b *encBuffer) *encoderState {
133 state := &encoderState{enc: nil, b: b}
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)
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
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())
323 func execDec(instr *decInstr, state *decoderState, t *testing.T, value reflect.Value) {
325 v := int(state.decodeUint())
326 if v+state.fieldnum != 6 {
327 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
329 instr.op(instr, state, value.Elem())
333 func newDecodeStateFromData(data []byte) *decoderState {
334 b := newDecBuffer(data)
335 state := newDecodeState(b)
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")
348 instr := &decInstr{decBool, 6, nil, ovfl}
349 state := newDecodeStateFromData(boolResult)
350 execDec(instr, state, t, reflect.ValueOf(&data))
352 t.Errorf("bool a = %v not true", data)
358 instr := &decInstr{decOpTable[reflect.Int], 6, nil, ovfl}
359 state := newDecodeStateFromData(signedResult)
360 execDec(instr, state, t, reflect.ValueOf(&data))
362 t.Errorf("int a = %v not 17", data)
369 instr := &decInstr{decOpTable[reflect.Uint], 6, nil, ovfl}
370 state := newDecodeStateFromData(unsignedResult)
371 execDec(instr, state, t, reflect.ValueOf(&data))
373 t.Errorf("uint a = %v not 17", data)
380 instr := &decInstr{decInt8, 6, nil, ovfl}
381 state := newDecodeStateFromData(signedResult)
382 execDec(instr, state, t, reflect.ValueOf(&data))
384 t.Errorf("int8 a = %v not 17", data)
391 instr := &decInstr{decUint8, 6, nil, ovfl}
392 state := newDecodeStateFromData(unsignedResult)
393 execDec(instr, state, t, reflect.ValueOf(&data))
395 t.Errorf("uint8 a = %v not 17", data)
402 instr := &decInstr{decInt16, 6, nil, ovfl}
403 state := newDecodeStateFromData(signedResult)
404 execDec(instr, state, t, reflect.ValueOf(&data))
406 t.Errorf("int16 a = %v not 17", data)
413 instr := &decInstr{decUint16, 6, nil, ovfl}
414 state := newDecodeStateFromData(unsignedResult)
415 execDec(instr, state, t, reflect.ValueOf(&data))
417 t.Errorf("uint16 a = %v not 17", data)
424 instr := &decInstr{decInt32, 6, nil, ovfl}
425 state := newDecodeStateFromData(signedResult)
426 execDec(instr, state, t, reflect.ValueOf(&data))
428 t.Errorf("int32 a = %v not 17", data)
435 instr := &decInstr{decUint32, 6, nil, ovfl}
436 state := newDecodeStateFromData(unsignedResult)
437 execDec(instr, state, t, reflect.ValueOf(&data))
439 t.Errorf("uint32 a = %v not 17", data)
446 instr := &decInstr{decOpTable[reflect.Uintptr], 6, nil, ovfl}
447 state := newDecodeStateFromData(unsignedResult)
448 execDec(instr, state, t, reflect.ValueOf(&data))
450 t.Errorf("uintptr a = %v not 17", data)
457 instr := &decInstr{decInt64, 6, nil, ovfl}
458 state := newDecodeStateFromData(signedResult)
459 execDec(instr, state, t, reflect.ValueOf(&data))
461 t.Errorf("int64 a = %v not 17", data)
468 instr := &decInstr{decUint64, 6, nil, ovfl}
469 state := newDecodeStateFromData(unsignedResult)
470 execDec(instr, state, t, reflect.ValueOf(&data))
472 t.Errorf("uint64 a = %v not 17", data)
479 instr := &decInstr{decFloat32, 6, nil, ovfl}
480 state := newDecodeStateFromData(floatResult)
481 execDec(instr, state, t, reflect.ValueOf(&data))
483 t.Errorf("float32 a = %v not 17", data)
490 instr := &decInstr{decFloat64, 6, nil, ovfl}
491 state := newDecodeStateFromData(floatResult)
492 execDec(instr, state, t, reflect.ValueOf(&data))
494 t.Errorf("float64 a = %v not 17", data)
501 instr := &decInstr{decOpTable[reflect.Complex64], 6, nil, ovfl}
502 state := newDecodeStateFromData(complexResult)
503 execDec(instr, state, t, reflect.ValueOf(&data))
505 t.Errorf("complex a = %v not 17+19i", data)
512 instr := &decInstr{decOpTable[reflect.Complex128], 6, nil, ovfl}
513 state := newDecodeStateFromData(complexResult)
514 execDec(instr, state, t, reflect.ValueOf(&data))
516 t.Errorf("complex a = %v not 17+19i", data)
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))
534 instr := &decInstr{decString, 6, nil, ovfl}
535 state := newDecodeStateFromData(bytesResult)
536 execDec(instr, state, t, reflect.ValueOf(&data))
538 t.Errorf(`bytes a = %q not "hello"`, data)
543 func TestEndToEnd(t *testing.T) {
553 M map[string]*float64
555 Mstring map[string]string
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.
575 var comp1 complex128 = complex(1.0, 1.0)
576 var comp2 complex128 = complex(1.0, 1.0)
583 var floatArr1 [2]*float64
586 var floatArr2 [2]*float64
593 M: map[string]*float64{"pi": &pi, "e": &e},
594 M2: map[int]T3{4: T3{X: pi, Z: &meaning}, 10: T3{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},
604 S: "Now is the time",
605 Y: []byte("hello, sailor"),
606 T: &T2{"this is T2"},
608 b := new(bytes.Buffer)
609 err := NewEncoder(b).Encode(t1)
611 t.Error("encode:", err)
614 err = NewDecoder(b).Decode(&_t1)
616 t.Fatal("decode:", err)
618 if !reflect.DeepEqual(t1, &_t1) {
619 t.Errorf("encode expected %v got %v", *t1, _t1)
621 // Be absolutely sure the received map is non-nil.
622 if t1.EmptyMap == nil {
623 t.Errorf("nil map sent")
625 if _t1.EmptyMap == nil {
626 t.Errorf("nil map received")
630 func TestOverflow(t *testing.T) {
642 b := new(bytes.Buffer)
649 Maxi: math.MaxInt8 + 1,
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)
662 Mini: math.MinInt8 - 1,
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)
674 Maxi: math.MaxInt16 + 1,
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)
687 Mini: math.MinInt16 - 1,
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)
699 Maxi: math.MaxInt32 + 1,
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)
712 Mini: math.MinInt32 - 1,
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)
724 Maxu: math.MaxUint8 + 1,
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)
739 Maxu: math.MaxUint16 + 1,
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)
754 Maxu: math.MaxUint32 + 1,
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)
769 Maxf: math.MaxFloat32 * 2,
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)
785 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
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)
799 func TestNesting(t *testing.T) {
808 b := new(bytes.Buffer)
809 NewEncoder(b).Encode(rt)
812 err := dec.Decode(&drt)
814 t.Fatal("decoder error:", err)
817 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
820 t.Errorf("nesting: recursion failed")
822 if drt.Next.A != rt.Next.A {
823 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
827 // These three structures have the same data with different indirections
847 func TestAutoIndirection(t *testing.T) {
848 // First transfer t1 into t0
860 b := new(bytes.Buffer)
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)
870 // Now transfer t2 into 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)
890 // Now transfer t0 into t1
891 t0 = T0{17, 177, 1777, 17777}
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)
900 // Now transfer t0 into 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)
909 // Now do t2 again but without pre-allocated pointers.
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)
934 func TestReorderedFields(t *testing.T) {
939 b := new(bytes.Buffer)
940 NewEncoder(b).Encode(rt0)
943 // Wire type is RT0, local type is RT1.
944 err := dec.Decode(&rt1)
946 t.Fatal("decode error:", err)
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)
953 // Like an RT0 but with fields we'll ignore on the decode side.
963 Ignore_m map[string]int
967 func TestIgnoredFields(t *testing.T) {
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
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}
982 b := new(bytes.Buffer)
983 NewEncoder(b).Encode(it0)
986 // Wire type is IT0, local type is RT1.
987 err := dec.Decode(&rt1)
989 t.Error("error: ", err)
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)
996 func TestBadRecursiveType(t *testing.T) {
999 b := new(bytes.Buffer)
1000 err := NewEncoder(b).Encode(&rec)
1002 t.Error("expected error; got none")
1003 } else if !strings.Contains(err.Error(), "recursive") {
1004 t.Error("expected recursive type error; got", err)
1006 // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
1009 type Indirect struct {
1012 M ****map[string]int
1015 type Direct struct {
1021 func TestIndirectSliceMapArray(t *testing.T) {
1022 // Marshal indirect, unmarshal to direct.
1027 ***i.A = [3]int{1, 2, 3}
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)
1041 err := dec.Decode(&d)
1043 t.Error("error: ", err)
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)
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)
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)
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}
1060 NewEncoder(b).Encode(d)
1062 err = dec.Decode(&i)
1064 t.Fatal("error: ", err)
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)
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)
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)
1077 // An interface with several implementations
1078 type Squarer interface {
1084 func (i Int) Square() int {
1090 func (f Float) Square() int {
1096 func (v Vector) Square() int {
1098 for _, x := range v {
1108 func (p Point) Square() int {
1109 return p.X*p.X + p.Y*p.Y
1112 // A struct with interfaces in it.
1113 type InterfaceItem struct {
1115 Sq1, Sq2, Sq3 Squarer
1120 // The same struct without interfaces
1121 type NoInterfaceItem struct {
1126 func TestInterface(t *testing.T) {
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.
1138 err := NewEncoder(b).Encode(item1)
1140 t.Error("expected no encode error; got", err)
1143 item2 := InterfaceItem{}
1144 err = NewDecoder(b).Decode(&item2)
1146 t.Fatal("decode:", err)
1148 if item2.I != item1.I {
1149 t.Error("normal int did not decode correctly")
1151 if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1152 t.Error("Int did not decode correctly")
1154 if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1155 t.Error("Float did not decode correctly")
1157 if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1158 t.Error("Vector did not decode correctly")
1160 if item2.F != item1.F {
1161 t.Error("normal float did not decode correctly")
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))
1167 for i, v1 := range item1.Sq {
1169 if v1 == nil || v2 == nil {
1170 if v1 != nil || v2 != nil {
1171 t.Errorf("item %d inconsistent nils", i)
1173 } else if v1.Square() != v2.Square() {
1174 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
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{}
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),
1196 complex64(1i), complex128(1i),
1201 err := NewEncoder(b).Encode(item1)
1203 t.Error("expected no encode error; got", err)
1206 item2 := &BasicInterfaceItem{}
1207 err = NewDecoder(b).Decode(&item2)
1209 t.Fatal("decode:", err)
1211 if !reflect.DeepEqual(item1, item2) {
1212 t.Errorf("encode expected %v got %v", item1, item2)
1214 // Hand check a couple for correct types.
1215 if v, ok := item2.Bool.(bool); !ok || !v {
1216 t.Error("boolean should be true")
1218 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1219 t.Errorf("string should be %v is %v", item1.String, v)
1225 type PtrInterfaceItem struct {
1226 Str1 interface{} // basic
1227 Str2 interface{} // derived
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)
1235 str2 := String("kiddo")
1236 item1 := &PtrInterfaceItem{
1240 // Register the type.
1242 err := NewEncoder(b).Encode(item1)
1244 t.Error("expected no encode error; got", err)
1247 item2 := &PtrInterfaceItem{}
1248 err = NewDecoder(b).Decode(&item2)
1250 t.Fatal("decode:", err)
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)
1256 if v, ok := item2.Str2.(String); !ok || v != str2 {
1257 t.Errorf("derived type String failed: %q should be %q", v, str2)
1261 func TestIgnoreInterface(t *testing.T) {
1264 // Sending a Point will require that the receiver define a type in the middle of
1265 // receiving the value for item2.
1267 b := new(bytes.Buffer)
1268 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1269 // Register the types.
1273 err := NewEncoder(b).Encode(item1)
1275 t.Error("expected no encode error; got", err)
1278 item2 := NoInterfaceItem{}
1279 err = NewDecoder(b).Decode(&item2)
1281 t.Fatal("decode:", err)
1283 if item2.I != item1.I {
1284 t.Error("normal int did not decode correctly")
1286 if item2.F != item1.F {
1287 t.Error("normal float did not decode correctly")
1298 func TestUnexportedFields(t *testing.T) {
1304 b := new(bytes.Buffer)
1305 NewEncoder(b).Encode(u0)
1306 dec := NewDecoder(b)
1309 err := dec.Decode(&u1)
1311 t.Fatal("decode error:", err)
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)
1317 t.Error("u1.c modified")
1321 var singletons = []interface{}{
1328 []float32{0.5, 0.25, 0.125},
1329 map[string]int{"one": 1, "two": 2},
1332 func TestDebugSingleton(t *testing.T) {
1333 if debugFunc == nil {
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)
1341 t.Fatal("encode:", err)
1347 // A type that won't be defined in the gob until we send it in an interface value.
1348 type OnTheFly struct {
1373 dt.M = map[string]int{"one": 1, "two": 2}
1374 dt.T = [3]int{11, 22, 33}
1375 dt.S = []string{"hi", "joe"}
1379 func TestDebugStruct(t *testing.T) {
1380 if debugFunc == nil {
1383 Register(OnTheFly{})
1385 b := new(bytes.Buffer)
1386 err := NewEncoder(b).Encode(dt)
1388 t.Fatal("encode:", err)
1390 debugBuffer := bytes.NewBuffer(b.Bytes())
1392 err = NewDecoder(b).Decode(&dt2)
1394 t.Error("decode:", err)
1396 debugFunc(debugBuffer)
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 {
1407 for i, bi := range b {
1408 if rng.Intn(10) < 3 {
1409 b[i] = bi + uint8(rng.Intn(256))
1413 dec := NewDecoder(buf)
1415 if err := dec.Decode(&e); err != nil {
1421 // This does some "fuzz testing" by attempting to decode a sequence of random bytes.
1422 func TestFuzz(t *testing.T) {
1424 t.Logf("disabled; run with -gob.fuzz to enable")
1428 // all possible inputs
1429 input := []interface{}{
1436 &StringStruct{"hello"},
1437 &GobTest1{0, &StringStruct{"hello"}},
1439 testFuzz(t, time.Now().UnixNano(), 100, input...)
1442 func TestFuzzRegressions(t *testing.T) {
1444 t.Logf("disabled; run with -gob.fuzz to enable")
1448 // An instance triggering a type name of length ~102 GB.
1449 testFuzz(t, 1328492090837718000, 100, new(float32))
1450 // An instance triggering a type name of 1.6 GB.
1451 // Note: can take several minutes to run.
1452 testFuzz(t, 1330522872628565000, 100, new(int))
1455 func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) {
1456 for _, e := range input {
1457 t.Logf("seed=%d n=%d e=%T", seed, n, e)
1458 rng := rand.New(rand.NewSource(seed))
1459 for i := 0; i < n; i++ {
1465 // TestFuzzOneByte tries to decode corrupted input sequences
1466 // and checks that no panic occurs.
1467 func TestFuzzOneByte(t *testing.T) {
1468 buf := new(bytes.Buffer)
1469 Register(OnTheFly{})
1471 if err := NewEncoder(buf).Encode(dt); err != nil {
1476 indices := make([]int, 0, len(s))
1477 for i := 0; i < len(s); i++ {
1479 case 14, 167, 231, 265: // a slice length, corruptions are not handled yet.
1482 // Large map size, which currently causes an out of memory panic.
1483 // See golang.org/issue/24308 and golang.org/issue/20221.
1486 indices = append(indices, i)
1488 if testing.Short() {
1489 indices = []int{1, 111, 178} // known fixed panics
1491 for _, i := range indices {
1492 for j := 0; j < 256; j += 3 {
1498 if p := recover(); p != nil {
1499 t.Errorf("crash for b[%d] ^= 0x%x", i, j)
1503 err := NewDecoder(bytes.NewReader(b)).Decode(&e)
1510 // Don't crash, just give error with invalid type id.
1512 func TestErrorInvalidTypeId(t *testing.T) {
1513 data := []byte{0x01, 0x00, 0x01, 0x00}
1514 d := NewDecoder(bytes.NewReader(data))
1515 // When running d.Decode(&foo) the first time the decoder stops
1516 // after []byte{0x01, 0x00} and reports an errBadType. Running
1517 // d.Decode(&foo) again on exactly the same input sequence should
1518 // give another errBadType, but instead caused a panic because
1519 // decoderMap wasn't cleaned up properly after the first error.
1520 for i := 0; i < 2; i++ {
1522 err := d.Decode(&foo)
1523 if err != errBadType {
1524 t.Fatalf("decode: expected %s, got %s", errBadType, err)