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.
17 // Guarantee encoding format by comparing some encodings to hand-written values
23 var encodeT = []EncodeT{
26 {0xFF, []byte{0xFF, 0xFF}},
27 {0xFFFF, []byte{0xFE, 0xFF, 0xFF}},
28 {0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}},
29 {0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}},
30 {0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
31 {0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
32 {0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
33 {0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
34 {0x1111, []byte{0xFE, 0x11, 0x11}},
35 {0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
36 {0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}},
37 {1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
40 // testError is meant to be used as a deferred function to turn a panic(gobError) into a
41 // plain test.Error call.
42 func testError(t *testing.T) {
43 if e := recover(); e != nil {
44 t.Error(e.(gobError).Error) // Will re-panic if not one of our errors, such as a runtime error.
49 // Test basic encode/decode routines for unsigned integers
50 func TestUintCodec(t *testing.T) {
52 b := new(bytes.Buffer)
53 encState := newEncoderState(b)
54 for _, tt := range encodeT {
56 encState.encodeUint(tt.x)
57 if !bytes.Equal(tt.b, b.Bytes()) {
58 t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
61 decState := newDecodeState(b)
62 for u := uint64(0); ; u = (u + 1) * 7 {
64 encState.encodeUint(u)
65 v := decState.decodeUint()
67 t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
75 func verifyInt(i int64, t *testing.T) {
77 var b = new(bytes.Buffer)
78 encState := newEncoderState(b)
80 decState := newDecodeState(b)
81 decState.buf = make([]byte, 8)
82 j := decState.decodeInt()
84 t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
88 // Test basic encode/decode routines for signed integers
89 func TestIntCodec(t *testing.T) {
90 for u := uint64(0); ; u = (u + 1) * 7 {
91 // Do positive and negative values
100 verifyInt(-1<<63, t) // a tricky case
103 // The result of encoding a true boolean with field number 7
104 var boolResult = []byte{0x07, 0x01}
105 // The result of encoding a number 17 with field number 7
106 var signedResult = []byte{0x07, 2 * 17}
107 var unsignedResult = []byte{0x07, 17}
108 var floatResult = []byte{0x07, 0xFE, 0x31, 0x40}
109 // The result of encoding a number 17+19i with field number 7
110 var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
111 // The result of encoding "hello" with field number 7
112 var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
114 func newDecodeState(buf *bytes.Buffer) *decoderState {
115 d := new(decoderState)
117 d.buf = make([]byte, uint64Size)
121 func newEncoderState(b *bytes.Buffer) *encoderState {
123 state := &encoderState{enc: nil, b: b}
128 // Test instruction execution for encoding.
129 // Do not run the machine yet; instead do individual instructions crafted by hand.
130 func TestScalarEncInstructions(t *testing.T) {
131 var b = new(bytes.Buffer)
135 data := struct{ a bool }{true}
136 instr := &encInstr{encBool, 6, 0, 0}
137 state := newEncoderState(b)
138 instr.op(instr, state, unsafe.Pointer(&data))
139 if !bytes.Equal(boolResult, b.Bytes()) {
140 t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
147 data := struct{ a int }{17}
148 instr := &encInstr{encInt, 6, 0, 0}
149 state := newEncoderState(b)
150 instr.op(instr, state, unsafe.Pointer(&data))
151 if !bytes.Equal(signedResult, b.Bytes()) {
152 t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
159 data := struct{ a uint }{17}
160 instr := &encInstr{encUint, 6, 0, 0}
161 state := newEncoderState(b)
162 instr.op(instr, state, unsafe.Pointer(&data))
163 if !bytes.Equal(unsignedResult, b.Bytes()) {
164 t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
171 data := struct{ a int8 }{17}
172 instr := &encInstr{encInt8, 6, 0, 0}
173 state := newEncoderState(b)
174 instr.op(instr, state, unsafe.Pointer(&data))
175 if !bytes.Equal(signedResult, b.Bytes()) {
176 t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
183 data := struct{ a uint8 }{17}
184 instr := &encInstr{encUint8, 6, 0, 0}
185 state := newEncoderState(b)
186 instr.op(instr, state, unsafe.Pointer(&data))
187 if !bytes.Equal(unsignedResult, b.Bytes()) {
188 t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
195 data := struct{ a int16 }{17}
196 instr := &encInstr{encInt16, 6, 0, 0}
197 state := newEncoderState(b)
198 instr.op(instr, state, unsafe.Pointer(&data))
199 if !bytes.Equal(signedResult, b.Bytes()) {
200 t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
207 data := struct{ a uint16 }{17}
208 instr := &encInstr{encUint16, 6, 0, 0}
209 state := newEncoderState(b)
210 instr.op(instr, state, unsafe.Pointer(&data))
211 if !bytes.Equal(unsignedResult, b.Bytes()) {
212 t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
219 data := struct{ a int32 }{17}
220 instr := &encInstr{encInt32, 6, 0, 0}
221 state := newEncoderState(b)
222 instr.op(instr, state, unsafe.Pointer(&data))
223 if !bytes.Equal(signedResult, b.Bytes()) {
224 t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
231 data := struct{ a uint32 }{17}
232 instr := &encInstr{encUint32, 6, 0, 0}
233 state := newEncoderState(b)
234 instr.op(instr, state, unsafe.Pointer(&data))
235 if !bytes.Equal(unsignedResult, b.Bytes()) {
236 t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
243 data := struct{ a int64 }{17}
244 instr := &encInstr{encInt64, 6, 0, 0}
245 state := newEncoderState(b)
246 instr.op(instr, state, unsafe.Pointer(&data))
247 if !bytes.Equal(signedResult, b.Bytes()) {
248 t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
255 data := struct{ a uint64 }{17}
256 instr := &encInstr{encUint64, 6, 0, 0}
257 state := newEncoderState(b)
258 instr.op(instr, state, unsafe.Pointer(&data))
259 if !bytes.Equal(unsignedResult, b.Bytes()) {
260 t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
267 data := struct{ a float32 }{17}
268 instr := &encInstr{encFloat32, 6, 0, 0}
269 state := newEncoderState(b)
270 instr.op(instr, state, unsafe.Pointer(&data))
271 if !bytes.Equal(floatResult, b.Bytes()) {
272 t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
279 data := struct{ a float64 }{17}
280 instr := &encInstr{encFloat64, 6, 0, 0}
281 state := newEncoderState(b)
282 instr.op(instr, state, unsafe.Pointer(&data))
283 if !bytes.Equal(floatResult, b.Bytes()) {
284 t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
291 data := struct{ a []byte }{[]byte("hello")}
292 instr := &encInstr{encUint8Array, 6, 0, 0}
293 state := newEncoderState(b)
294 instr.op(instr, state, unsafe.Pointer(&data))
295 if !bytes.Equal(bytesResult, b.Bytes()) {
296 t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
303 data := struct{ a string }{"hello"}
304 instr := &encInstr{encString, 6, 0, 0}
305 state := newEncoderState(b)
306 instr.op(instr, state, unsafe.Pointer(&data))
307 if !bytes.Equal(bytesResult, b.Bytes()) {
308 t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
313 func execDec(typ string, instr *decInstr, state *decoderState, t *testing.T, p unsafe.Pointer) {
315 v := int(state.decodeUint())
316 if v+state.fieldnum != 6 {
317 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
319 instr.op(instr, state, decIndirect(p, instr.indir))
323 func newDecodeStateFromData(data []byte) *decoderState {
324 b := bytes.NewBuffer(data)
325 state := newDecodeState(b)
330 // Test instruction execution for decoding.
331 // Do not run the machine yet; instead do individual instructions crafted by hand.
332 func TestScalarDecInstructions(t *testing.T) {
333 ovfl := os.ErrorString("overflow")
340 instr := &decInstr{decBool, 6, 0, 0, ovfl}
341 state := newDecodeStateFromData(boolResult)
342 execDec("bool", instr, state, t, unsafe.Pointer(&data))
344 t.Errorf("bool a = %v not true", data.a)
352 instr := &decInstr{decOpTable[reflect.Int], 6, 0, 0, ovfl}
353 state := newDecodeStateFromData(signedResult)
354 execDec("int", instr, state, t, unsafe.Pointer(&data))
356 t.Errorf("int a = %v not 17", data.a)
365 instr := &decInstr{decOpTable[reflect.Uint], 6, 0, 0, ovfl}
366 state := newDecodeStateFromData(unsignedResult)
367 execDec("uint", instr, state, t, unsafe.Pointer(&data))
369 t.Errorf("uint a = %v not 17", data.a)
378 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
379 state := newDecodeStateFromData(signedResult)
380 execDec("int8", instr, state, t, unsafe.Pointer(&data))
382 t.Errorf("int8 a = %v not 17", data.a)
391 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
392 state := newDecodeStateFromData(unsignedResult)
393 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
395 t.Errorf("uint8 a = %v not 17", data.a)
404 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
405 state := newDecodeStateFromData(signedResult)
406 execDec("int16", instr, state, t, unsafe.Pointer(&data))
408 t.Errorf("int16 a = %v not 17", data.a)
417 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
418 state := newDecodeStateFromData(unsignedResult)
419 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
421 t.Errorf("uint16 a = %v not 17", data.a)
430 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
431 state := newDecodeStateFromData(signedResult)
432 execDec("int32", instr, state, t, unsafe.Pointer(&data))
434 t.Errorf("int32 a = %v not 17", data.a)
443 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
444 state := newDecodeStateFromData(unsignedResult)
445 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
447 t.Errorf("uint32 a = %v not 17", data.a)
456 instr := &decInstr{decOpTable[reflect.Uintptr], 6, 0, 0, ovfl}
457 state := newDecodeStateFromData(unsignedResult)
458 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
460 t.Errorf("uintptr a = %v not 17", data.a)
469 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
470 state := newDecodeStateFromData(signedResult)
471 execDec("int64", instr, state, t, unsafe.Pointer(&data))
473 t.Errorf("int64 a = %v not 17", data.a)
482 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
483 state := newDecodeStateFromData(unsignedResult)
484 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
486 t.Errorf("uint64 a = %v not 17", data.a)
495 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
496 state := newDecodeStateFromData(floatResult)
497 execDec("float32", instr, state, t, unsafe.Pointer(&data))
499 t.Errorf("float32 a = %v not 17", data.a)
508 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
509 state := newDecodeStateFromData(floatResult)
510 execDec("float64", instr, state, t, unsafe.Pointer(&data))
512 t.Errorf("float64 a = %v not 17", data.a)
521 instr := &decInstr{decOpTable[reflect.Complex64], 6, 0, 0, ovfl}
522 state := newDecodeStateFromData(complexResult)
523 execDec("complex", instr, state, t, unsafe.Pointer(&data))
524 if data.a != 17+19i {
525 t.Errorf("complex a = %v not 17+19i", data.a)
534 instr := &decInstr{decOpTable[reflect.Complex128], 6, 0, 0, ovfl}
535 state := newDecodeStateFromData(complexResult)
536 execDec("complex", instr, state, t, unsafe.Pointer(&data))
537 if data.a != 17+19i {
538 t.Errorf("complex a = %v not 17+19i", data.a)
547 instr := &decInstr{decUint8Array, 6, 0, 0, ovfl}
548 state := newDecodeStateFromData(bytesResult)
549 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
550 if string(data.a) != "hello" {
551 t.Errorf(`bytes a = %q not "hello"`, string(data.a))
560 instr := &decInstr{decString, 6, 0, 0, ovfl}
561 state := newDecodeStateFromData(bytesResult)
562 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
563 if data.a != "hello" {
564 t.Errorf(`bytes a = %q not "hello"`, data.a)
569 func TestEndToEnd(t *testing.T) {
577 M map[string]*float64
592 M: map[string]*float64{"pi": &pi, "e": &e},
593 N: &[3]float64{1.5, 2.5, 3.5},
594 Strs: &[2]string{s1, s2},
595 Int64s: &[]int64{77, 89, 123412342134},
597 S: "Now is the time",
598 Y: []byte("hello, sailor"),
599 T: &T2{"this is T2"},
601 b := new(bytes.Buffer)
602 err := NewEncoder(b).Encode(t1)
604 t.Error("encode:", err)
607 err = NewDecoder(b).Decode(&_t1)
609 t.Fatal("decode:", err)
611 if !reflect.DeepEqual(t1, &_t1) {
612 t.Errorf("encode expected %v got %v", *t1, _t1)
616 func TestOverflow(t *testing.T) {
628 b := new(bytes.Buffer)
635 Maxi: math.MaxInt8 + 1,
643 err = dec.Decode(&o1)
644 if err == nil || err.String() != `value for "Maxi" out of range` {
645 t.Error("wrong overflow error for int8:", err)
648 Mini: math.MinInt8 - 1,
652 err = dec.Decode(&o1)
653 if err == nil || err.String() != `value for "Mini" out of range` {
654 t.Error("wrong underflow error for int8:", err)
660 Maxi: math.MaxInt16 + 1,
668 err = dec.Decode(&o2)
669 if err == nil || err.String() != `value for "Maxi" out of range` {
670 t.Error("wrong overflow error for int16:", err)
673 Mini: math.MinInt16 - 1,
677 err = dec.Decode(&o2)
678 if err == nil || err.String() != `value for "Mini" out of range` {
679 t.Error("wrong underflow error for int16:", err)
685 Maxi: math.MaxInt32 + 1,
693 err = dec.Decode(&o3)
694 if err == nil || err.String() != `value for "Maxi" out of range` {
695 t.Error("wrong overflow error for int32:", err)
698 Mini: math.MinInt32 - 1,
702 err = dec.Decode(&o3)
703 if err == nil || err.String() != `value for "Mini" out of range` {
704 t.Error("wrong underflow error for int32:", err)
710 Maxu: math.MaxUint8 + 1,
717 err = dec.Decode(&o4)
718 if err == nil || err.String() != `value for "Maxu" out of range` {
719 t.Error("wrong overflow error for uint8:", err)
725 Maxu: math.MaxUint16 + 1,
732 err = dec.Decode(&o5)
733 if err == nil || err.String() != `value for "Maxu" out of range` {
734 t.Error("wrong overflow error for uint16:", err)
740 Maxu: math.MaxUint32 + 1,
747 err = dec.Decode(&o6)
748 if err == nil || err.String() != `value for "Maxu" out of range` {
749 t.Error("wrong overflow error for uint32:", err)
755 Maxf: math.MaxFloat32 * 2,
763 err = dec.Decode(&o7)
764 if err == nil || err.String() != `value for "Maxf" out of range` {
765 t.Error("wrong overflow error for float32:", err)
771 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
779 err = dec.Decode(&o8)
780 if err == nil || err.String() != `value for "Maxc" out of range` {
781 t.Error("wrong overflow error for complex64:", err)
786 func TestNesting(t *testing.T) {
795 b := new(bytes.Buffer)
796 NewEncoder(b).Encode(rt)
799 err := dec.Decode(&drt)
801 t.Fatal("decoder error:", err)
804 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
807 t.Errorf("nesting: recursion failed")
809 if drt.Next.A != rt.Next.A {
810 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
814 // These three structures have the same data with different indirections
834 func TestAutoIndirection(t *testing.T) {
835 // First transfer t1 into t0
847 b := new(bytes.Buffer)
853 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
854 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
857 // Now transfer t2 into t0
873 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
874 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
877 // Now transfer t0 into t1
878 t0 = T0{17, 177, 1777, 17777}
883 if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
884 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
887 // Now transfer t0 into t2
892 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
893 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
896 // Now do t2 again but without pre-allocated pointers.
904 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
905 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
921 func TestReorderedFields(t *testing.T) {
926 b := new(bytes.Buffer)
927 NewEncoder(b).Encode(rt0)
930 // Wire type is RT0, local type is RT1.
931 err := dec.Decode(&rt1)
933 t.Fatal("decode error:", err)
935 if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
936 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
940 // Like an RT0 but with fields we'll ignore on the decode side.
950 Ignore_m map[string]int
954 func TestIgnoredFields(t *testing.T) {
959 it0.Ignore_d = []int{1, 2, 3}
960 it0.Ignore_e[0] = 1.0
961 it0.Ignore_e[1] = 2.0
962 it0.Ignore_e[2] = 3.0
964 it0.Ignore_g = "pay no attention"
965 it0.Ignore_h = []byte("to the curtain")
966 it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
967 it0.Ignore_m = map[string]int{"one": 1, "two": 2}
969 b := new(bytes.Buffer)
970 NewEncoder(b).Encode(it0)
973 // Wire type is IT0, local type is RT1.
974 err := dec.Decode(&rt1)
976 t.Error("error: ", err)
978 if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
979 t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
984 func TestBadRecursiveType(t *testing.T) {
987 b := new(bytes.Buffer)
988 err := NewEncoder(b).Encode(&rec)
990 t.Error("expected error; got none")
991 } else if strings.Index(err.String(), "recursive") < 0 {
992 t.Error("expected recursive type error; got", err)
994 // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
1002 func TestInvalidField(t *testing.T) {
1004 bad0.CH = make(chan int)
1005 b := new(bytes.Buffer)
1006 dummyEncoder := new(Encoder) // sufficient for this purpose.
1007 dummyEncoder.encode(b, reflect.ValueOf(&bad0), userType(reflect.TypeOf(&bad0)))
1008 if err := dummyEncoder.err; err == nil {
1009 t.Error("expected error; got none")
1010 } else if strings.Index(err.String(), "type") < 0 {
1011 t.Error("expected type error; got", err)
1015 type Indirect struct {
1018 M ****map[string]int
1021 type Direct struct {
1027 func TestIndirectSliceMapArray(t *testing.T) {
1028 // Marshal indirect, unmarshal to direct.
1033 ***i.A = [3]int{1, 2, 3}
1037 ***i.S = []int{4, 5, 6}
1038 i.M = new(***map[string]int)
1039 *i.M = new(**map[string]int)
1040 **i.M = new(*map[string]int)
1041 ***i.M = new(map[string]int)
1042 ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1043 b := new(bytes.Buffer)
1044 NewEncoder(b).Encode(i)
1045 dec := NewDecoder(b)
1047 err := dec.Decode(&d)
1049 t.Error("error: ", err)
1051 if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1052 t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1054 if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1055 t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1057 if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1058 t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1060 // Marshal direct, unmarshal to indirect.
1061 d.A = [3]int{11, 22, 33}
1062 d.S = []int{44, 55, 66}
1063 d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1066 NewEncoder(b).Encode(d)
1068 err = dec.Decode(&i)
1070 t.Fatal("error: ", err)
1072 if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1073 t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1075 if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1076 t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1078 if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1079 t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1083 // An interface with several implementations
1084 type Squarer interface {
1090 func (i Int) Square() int {
1096 func (f Float) Square() int {
1102 func (v Vector) Square() int {
1104 for _, x := range v {
1114 func (p Point) Square() int {
1115 return p.X*p.X + p.Y*p.Y
1118 // A struct with interfaces in it.
1119 type InterfaceItem struct {
1121 Sq1, Sq2, Sq3 Squarer
1126 // The same struct without interfaces
1127 type NoInterfaceItem struct {
1132 func TestInterface(t *testing.T) {
1135 // Sending a Vector will require that the receiver define a type in the middle of
1136 // receiving the value for item2.
1137 vVal := Vector{1, 2, 3}
1138 b := new(bytes.Buffer)
1139 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1140 // Register the types.
1144 err := NewEncoder(b).Encode(item1)
1146 t.Error("expected no encode error; got", err)
1149 item2 := InterfaceItem{}
1150 err = NewDecoder(b).Decode(&item2)
1152 t.Fatal("decode:", err)
1154 if item2.I != item1.I {
1155 t.Error("normal int did not decode correctly")
1157 if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1158 t.Error("Int did not decode correctly")
1160 if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1161 t.Error("Float did not decode correctly")
1163 if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1164 t.Error("Vector did not decode correctly")
1166 if item2.F != item1.F {
1167 t.Error("normal float did not decode correctly")
1169 // Now check that we received a slice of Squarers correctly, including a nil element
1170 if len(item1.Sq) != len(item2.Sq) {
1171 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1173 for i, v1 := range item1.Sq {
1175 if v1 == nil || v2 == nil {
1176 if v1 != nil || v2 != nil {
1177 t.Errorf("item %d inconsistent nils", i)
1180 if v1.Square() != v2.Square() {
1181 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1187 // A struct with all basic types, stored in interfaces.
1188 type BasicInterfaceItem struct {
1189 Int, Int8, Int16, Int32, Int64 interface{}
1190 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1191 Float32, Float64 interface{}
1192 Complex64, Complex128 interface{}
1198 func TestInterfaceBasic(t *testing.T) {
1199 b := new(bytes.Buffer)
1200 item1 := &BasicInterfaceItem{
1201 int(1), int8(1), int16(1), int32(1), int64(1),
1202 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1204 complex64(1i), complex128(1i),
1209 err := NewEncoder(b).Encode(item1)
1211 t.Error("expected no encode error; got", err)
1214 item2 := &BasicInterfaceItem{}
1215 err = NewDecoder(b).Decode(&item2)
1217 t.Fatal("decode:", err)
1219 if !reflect.DeepEqual(item1, item2) {
1220 t.Errorf("encode expected %v got %v", item1, item2)
1222 // Hand check a couple for correct types.
1223 if v, ok := item2.Bool.(bool); !ok || !v {
1224 t.Error("boolean should be true")
1226 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1227 t.Errorf("string should be %v is %v", item1.String, v)
1233 type PtrInterfaceItem struct {
1234 Str1 interface{} // basic
1235 Str2 interface{} // derived
1238 // We'll send pointers; should receive values.
1239 // Also check that we can register T but send *T.
1240 func TestInterfacePointer(t *testing.T) {
1241 b := new(bytes.Buffer)
1243 str2 := String("kiddo")
1244 item1 := &PtrInterfaceItem{
1248 // Register the type.
1250 err := NewEncoder(b).Encode(item1)
1252 t.Error("expected no encode error; got", err)
1255 item2 := &PtrInterfaceItem{}
1256 err = NewDecoder(b).Decode(&item2)
1258 t.Fatal("decode:", err)
1260 // Hand test for correct types and values.
1261 if v, ok := item2.Str1.(string); !ok || v != str1 {
1262 t.Errorf("basic string failed: %q should be %q", v, str1)
1264 if v, ok := item2.Str2.(String); !ok || v != str2 {
1265 t.Errorf("derived type String failed: %q should be %q", v, str2)
1269 func TestIgnoreInterface(t *testing.T) {
1272 // Sending a Point will require that the receiver define a type in the middle of
1273 // receiving the value for item2.
1275 b := new(bytes.Buffer)
1276 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1277 // Register the types.
1281 err := NewEncoder(b).Encode(item1)
1283 t.Error("expected no encode error; got", err)
1286 item2 := NoInterfaceItem{}
1287 err = NewDecoder(b).Decode(&item2)
1289 t.Fatal("decode:", err)
1291 if item2.I != item1.I {
1292 t.Error("normal int did not decode correctly")
1294 if item2.F != item2.F {
1295 t.Error("normal float did not decode correctly")
1306 func TestUnexportedFields(t *testing.T) {
1312 b := new(bytes.Buffer)
1313 NewEncoder(b).Encode(u0)
1314 dec := NewDecoder(b)
1317 err := dec.Decode(&u1)
1319 t.Fatal("decode error:", err)
1321 if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1322 t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1325 t.Error("u1.c modified")
1329 var singletons = []interface{}{
1335 []float32{0.5, 0.25, 0.125},
1336 map[string]int{"one": 1, "two": 2},
1339 func TestDebugSingleton(t *testing.T) {
1340 if debugFunc == nil {
1343 b := new(bytes.Buffer)
1344 // Accumulate a number of values and print them out all at once.
1345 for _, x := range singletons {
1346 err := NewEncoder(b).Encode(x)
1348 t.Fatal("encode:", err)
1354 // A type that won't be defined in the gob until we send it in an interface value.
1355 type OnTheFly struct {
1372 func TestDebugStruct(t *testing.T) {
1373 if debugFunc == nil {
1376 Register(OnTheFly{})
1384 dt.M = map[string]int{"one": 1, "two": 2}
1385 dt.T = [3]int{11, 22, 33}
1386 dt.S = []string{"hi", "joe"}
1387 b := new(bytes.Buffer)
1388 err := NewEncoder(b).Encode(dt)
1390 t.Fatal("encode:", err)
1392 debugBuffer := bytes.NewBuffer(b.Bytes())
1394 err = NewDecoder(b).Decode(&dt2)
1396 t.Error("decode:", err)
1398 debugFunc(debugBuffer)