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.NewError("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
578 EmptyMap map[string]int // to check that we receive a non-nil map.
593 M: map[string]*float64{"pi": &pi, "e": &e},
594 EmptyMap: make(map[string]int),
595 N: &[3]float64{1.5, 2.5, 3.5},
596 Strs: &[2]string{s1, s2},
597 Int64s: &[]int64{77, 89, 123412342134},
599 S: "Now is the time",
600 Y: []byte("hello, sailor"),
601 T: &T2{"this is T2"},
603 b := new(bytes.Buffer)
604 err := NewEncoder(b).Encode(t1)
606 t.Error("encode:", err)
609 err = NewDecoder(b).Decode(&_t1)
611 t.Fatal("decode:", err)
613 if !reflect.DeepEqual(t1, &_t1) {
614 t.Errorf("encode expected %v got %v", *t1, _t1)
616 // Be absolutely sure the received map is non-nil.
617 if t1.EmptyMap == nil {
618 t.Errorf("nil map sent")
620 if _t1.EmptyMap == nil {
621 t.Errorf("nil map received")
625 func TestOverflow(t *testing.T) {
637 b := new(bytes.Buffer)
644 Maxi: math.MaxInt8 + 1,
652 err = dec.Decode(&o1)
653 if err == nil || err.String() != `value for "Maxi" out of range` {
654 t.Error("wrong overflow error for int8:", err)
657 Mini: math.MinInt8 - 1,
661 err = dec.Decode(&o1)
662 if err == nil || err.String() != `value for "Mini" out of range` {
663 t.Error("wrong underflow error for int8:", err)
669 Maxi: math.MaxInt16 + 1,
677 err = dec.Decode(&o2)
678 if err == nil || err.String() != `value for "Maxi" out of range` {
679 t.Error("wrong overflow error for int16:", err)
682 Mini: math.MinInt16 - 1,
686 err = dec.Decode(&o2)
687 if err == nil || err.String() != `value for "Mini" out of range` {
688 t.Error("wrong underflow error for int16:", err)
694 Maxi: math.MaxInt32 + 1,
702 err = dec.Decode(&o3)
703 if err == nil || err.String() != `value for "Maxi" out of range` {
704 t.Error("wrong overflow error for int32:", err)
707 Mini: math.MinInt32 - 1,
711 err = dec.Decode(&o3)
712 if err == nil || err.String() != `value for "Mini" out of range` {
713 t.Error("wrong underflow error for int32:", err)
719 Maxu: math.MaxUint8 + 1,
726 err = dec.Decode(&o4)
727 if err == nil || err.String() != `value for "Maxu" out of range` {
728 t.Error("wrong overflow error for uint8:", err)
734 Maxu: math.MaxUint16 + 1,
741 err = dec.Decode(&o5)
742 if err == nil || err.String() != `value for "Maxu" out of range` {
743 t.Error("wrong overflow error for uint16:", err)
749 Maxu: math.MaxUint32 + 1,
756 err = dec.Decode(&o6)
757 if err == nil || err.String() != `value for "Maxu" out of range` {
758 t.Error("wrong overflow error for uint32:", err)
764 Maxf: math.MaxFloat32 * 2,
772 err = dec.Decode(&o7)
773 if err == nil || err.String() != `value for "Maxf" out of range` {
774 t.Error("wrong overflow error for float32:", err)
780 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
788 err = dec.Decode(&o8)
789 if err == nil || err.String() != `value for "Maxc" out of range` {
790 t.Error("wrong overflow error for complex64:", err)
794 func TestNesting(t *testing.T) {
803 b := new(bytes.Buffer)
804 NewEncoder(b).Encode(rt)
807 err := dec.Decode(&drt)
809 t.Fatal("decoder error:", err)
812 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
815 t.Errorf("nesting: recursion failed")
817 if drt.Next.A != rt.Next.A {
818 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
822 // These three structures have the same data with different indirections
842 func TestAutoIndirection(t *testing.T) {
843 // First transfer t1 into t0
855 b := new(bytes.Buffer)
861 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
862 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
865 // Now transfer t2 into t0
881 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
882 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
885 // Now transfer t0 into t1
886 t0 = T0{17, 177, 1777, 17777}
891 if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
892 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
895 // Now transfer t0 into t2
900 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
901 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
904 // Now do t2 again but without pre-allocated pointers.
912 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
913 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
929 func TestReorderedFields(t *testing.T) {
934 b := new(bytes.Buffer)
935 NewEncoder(b).Encode(rt0)
938 // Wire type is RT0, local type is RT1.
939 err := dec.Decode(&rt1)
941 t.Fatal("decode error:", err)
943 if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
944 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
948 // Like an RT0 but with fields we'll ignore on the decode side.
958 Ignore_m map[string]int
962 func TestIgnoredFields(t *testing.T) {
967 it0.Ignore_d = []int{1, 2, 3}
968 it0.Ignore_e[0] = 1.0
969 it0.Ignore_e[1] = 2.0
970 it0.Ignore_e[2] = 3.0
972 it0.Ignore_g = "pay no attention"
973 it0.Ignore_h = []byte("to the curtain")
974 it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
975 it0.Ignore_m = map[string]int{"one": 1, "two": 2}
977 b := new(bytes.Buffer)
978 NewEncoder(b).Encode(it0)
981 // Wire type is IT0, local type is RT1.
982 err := dec.Decode(&rt1)
984 t.Error("error: ", err)
986 if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
987 t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
991 func TestBadRecursiveType(t *testing.T) {
994 b := new(bytes.Buffer)
995 err := NewEncoder(b).Encode(&rec)
997 t.Error("expected error; got none")
998 } else if strings.Index(err.String(), "recursive") < 0 {
999 t.Error("expected recursive type error; got", err)
1001 // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
1009 func TestInvalidField(t *testing.T) {
1011 bad0.CH = make(chan int)
1012 b := new(bytes.Buffer)
1013 dummyEncoder := new(Encoder) // sufficient for this purpose.
1014 dummyEncoder.encode(b, reflect.ValueOf(&bad0), userType(reflect.TypeOf(&bad0)))
1015 if err := dummyEncoder.err; err == nil {
1016 t.Error("expected error; got none")
1017 } else if strings.Index(err.String(), "type") < 0 {
1018 t.Error("expected type error; got", err)
1022 type Indirect struct {
1025 M ****map[string]int
1028 type Direct struct {
1034 func TestIndirectSliceMapArray(t *testing.T) {
1035 // Marshal indirect, unmarshal to direct.
1040 ***i.A = [3]int{1, 2, 3}
1044 ***i.S = []int{4, 5, 6}
1045 i.M = new(***map[string]int)
1046 *i.M = new(**map[string]int)
1047 **i.M = new(*map[string]int)
1048 ***i.M = new(map[string]int)
1049 ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1050 b := new(bytes.Buffer)
1051 NewEncoder(b).Encode(i)
1052 dec := NewDecoder(b)
1054 err := dec.Decode(&d)
1056 t.Error("error: ", err)
1058 if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1059 t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1061 if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1062 t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1064 if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1065 t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1067 // Marshal direct, unmarshal to indirect.
1068 d.A = [3]int{11, 22, 33}
1069 d.S = []int{44, 55, 66}
1070 d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1073 NewEncoder(b).Encode(d)
1075 err = dec.Decode(&i)
1077 t.Fatal("error: ", err)
1079 if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1080 t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1082 if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1083 t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1085 if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1086 t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1090 // An interface with several implementations
1091 type Squarer interface {
1097 func (i Int) Square() int {
1103 func (f Float) Square() int {
1109 func (v Vector) Square() int {
1111 for _, x := range v {
1121 func (p Point) Square() int {
1122 return p.X*p.X + p.Y*p.Y
1125 // A struct with interfaces in it.
1126 type InterfaceItem struct {
1128 Sq1, Sq2, Sq3 Squarer
1133 // The same struct without interfaces
1134 type NoInterfaceItem struct {
1139 func TestInterface(t *testing.T) {
1142 // Sending a Vector will require that the receiver define a type in the middle of
1143 // receiving the value for item2.
1144 vVal := Vector{1, 2, 3}
1145 b := new(bytes.Buffer)
1146 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1147 // Register the types.
1151 err := NewEncoder(b).Encode(item1)
1153 t.Error("expected no encode error; got", err)
1156 item2 := InterfaceItem{}
1157 err = NewDecoder(b).Decode(&item2)
1159 t.Fatal("decode:", err)
1161 if item2.I != item1.I {
1162 t.Error("normal int did not decode correctly")
1164 if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1165 t.Error("Int did not decode correctly")
1167 if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1168 t.Error("Float did not decode correctly")
1170 if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1171 t.Error("Vector did not decode correctly")
1173 if item2.F != item1.F {
1174 t.Error("normal float did not decode correctly")
1176 // Now check that we received a slice of Squarers correctly, including a nil element
1177 if len(item1.Sq) != len(item2.Sq) {
1178 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1180 for i, v1 := range item1.Sq {
1182 if v1 == nil || v2 == nil {
1183 if v1 != nil || v2 != nil {
1184 t.Errorf("item %d inconsistent nils", i)
1187 if v1.Square() != v2.Square() {
1188 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1194 // A struct with all basic types, stored in interfaces.
1195 type BasicInterfaceItem struct {
1196 Int, Int8, Int16, Int32, Int64 interface{}
1197 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1198 Float32, Float64 interface{}
1199 Complex64, Complex128 interface{}
1205 func TestInterfaceBasic(t *testing.T) {
1206 b := new(bytes.Buffer)
1207 item1 := &BasicInterfaceItem{
1208 int(1), int8(1), int16(1), int32(1), int64(1),
1209 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1211 complex64(1i), complex128(1i),
1216 err := NewEncoder(b).Encode(item1)
1218 t.Error("expected no encode error; got", err)
1221 item2 := &BasicInterfaceItem{}
1222 err = NewDecoder(b).Decode(&item2)
1224 t.Fatal("decode:", err)
1226 if !reflect.DeepEqual(item1, item2) {
1227 t.Errorf("encode expected %v got %v", item1, item2)
1229 // Hand check a couple for correct types.
1230 if v, ok := item2.Bool.(bool); !ok || !v {
1231 t.Error("boolean should be true")
1233 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1234 t.Errorf("string should be %v is %v", item1.String, v)
1240 type PtrInterfaceItem struct {
1241 Str1 interface{} // basic
1242 Str2 interface{} // derived
1245 // We'll send pointers; should receive values.
1246 // Also check that we can register T but send *T.
1247 func TestInterfacePointer(t *testing.T) {
1248 b := new(bytes.Buffer)
1250 str2 := String("kiddo")
1251 item1 := &PtrInterfaceItem{
1255 // Register the type.
1257 err := NewEncoder(b).Encode(item1)
1259 t.Error("expected no encode error; got", err)
1262 item2 := &PtrInterfaceItem{}
1263 err = NewDecoder(b).Decode(&item2)
1265 t.Fatal("decode:", err)
1267 // Hand test for correct types and values.
1268 if v, ok := item2.Str1.(string); !ok || v != str1 {
1269 t.Errorf("basic string failed: %q should be %q", v, str1)
1271 if v, ok := item2.Str2.(String); !ok || v != str2 {
1272 t.Errorf("derived type String failed: %q should be %q", v, str2)
1276 func TestIgnoreInterface(t *testing.T) {
1279 // Sending a Point will require that the receiver define a type in the middle of
1280 // receiving the value for item2.
1282 b := new(bytes.Buffer)
1283 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1284 // Register the types.
1288 err := NewEncoder(b).Encode(item1)
1290 t.Error("expected no encode error; got", err)
1293 item2 := NoInterfaceItem{}
1294 err = NewDecoder(b).Decode(&item2)
1296 t.Fatal("decode:", err)
1298 if item2.I != item1.I {
1299 t.Error("normal int did not decode correctly")
1301 if item2.F != item2.F {
1302 t.Error("normal float did not decode correctly")
1313 func TestUnexportedFields(t *testing.T) {
1319 b := new(bytes.Buffer)
1320 NewEncoder(b).Encode(u0)
1321 dec := NewDecoder(b)
1324 err := dec.Decode(&u1)
1326 t.Fatal("decode error:", err)
1328 if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1329 t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1332 t.Error("u1.c modified")
1336 var singletons = []interface{}{
1342 []float32{0.5, 0.25, 0.125},
1343 map[string]int{"one": 1, "two": 2},
1346 func TestDebugSingleton(t *testing.T) {
1347 if debugFunc == nil {
1350 b := new(bytes.Buffer)
1351 // Accumulate a number of values and print them out all at once.
1352 for _, x := range singletons {
1353 err := NewEncoder(b).Encode(x)
1355 t.Fatal("encode:", err)
1361 // A type that won't be defined in the gob until we send it in an interface value.
1362 type OnTheFly struct {
1379 func TestDebugStruct(t *testing.T) {
1380 if debugFunc == nil {
1383 Register(OnTheFly{})
1391 dt.M = map[string]int{"one": 1, "two": 2}
1392 dt.T = [3]int{11, 22, 33}
1393 dt.S = []string{"hi", "joe"}
1394 b := new(bytes.Buffer)
1395 err := NewEncoder(b).Encode(dt)
1397 t.Fatal("encode:", err)
1399 debugBuffer := bytes.NewBuffer(b.Bytes())
1401 err = NewDecoder(b).Decode(&dt2)
1403 t.Error("decode:", err)
1405 debugFunc(debugBuffer)