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(nil, b)
54 for _, tt := range encodeT {
56 encodeUint(encState, 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(nil, &b)
62 for u := uint64(0); ; u = (u + 1) * 7 {
64 encodeUint(encState, u)
65 v := decodeUint(decState)
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(nil, b)
79 encodeInt(encState, i)
80 decState := newDecodeState(nil, &b)
81 decState.buf = make([]byte, 8)
82 j := decodeInt(decState)
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 newencoderState(b *bytes.Buffer) *encoderState {
116 state := newEncoderState(nil, b)
121 // Test instruction execution for encoding.
122 // Do not run the machine yet; instead do individual instructions crafted by hand.
123 func TestScalarEncInstructions(t *testing.T) {
124 var b = new(bytes.Buffer)
128 data := struct{ a bool }{true}
129 instr := &encInstr{encBool, 6, 0, 0}
130 state := newencoderState(b)
131 instr.op(instr, state, unsafe.Pointer(&data))
132 if !bytes.Equal(boolResult, b.Bytes()) {
133 t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
140 data := struct{ a int }{17}
141 instr := &encInstr{encInt, 6, 0, 0}
142 state := newencoderState(b)
143 instr.op(instr, state, unsafe.Pointer(&data))
144 if !bytes.Equal(signedResult, b.Bytes()) {
145 t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
152 data := struct{ a uint }{17}
153 instr := &encInstr{encUint, 6, 0, 0}
154 state := newencoderState(b)
155 instr.op(instr, state, unsafe.Pointer(&data))
156 if !bytes.Equal(unsignedResult, b.Bytes()) {
157 t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
164 data := struct{ a int8 }{17}
165 instr := &encInstr{encInt8, 6, 0, 0}
166 state := newencoderState(b)
167 instr.op(instr, state, unsafe.Pointer(&data))
168 if !bytes.Equal(signedResult, b.Bytes()) {
169 t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
176 data := struct{ a uint8 }{17}
177 instr := &encInstr{encUint8, 6, 0, 0}
178 state := newencoderState(b)
179 instr.op(instr, state, unsafe.Pointer(&data))
180 if !bytes.Equal(unsignedResult, b.Bytes()) {
181 t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
188 data := struct{ a int16 }{17}
189 instr := &encInstr{encInt16, 6, 0, 0}
190 state := newencoderState(b)
191 instr.op(instr, state, unsafe.Pointer(&data))
192 if !bytes.Equal(signedResult, b.Bytes()) {
193 t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
200 data := struct{ a uint16 }{17}
201 instr := &encInstr{encUint16, 6, 0, 0}
202 state := newencoderState(b)
203 instr.op(instr, state, unsafe.Pointer(&data))
204 if !bytes.Equal(unsignedResult, b.Bytes()) {
205 t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
212 data := struct{ a int32 }{17}
213 instr := &encInstr{encInt32, 6, 0, 0}
214 state := newencoderState(b)
215 instr.op(instr, state, unsafe.Pointer(&data))
216 if !bytes.Equal(signedResult, b.Bytes()) {
217 t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
224 data := struct{ a uint32 }{17}
225 instr := &encInstr{encUint32, 6, 0, 0}
226 state := newencoderState(b)
227 instr.op(instr, state, unsafe.Pointer(&data))
228 if !bytes.Equal(unsignedResult, b.Bytes()) {
229 t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
236 data := struct{ a int64 }{17}
237 instr := &encInstr{encInt64, 6, 0, 0}
238 state := newencoderState(b)
239 instr.op(instr, state, unsafe.Pointer(&data))
240 if !bytes.Equal(signedResult, b.Bytes()) {
241 t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
248 data := struct{ a uint64 }{17}
249 instr := &encInstr{encUint64, 6, 0, 0}
250 state := newencoderState(b)
251 instr.op(instr, state, unsafe.Pointer(&data))
252 if !bytes.Equal(unsignedResult, b.Bytes()) {
253 t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
260 data := struct{ a float }{17}
261 instr := &encInstr{encFloat, 6, 0, 0}
262 state := newencoderState(b)
263 instr.op(instr, state, unsafe.Pointer(&data))
264 if !bytes.Equal(floatResult, b.Bytes()) {
265 t.Errorf("float enc instructions: expected % x got % x", floatResult, b.Bytes())
272 data := struct{ a float32 }{17}
273 instr := &encInstr{encFloat32, 6, 0, 0}
274 state := newencoderState(b)
275 instr.op(instr, state, unsafe.Pointer(&data))
276 if !bytes.Equal(floatResult, b.Bytes()) {
277 t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
284 data := struct{ a float64 }{17}
285 instr := &encInstr{encFloat64, 6, 0, 0}
286 state := newencoderState(b)
287 instr.op(instr, state, unsafe.Pointer(&data))
288 if !bytes.Equal(floatResult, b.Bytes()) {
289 t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
296 data := struct{ a []byte }{[]byte("hello")}
297 instr := &encInstr{encUint8Array, 6, 0, 0}
298 state := newencoderState(b)
299 instr.op(instr, state, unsafe.Pointer(&data))
300 if !bytes.Equal(bytesResult, b.Bytes()) {
301 t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
308 data := struct{ a string }{"hello"}
309 instr := &encInstr{encString, 6, 0, 0}
310 state := newencoderState(b)
311 instr.op(instr, state, unsafe.Pointer(&data))
312 if !bytes.Equal(bytesResult, b.Bytes()) {
313 t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
318 func execDec(typ string, instr *decInstr, state *decodeState, t *testing.T, p unsafe.Pointer) {
320 v := int(decodeUint(state))
321 if v+state.fieldnum != 6 {
322 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
324 instr.op(instr, state, decIndirect(p, instr.indir))
328 func newDecodeStateFromData(data []byte) *decodeState {
329 b := bytes.NewBuffer(data)
330 state := newDecodeState(nil, &b)
335 // Test instruction execution for decoding.
336 // Do not run the machine yet; instead do individual instructions crafted by hand.
337 func TestScalarDecInstructions(t *testing.T) {
338 ovfl := os.ErrorString("overflow")
345 instr := &decInstr{decBool, 6, 0, 0, ovfl}
346 state := newDecodeStateFromData(boolResult)
347 execDec("bool", instr, state, t, unsafe.Pointer(&data))
349 t.Errorf("bool a = %v not true", data.a)
357 instr := &decInstr{decOpMap[reflect.Int], 6, 0, 0, ovfl}
358 state := newDecodeStateFromData(signedResult)
359 execDec("int", instr, state, t, unsafe.Pointer(&data))
361 t.Errorf("int a = %v not 17", data.a)
370 instr := &decInstr{decOpMap[reflect.Uint], 6, 0, 0, ovfl}
371 state := newDecodeStateFromData(unsignedResult)
372 execDec("uint", instr, state, t, unsafe.Pointer(&data))
374 t.Errorf("uint a = %v not 17", data.a)
383 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
384 state := newDecodeStateFromData(signedResult)
385 execDec("int8", instr, state, t, unsafe.Pointer(&data))
387 t.Errorf("int8 a = %v not 17", data.a)
396 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
397 state := newDecodeStateFromData(unsignedResult)
398 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
400 t.Errorf("uint8 a = %v not 17", data.a)
409 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
410 state := newDecodeStateFromData(signedResult)
411 execDec("int16", instr, state, t, unsafe.Pointer(&data))
413 t.Errorf("int16 a = %v not 17", data.a)
422 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
423 state := newDecodeStateFromData(unsignedResult)
424 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
426 t.Errorf("uint16 a = %v not 17", data.a)
435 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
436 state := newDecodeStateFromData(signedResult)
437 execDec("int32", instr, state, t, unsafe.Pointer(&data))
439 t.Errorf("int32 a = %v not 17", data.a)
448 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
449 state := newDecodeStateFromData(unsignedResult)
450 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
452 t.Errorf("uint32 a = %v not 17", data.a)
461 instr := &decInstr{decOpMap[reflect.Uintptr], 6, 0, 0, ovfl}
462 state := newDecodeStateFromData(unsignedResult)
463 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
465 t.Errorf("uintptr a = %v not 17", data.a)
474 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
475 state := newDecodeStateFromData(signedResult)
476 execDec("int64", instr, state, t, unsafe.Pointer(&data))
478 t.Errorf("int64 a = %v not 17", data.a)
487 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
488 state := newDecodeStateFromData(unsignedResult)
489 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
491 t.Errorf("uint64 a = %v not 17", data.a)
500 instr := &decInstr{decOpMap[reflect.Float], 6, 0, 0, ovfl}
501 state := newDecodeStateFromData(floatResult)
502 execDec("float", instr, state, t, unsafe.Pointer(&data))
504 t.Errorf("float a = %v not 17", data.a)
513 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
514 state := newDecodeStateFromData(floatResult)
515 execDec("float32", instr, state, t, unsafe.Pointer(&data))
517 t.Errorf("float32 a = %v not 17", data.a)
526 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
527 state := newDecodeStateFromData(floatResult)
528 execDec("float64", instr, state, t, unsafe.Pointer(&data))
530 t.Errorf("float64 a = %v not 17", data.a)
539 instr := &decInstr{decOpMap[reflect.Complex], 6, 0, 0, ovfl}
540 state := newDecodeStateFromData(complexResult)
541 execDec("complex", instr, state, t, unsafe.Pointer(&data))
542 if data.a != 17+19i {
543 t.Errorf("complex a = %v not 17+19i", data.a)
552 instr := &decInstr{decOpMap[reflect.Complex64], 6, 0, 0, ovfl}
553 state := newDecodeStateFromData(complexResult)
554 execDec("complex", instr, state, t, unsafe.Pointer(&data))
555 if data.a != 17+19i {
556 t.Errorf("complex a = %v not 17+19i", data.a)
565 instr := &decInstr{decOpMap[reflect.Complex128], 6, 0, 0, ovfl}
566 state := newDecodeStateFromData(complexResult)
567 execDec("complex", instr, state, t, unsafe.Pointer(&data))
568 if data.a != 17+19i {
569 t.Errorf("complex a = %v not 17+19i", data.a)
578 instr := &decInstr{decUint8Array, 6, 0, 0, ovfl}
579 state := newDecodeStateFromData(bytesResult)
580 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
581 if string(data.a) != "hello" {
582 t.Errorf(`bytes a = %q not "hello"`, string(data.a))
591 instr := &decInstr{decString, 6, 0, 0, ovfl}
592 state := newDecodeStateFromData(bytesResult)
593 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
594 if data.a != "hello" {
595 t.Errorf(`bytes a = %q not "hello"`, data.a)
600 func TestEndToEnd(t *testing.T) {
623 m: map[string]*float{"pi": &pi, "e": &e},
624 n: &[3]float{1.5, 2.5, 3.5},
625 strs: &[2]string{s1, s2},
626 int64s: &[]int64{77, 89, 123412342134},
628 s: "Now is the time",
629 y: []byte("hello, sailor"),
630 t: &T2{"this is T2"},
632 b := new(bytes.Buffer)
633 err := NewEncoder(b).Encode(t1)
635 t.Error("encode:", err)
638 err = NewDecoder(b).Decode(&_t1)
640 t.Fatal("decode:", err)
642 if !reflect.DeepEqual(t1, &_t1) {
643 t.Errorf("encode expected %v got %v", *t1, _t1)
647 func TestOverflow(t *testing.T) {
659 b := new(bytes.Buffer)
666 maxi: math.MaxInt8 + 1,
674 err = dec.Decode(&o1)
675 if err == nil || err.String() != `value for "maxi" out of range` {
676 t.Error("wrong overflow error for int8:", err)
679 mini: math.MinInt8 - 1,
683 err = dec.Decode(&o1)
684 if err == nil || err.String() != `value for "mini" out of range` {
685 t.Error("wrong underflow error for int8:", err)
691 maxi: math.MaxInt16 + 1,
699 err = dec.Decode(&o2)
700 if err == nil || err.String() != `value for "maxi" out of range` {
701 t.Error("wrong overflow error for int16:", err)
704 mini: math.MinInt16 - 1,
708 err = dec.Decode(&o2)
709 if err == nil || err.String() != `value for "mini" out of range` {
710 t.Error("wrong underflow error for int16:", err)
716 maxi: math.MaxInt32 + 1,
724 err = dec.Decode(&o3)
725 if err == nil || err.String() != `value for "maxi" out of range` {
726 t.Error("wrong overflow error for int32:", err)
729 mini: math.MinInt32 - 1,
733 err = dec.Decode(&o3)
734 if err == nil || err.String() != `value for "mini" out of range` {
735 t.Error("wrong underflow error for int32:", err)
741 maxu: math.MaxUint8 + 1,
748 err = dec.Decode(&o4)
749 if err == nil || err.String() != `value for "maxu" out of range` {
750 t.Error("wrong overflow error for uint8:", err)
756 maxu: math.MaxUint16 + 1,
763 err = dec.Decode(&o5)
764 if err == nil || err.String() != `value for "maxu" out of range` {
765 t.Error("wrong overflow error for uint16:", err)
771 maxu: math.MaxUint32 + 1,
778 err = dec.Decode(&o6)
779 if err == nil || err.String() != `value for "maxu" out of range` {
780 t.Error("wrong overflow error for uint32:", err)
786 maxf: math.MaxFloat32 * 2,
794 err = dec.Decode(&o7)
795 if err == nil || err.String() != `value for "maxf" out of range` {
796 t.Error("wrong overflow error for float32:", err)
802 maxc: cmplx(math.MaxFloat32*2, math.MaxFloat32*2),
810 err = dec.Decode(&o8)
811 if err == nil || err.String() != `value for "maxc" out of range` {
812 t.Error("wrong overflow error for complex64:", err)
817 func TestNesting(t *testing.T) {
826 b := new(bytes.Buffer)
827 NewEncoder(b).Encode(rt)
830 err := dec.Decode(&drt)
832 t.Errorf("decoder error:", err)
835 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
838 t.Errorf("nesting: recursion failed")
840 if drt.next.a != rt.next.a {
841 t.Errorf("nesting: encode expected %v got %v", *rt.next, *drt.next)
845 // These three structures have the same data with different indirections
865 func TestAutoIndirection(t *testing.T) {
866 // First transfer t1 into t0
878 b := new(bytes.Buffer)
884 if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 {
885 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
888 // Now transfer t2 into t0
904 if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 {
905 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
908 // Now transfer t0 into t1
909 t0 = T0{17, 177, 1777, 17777}
914 if t1.a != 17 || *t1.b != 177 || **t1.c != 1777 || ***t1.d != 17777 {
915 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.a, *t1.b, **t1.c, ***t1.d)
918 // Now transfer t0 into t2
923 if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 {
924 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d)
927 // Now do t2 again but without pre-allocated pointers.
935 if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 {
936 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d)
952 func TestReorderedFields(t *testing.T) {
957 b := new(bytes.Buffer)
958 NewEncoder(b).Encode(rt0)
961 // Wire type is RT0, local type is RT1.
962 err := dec.Decode(&rt1)
964 t.Error("decode error:", err)
966 if rt0.a != rt1.a || rt0.b != rt1.b || rt0.c != rt1.c {
967 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
971 // Like an RT0 but with fields we'll ignore on the decode side.
981 ignore_m map[string]int
985 func TestIgnoredFields(t *testing.T) {
990 it0.ignore_d = []int{1, 2, 3}
991 it0.ignore_e[0] = 1.0
992 it0.ignore_e[1] = 2.0
993 it0.ignore_e[2] = 3.0
995 it0.ignore_g = "pay no attention"
996 it0.ignore_h = []byte("to the curtain")
997 it0.ignore_i = &RT1{3.1, "hi", 7, "hello"}
998 it0.ignore_m = map[string]int{"one": 1, "two": 2}
1000 b := new(bytes.Buffer)
1001 NewEncoder(b).Encode(it0)
1002 dec := NewDecoder(b)
1004 // Wire type is IT0, local type is RT1.
1005 err := dec.Decode(&rt1)
1007 t.Error("error: ", err)
1009 if int(it0.a) != rt1.a || it0.b != rt1.b || it0.c != rt1.c {
1010 t.Errorf("rt1->rt0: expected %v; got %v", it0, rt1)
1019 var nilEncoder *Encoder
1021 func TestInvalidField(t *testing.T) {
1023 bad0.ch = make(chan int)
1024 b := new(bytes.Buffer)
1025 err := nilEncoder.encode(b, reflect.NewValue(&bad0))
1027 t.Error("expected error; got none")
1028 } else if strings.Index(err.String(), "type") < 0 {
1029 t.Error("expected type error; got", err)
1033 type Indirect struct {
1036 m ****map[string]int
1039 type Direct struct {
1045 func TestIndirectSliceMapArray(t *testing.T) {
1046 // Marshal indirect, unmarshal to direct.
1051 ***i.a = [3]int{1, 2, 3}
1055 ***i.s = []int{4, 5, 6}
1056 i.m = new(***map[string]int)
1057 *i.m = new(**map[string]int)
1058 **i.m = new(*map[string]int)
1059 ***i.m = new(map[string]int)
1060 ****i.m = map[string]int{"one": 1, "two": 2, "three": 3}
1061 b := new(bytes.Buffer)
1062 NewEncoder(b).Encode(i)
1063 dec := NewDecoder(b)
1065 err := dec.Decode(&d)
1067 t.Error("error: ", err)
1069 if len(d.a) != 3 || d.a[0] != 1 || d.a[1] != 2 || d.a[2] != 3 {
1070 t.Errorf("indirect to direct: d.a is %v not %v", d.a, ***i.a)
1072 if len(d.s) != 3 || d.s[0] != 4 || d.s[1] != 5 || d.s[2] != 6 {
1073 t.Errorf("indirect to direct: d.s is %v not %v", d.s, ***i.s)
1075 if len(d.m) != 3 || d.m["one"] != 1 || d.m["two"] != 2 || d.m["three"] != 3 {
1076 t.Errorf("indirect to direct: d.m is %v not %v", d.m, ***i.m)
1078 // Marshal direct, unmarshal to indirect.
1079 d.a = [3]int{11, 22, 33}
1080 d.s = []int{44, 55, 66}
1081 d.m = map[string]int{"four": 4, "five": 5, "six": 6}
1084 NewEncoder(b).Encode(d)
1086 err = dec.Decode(&i)
1088 t.Error("error: ", err)
1090 if len(***i.a) != 3 || (***i.a)[0] != 11 || (***i.a)[1] != 22 || (***i.a)[2] != 33 {
1091 t.Errorf("direct to indirect: ***i.a is %v not %v", ***i.a, d.a)
1093 if len(***i.s) != 3 || (***i.s)[0] != 44 || (***i.s)[1] != 55 || (***i.s)[2] != 66 {
1094 t.Errorf("direct to indirect: ***i.s is %v not %v", ***i.s, ***i.s)
1096 if len(****i.m) != 3 || (****i.m)["four"] != 4 || (****i.m)["five"] != 5 || (****i.m)["six"] != 6 {
1097 t.Errorf("direct to indirect: ****i.m is %v not %v", ****i.m, d.m)
1101 // An interface with several implementations
1102 type Squarer interface {
1108 func (i Int) Square() int {
1114 func (f Float) Square() int {
1120 func (v Vector) Square() int {
1122 for _, x := range v {
1132 func (p Point) Square() int {
1133 return p.a*p.a + p.b*p.b
1136 // A struct with interfaces in it.
1137 type InterfaceItem struct {
1139 sq1, sq2, sq3 Squarer
1144 // The same struct without interfaces
1145 type NoInterfaceItem struct {
1150 func TestInterface(t *testing.T) {
1153 // Sending a Vector will require that the receiver define a type in the middle of
1154 // receiving the value for item2.
1155 vVal := Vector{1, 2, 3}
1156 b := new(bytes.Buffer)
1157 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1158 // Register the types.
1162 err := NewEncoder(b).Encode(item1)
1164 t.Error("expected no encode error; got", err)
1167 item2 := InterfaceItem{}
1168 err = NewDecoder(b).Decode(&item2)
1170 t.Fatal("decode:", err)
1172 if item2.i != item1.i {
1173 t.Error("normal int did not decode correctly")
1175 if item2.sq1 == nil || item2.sq1.Square() != iVal.Square() {
1176 t.Error("Int did not decode correctly")
1178 if item2.sq2 == nil || item2.sq2.Square() != fVal.Square() {
1179 t.Error("Float did not decode correctly")
1181 if item2.sq3 == nil || item2.sq3.Square() != vVal.Square() {
1182 t.Error("Vector did not decode correctly")
1184 if item2.f != item1.f {
1185 t.Error("normal float did not decode correctly")
1187 // Now check that we received a slice of Squarers correctly, including a nil element
1188 if len(item1.sq) != len(item2.sq) {
1189 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.sq), len(item1.sq))
1191 for i, v1 := range item1.sq {
1193 if v1 == nil || v2 == nil {
1194 if v1 != nil || v2 != nil {
1195 t.Errorf("item %d inconsistent nils", i)
1198 if v1.Square() != v2.Square() {
1199 t.Errorf("item %d inconsistent values: %v %v", v1, v2)
1206 // A struct with all basic types, stored in interfaces.
1207 type BasicInterfaceItem struct {
1208 Int, Int8, Int16, Int32, Int64 interface{}
1209 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1210 Float, Float32, Float64 interface{}
1211 Complex, Complex64, Complex128 interface{}
1217 func TestInterfaceBasic(t *testing.T) {
1218 b := new(bytes.Buffer)
1219 item1 := &BasicInterfaceItem{
1220 int(1), int8(1), int16(1), int32(1), int64(1),
1221 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1222 float(1), float32(1), float64(1),
1223 complex(0i), complex64(0i), complex128(0i),
1228 err := NewEncoder(b).Encode(item1)
1230 t.Error("expected no encode error; got", err)
1233 item2 := &BasicInterfaceItem{}
1234 err = NewDecoder(b).Decode(&item2)
1236 t.Fatal("decode:", err)
1238 if !reflect.DeepEqual(item1, item2) {
1239 t.Errorf("encode expected %v got %v", item1, item2)
1241 // Hand check a couple for correct types.
1242 if v, ok := item2.Bool.(bool); !ok || !v {
1243 t.Error("boolean should be true")
1245 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1246 t.Errorf("string should be %v is %v", item1.String, v)
1252 type PtrInterfaceItem struct {
1253 str interface{} // basic
1254 Str interface{} // derived
1257 // We'll send pointers; should receive values.
1258 // Also check that we can register T but send *T.
1259 func TestInterfacePointer(t *testing.T) {
1260 b := new(bytes.Buffer)
1262 str2 := String("kiddo")
1263 item1 := &PtrInterfaceItem{
1267 // Register the type.
1269 err := NewEncoder(b).Encode(item1)
1271 t.Error("expected no encode error; got", err)
1274 item2 := &PtrInterfaceItem{}
1275 err = NewDecoder(b).Decode(&item2)
1277 t.Fatal("decode:", err)
1279 // Hand test for correct types and values.
1280 if v, ok := item2.str.(string); !ok || v != str1 {
1281 t.Errorf("basic string failed: %q should be %q", v, str1)
1283 if v, ok := item2.Str.(String); !ok || v != str2 {
1284 t.Errorf("derived type String failed: %q should be %q", v, str2)
1288 func TestIgnoreInterface(t *testing.T) {
1291 // Sending a Point will require that the receiver define a type in the middle of
1292 // receiving the value for item2.
1294 b := new(bytes.Buffer)
1295 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1296 // Register the types.
1300 err := NewEncoder(b).Encode(item1)
1302 t.Error("expected no encode error; got", err)
1305 item2 := NoInterfaceItem{}
1306 err = NewDecoder(b).Decode(&item2)
1308 t.Fatal("decode:", err)
1310 if item2.i != item1.i {
1311 t.Error("normal int did not decode correctly")
1313 if item2.f != item2.f {
1314 t.Error("normal float did not decode correctly")
1318 // A type that won't be defined in the gob until we send it in an interface value.
1319 type OnTheFly struct {
1336 func TestDebug(t *testing.T) {
1337 if debugFunc == nil {
1340 Register(OnTheFly{})
1348 dt.m = map[string]int{"one": 1, "two": 2}
1349 dt.r = [3]int{11, 22, 33}
1350 dt.s = []string{"hi", "joe"}
1351 b := new(bytes.Buffer)
1352 err := NewEncoder(b).Encode(dt)
1354 t.Fatal("encode:", err)
1356 debugBuffer := bytes.NewBuffer(b.Bytes())
1358 err = NewDecoder(b).Decode(&dt2)
1360 t.Error("decode:", err)
1362 debugFunc(debugBuffer)