re PR lto/48086 (bootstrap-lto creates c-common.s with too many sections on x86_64...
[official-gcc.git] / libgo / go / gob / codec_test.go
blobaf941c629cd9f4da31fb4d659df6229124900c1c
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.
5 package gob
7 import (
8 "bytes"
9 "math"
10 "os"
11 "reflect"
12 "strings"
13 "testing"
14 "unsafe"
17 // Guarantee encoding format by comparing some encodings to hand-written values
18 type EncodeT struct {
19 x uint64
20 b []byte
23 var encodeT = []EncodeT{
24 {0x00, []byte{0x00}},
25 {0x0F, []byte{0x0F}},
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.
46 return
49 // Test basic encode/decode routines for unsigned integers
50 func TestUintCodec(t *testing.T) {
51 defer testError(t)
52 b := new(bytes.Buffer)
53 encState := newEncoderState(nil, b)
54 for _, tt := range encodeT {
55 b.Reset()
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(nil, &b)
62 for u := uint64(0); ; u = (u + 1) * 7 {
63 b.Reset()
64 encState.encodeUint(u)
65 v := decState.decodeUint()
66 if u != v {
67 t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
69 if u&(1<<63) != 0 {
70 break
75 func verifyInt(i int64, t *testing.T) {
76 defer testError(t)
77 var b = new(bytes.Buffer)
78 encState := newEncoderState(nil, b)
79 encState.encodeInt(i)
80 decState := newDecodeState(nil, &b)
81 decState.buf = make([]byte, 8)
82 j := decState.decodeInt()
83 if i != j {
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
92 i := int64(u)
93 verifyInt(i, t)
94 verifyInt(-i, t)
95 verifyInt(^i, t)
96 if u&(1<<63) != 0 {
97 break
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 {
115 b.Reset()
116 state := newEncoderState(nil, b)
117 state.fieldnum = -1
118 return state
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)
126 // bool
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())
137 // int
139 b.Reset()
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())
149 // uint
151 b.Reset()
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())
161 // int8
163 b.Reset()
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())
173 // uint8
175 b.Reset()
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())
185 // int16
187 b.Reset()
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())
197 // uint16
199 b.Reset()
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())
209 // int32
211 b.Reset()
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())
221 // uint32
223 b.Reset()
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())
233 // int64
235 b.Reset()
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())
245 // uint64
247 b.Reset()
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())
257 // float32
259 b.Reset()
260 data := struct{ a float32 }{17}
261 instr := &encInstr{encFloat32, 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("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
269 // float64
271 b.Reset()
272 data := struct{ a float64 }{17}
273 instr := &encInstr{encFloat64, 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("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
281 // bytes == []uint8
283 b.Reset()
284 data := struct{ a []byte }{[]byte("hello")}
285 instr := &encInstr{encUint8Array, 6, 0, 0}
286 state := newencoderState(b)
287 instr.op(instr, state, unsafe.Pointer(&data))
288 if !bytes.Equal(bytesResult, b.Bytes()) {
289 t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
293 // string
295 b.Reset()
296 data := struct{ a string }{"hello"}
297 instr := &encInstr{encString, 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("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
306 func execDec(typ string, instr *decInstr, state *decodeState, t *testing.T, p unsafe.Pointer) {
307 defer testError(t)
308 v := int(state.decodeUint())
309 if v+state.fieldnum != 6 {
310 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
312 instr.op(instr, state, decIndirect(p, instr.indir))
313 state.fieldnum = 6
316 func newDecodeStateFromData(data []byte) *decodeState {
317 b := bytes.NewBuffer(data)
318 state := newDecodeState(nil, &b)
319 state.fieldnum = -1
320 return state
323 // Test instruction execution for decoding.
324 // Do not run the machine yet; instead do individual instructions crafted by hand.
325 func TestScalarDecInstructions(t *testing.T) {
326 ovfl := os.ErrorString("overflow")
328 // bool
330 var data struct {
331 a bool
333 instr := &decInstr{decBool, 6, 0, 0, ovfl}
334 state := newDecodeStateFromData(boolResult)
335 execDec("bool", instr, state, t, unsafe.Pointer(&data))
336 if data.a != true {
337 t.Errorf("bool a = %v not true", data.a)
340 // int
342 var data struct {
343 a int
345 instr := &decInstr{decOpMap[reflect.Int], 6, 0, 0, ovfl}
346 state := newDecodeStateFromData(signedResult)
347 execDec("int", instr, state, t, unsafe.Pointer(&data))
348 if data.a != 17 {
349 t.Errorf("int a = %v not 17", data.a)
353 // uint
355 var data struct {
356 a uint
358 instr := &decInstr{decOpMap[reflect.Uint], 6, 0, 0, ovfl}
359 state := newDecodeStateFromData(unsignedResult)
360 execDec("uint", instr, state, t, unsafe.Pointer(&data))
361 if data.a != 17 {
362 t.Errorf("uint a = %v not 17", data.a)
366 // int8
368 var data struct {
369 a int8
371 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
372 state := newDecodeStateFromData(signedResult)
373 execDec("int8", instr, state, t, unsafe.Pointer(&data))
374 if data.a != 17 {
375 t.Errorf("int8 a = %v not 17", data.a)
379 // uint8
381 var data struct {
382 a uint8
384 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
385 state := newDecodeStateFromData(unsignedResult)
386 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
387 if data.a != 17 {
388 t.Errorf("uint8 a = %v not 17", data.a)
392 // int16
394 var data struct {
395 a int16
397 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
398 state := newDecodeStateFromData(signedResult)
399 execDec("int16", instr, state, t, unsafe.Pointer(&data))
400 if data.a != 17 {
401 t.Errorf("int16 a = %v not 17", data.a)
405 // uint16
407 var data struct {
408 a uint16
410 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
411 state := newDecodeStateFromData(unsignedResult)
412 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
413 if data.a != 17 {
414 t.Errorf("uint16 a = %v not 17", data.a)
418 // int32
420 var data struct {
421 a int32
423 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
424 state := newDecodeStateFromData(signedResult)
425 execDec("int32", instr, state, t, unsafe.Pointer(&data))
426 if data.a != 17 {
427 t.Errorf("int32 a = %v not 17", data.a)
431 // uint32
433 var data struct {
434 a uint32
436 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
437 state := newDecodeStateFromData(unsignedResult)
438 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
439 if data.a != 17 {
440 t.Errorf("uint32 a = %v not 17", data.a)
444 // uintptr
446 var data struct {
447 a uintptr
449 instr := &decInstr{decOpMap[reflect.Uintptr], 6, 0, 0, ovfl}
450 state := newDecodeStateFromData(unsignedResult)
451 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
452 if data.a != 17 {
453 t.Errorf("uintptr a = %v not 17", data.a)
457 // int64
459 var data struct {
460 a int64
462 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
463 state := newDecodeStateFromData(signedResult)
464 execDec("int64", instr, state, t, unsafe.Pointer(&data))
465 if data.a != 17 {
466 t.Errorf("int64 a = %v not 17", data.a)
470 // uint64
472 var data struct {
473 a uint64
475 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
476 state := newDecodeStateFromData(unsignedResult)
477 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
478 if data.a != 17 {
479 t.Errorf("uint64 a = %v not 17", data.a)
483 // float32
485 var data struct {
486 a float32
488 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
489 state := newDecodeStateFromData(floatResult)
490 execDec("float32", instr, state, t, unsafe.Pointer(&data))
491 if data.a != 17 {
492 t.Errorf("float32 a = %v not 17", data.a)
496 // float64
498 var data struct {
499 a float64
501 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
502 state := newDecodeStateFromData(floatResult)
503 execDec("float64", instr, state, t, unsafe.Pointer(&data))
504 if data.a != 17 {
505 t.Errorf("float64 a = %v not 17", data.a)
509 // complex64
511 var data struct {
512 a complex64
514 instr := &decInstr{decOpMap[reflect.Complex64], 6, 0, 0, ovfl}
515 state := newDecodeStateFromData(complexResult)
516 execDec("complex", instr, state, t, unsafe.Pointer(&data))
517 if data.a != 17+19i {
518 t.Errorf("complex a = %v not 17+19i", data.a)
522 // complex128
524 var data struct {
525 a complex128
527 instr := &decInstr{decOpMap[reflect.Complex128], 6, 0, 0, ovfl}
528 state := newDecodeStateFromData(complexResult)
529 execDec("complex", instr, state, t, unsafe.Pointer(&data))
530 if data.a != 17+19i {
531 t.Errorf("complex a = %v not 17+19i", data.a)
535 // bytes == []uint8
537 var data struct {
538 a []byte
540 instr := &decInstr{decUint8Array, 6, 0, 0, ovfl}
541 state := newDecodeStateFromData(bytesResult)
542 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
543 if string(data.a) != "hello" {
544 t.Errorf(`bytes a = %q not "hello"`, string(data.a))
548 // string
550 var data struct {
551 a string
553 instr := &decInstr{decString, 6, 0, 0, ovfl}
554 state := newDecodeStateFromData(bytesResult)
555 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
556 if data.a != "hello" {
557 t.Errorf(`bytes a = %q not "hello"`, data.a)
562 func TestEndToEnd(t *testing.T) {
563 type T2 struct {
564 T string
566 s1 := "string1"
567 s2 := "string2"
568 type T1 struct {
569 A, B, C int
570 M map[string]*float64
571 N *[3]float64
572 Strs *[2]string
573 Int64s *[]int64
574 RI complex64
575 S string
576 Y []byte
577 T *T2
579 pi := 3.14159
580 e := 2.71828
581 t1 := &T1{
582 A: 17,
583 B: 18,
584 C: -5,
585 M: map[string]*float64{"pi": &pi, "e": &e},
586 N: &[3]float64{1.5, 2.5, 3.5},
587 Strs: &[2]string{s1, s2},
588 Int64s: &[]int64{77, 89, 123412342134},
589 RI: 17 - 23i,
590 S: "Now is the time",
591 Y: []byte("hello, sailor"),
592 T: &T2{"this is T2"},
594 b := new(bytes.Buffer)
595 err := NewEncoder(b).Encode(t1)
596 if err != nil {
597 t.Error("encode:", err)
599 var _t1 T1
600 err = NewDecoder(b).Decode(&_t1)
601 if err != nil {
602 t.Fatal("decode:", err)
604 if !reflect.DeepEqual(t1, &_t1) {
605 t.Errorf("encode expected %v got %v", *t1, _t1)
609 func TestOverflow(t *testing.T) {
610 type inputT struct {
611 Maxi int64
612 Mini int64
613 Maxu uint64
614 Maxf float64
615 Minf float64
616 Maxc complex128
617 Minc complex128
619 var it inputT
620 var err os.Error
621 b := new(bytes.Buffer)
622 enc := NewEncoder(b)
623 dec := NewDecoder(b)
625 // int8
626 b.Reset()
627 it = inputT{
628 Maxi: math.MaxInt8 + 1,
630 type outi8 struct {
631 Maxi int8
632 Mini int8
634 var o1 outi8
635 enc.Encode(it)
636 err = dec.Decode(&o1)
637 if err == nil || err.String() != `value for "Maxi" out of range` {
638 t.Error("wrong overflow error for int8:", err)
640 it = inputT{
641 Mini: math.MinInt8 - 1,
643 b.Reset()
644 enc.Encode(it)
645 err = dec.Decode(&o1)
646 if err == nil || err.String() != `value for "Mini" out of range` {
647 t.Error("wrong underflow error for int8:", err)
650 // int16
651 b.Reset()
652 it = inputT{
653 Maxi: math.MaxInt16 + 1,
655 type outi16 struct {
656 Maxi int16
657 Mini int16
659 var o2 outi16
660 enc.Encode(it)
661 err = dec.Decode(&o2)
662 if err == nil || err.String() != `value for "Maxi" out of range` {
663 t.Error("wrong overflow error for int16:", err)
665 it = inputT{
666 Mini: math.MinInt16 - 1,
668 b.Reset()
669 enc.Encode(it)
670 err = dec.Decode(&o2)
671 if err == nil || err.String() != `value for "Mini" out of range` {
672 t.Error("wrong underflow error for int16:", err)
675 // int32
676 b.Reset()
677 it = inputT{
678 Maxi: math.MaxInt32 + 1,
680 type outi32 struct {
681 Maxi int32
682 Mini int32
684 var o3 outi32
685 enc.Encode(it)
686 err = dec.Decode(&o3)
687 if err == nil || err.String() != `value for "Maxi" out of range` {
688 t.Error("wrong overflow error for int32:", err)
690 it = inputT{
691 Mini: math.MinInt32 - 1,
693 b.Reset()
694 enc.Encode(it)
695 err = dec.Decode(&o3)
696 if err == nil || err.String() != `value for "Mini" out of range` {
697 t.Error("wrong underflow error for int32:", err)
700 // uint8
701 b.Reset()
702 it = inputT{
703 Maxu: math.MaxUint8 + 1,
705 type outu8 struct {
706 Maxu uint8
708 var o4 outu8
709 enc.Encode(it)
710 err = dec.Decode(&o4)
711 if err == nil || err.String() != `value for "Maxu" out of range` {
712 t.Error("wrong overflow error for uint8:", err)
715 // uint16
716 b.Reset()
717 it = inputT{
718 Maxu: math.MaxUint16 + 1,
720 type outu16 struct {
721 Maxu uint16
723 var o5 outu16
724 enc.Encode(it)
725 err = dec.Decode(&o5)
726 if err == nil || err.String() != `value for "Maxu" out of range` {
727 t.Error("wrong overflow error for uint16:", err)
730 // uint32
731 b.Reset()
732 it = inputT{
733 Maxu: math.MaxUint32 + 1,
735 type outu32 struct {
736 Maxu uint32
738 var o6 outu32
739 enc.Encode(it)
740 err = dec.Decode(&o6)
741 if err == nil || err.String() != `value for "Maxu" out of range` {
742 t.Error("wrong overflow error for uint32:", err)
745 // float32
746 b.Reset()
747 it = inputT{
748 Maxf: math.MaxFloat32 * 2,
750 type outf32 struct {
751 Maxf float32
752 Minf float32
754 var o7 outf32
755 enc.Encode(it)
756 err = dec.Decode(&o7)
757 if err == nil || err.String() != `value for "Maxf" out of range` {
758 t.Error("wrong overflow error for float32:", err)
761 // complex64
762 b.Reset()
763 it = inputT{
764 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
766 type outc64 struct {
767 Maxc complex64
768 Minc complex64
770 var o8 outc64
771 enc.Encode(it)
772 err = dec.Decode(&o8)
773 if err == nil || err.String() != `value for "Maxc" out of range` {
774 t.Error("wrong overflow error for complex64:", err)
779 func TestNesting(t *testing.T) {
780 type RT struct {
781 A string
782 Next *RT
784 rt := new(RT)
785 rt.A = "level1"
786 rt.Next = new(RT)
787 rt.Next.A = "level2"
788 b := new(bytes.Buffer)
789 NewEncoder(b).Encode(rt)
790 var drt RT
791 dec := NewDecoder(b)
792 err := dec.Decode(&drt)
793 if err != nil {
794 t.Fatal("decoder error:", err)
796 if drt.A != rt.A {
797 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
799 if drt.Next == nil {
800 t.Errorf("nesting: recursion failed")
802 if drt.Next.A != rt.Next.A {
803 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
807 // These three structures have the same data with different indirections
808 type T0 struct {
809 A int
810 B int
811 C int
812 D int
814 type T1 struct {
815 A int
816 B *int
817 C **int
818 D ***int
820 type T2 struct {
821 A ***int
822 B **int
823 C *int
824 D int
827 func TestAutoIndirection(t *testing.T) {
828 // First transfer t1 into t0
829 var t1 T1
830 t1.A = 17
831 t1.B = new(int)
832 *t1.B = 177
833 t1.C = new(*int)
834 *t1.C = new(int)
835 **t1.C = 1777
836 t1.D = new(**int)
837 *t1.D = new(*int)
838 **t1.D = new(int)
839 ***t1.D = 17777
840 b := new(bytes.Buffer)
841 enc := NewEncoder(b)
842 enc.Encode(t1)
843 dec := NewDecoder(b)
844 var t0 T0
845 dec.Decode(&t0)
846 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
847 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
850 // Now transfer t2 into t0
851 var t2 T2
852 t2.D = 17777
853 t2.C = new(int)
854 *t2.C = 1777
855 t2.B = new(*int)
856 *t2.B = new(int)
857 **t2.B = 177
858 t2.A = new(**int)
859 *t2.A = new(*int)
860 **t2.A = new(int)
861 ***t2.A = 17
862 b.Reset()
863 enc.Encode(t2)
864 t0 = T0{}
865 dec.Decode(&t0)
866 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
867 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
870 // Now transfer t0 into t1
871 t0 = T0{17, 177, 1777, 17777}
872 b.Reset()
873 enc.Encode(t0)
874 t1 = T1{}
875 dec.Decode(&t1)
876 if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
877 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
880 // Now transfer t0 into t2
881 b.Reset()
882 enc.Encode(t0)
883 t2 = T2{}
884 dec.Decode(&t2)
885 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
886 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
889 // Now do t2 again but without pre-allocated pointers.
890 b.Reset()
891 enc.Encode(t0)
892 ***t2.A = 0
893 **t2.B = 0
894 *t2.C = 0
895 t2.D = 0
896 dec.Decode(&t2)
897 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
898 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
902 type RT0 struct {
903 A int
904 B string
905 C float64
907 type RT1 struct {
908 C float64
909 B string
910 A int
911 NotSet string
914 func TestReorderedFields(t *testing.T) {
915 var rt0 RT0
916 rt0.A = 17
917 rt0.B = "hello"
918 rt0.C = 3.14159
919 b := new(bytes.Buffer)
920 NewEncoder(b).Encode(rt0)
921 dec := NewDecoder(b)
922 var rt1 RT1
923 // Wire type is RT0, local type is RT1.
924 err := dec.Decode(&rt1)
925 if err != nil {
926 t.Fatal("decode error:", err)
928 if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
929 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
933 // Like an RT0 but with fields we'll ignore on the decode side.
934 type IT0 struct {
935 A int64
936 B string
937 Ignore_d []int
938 Ignore_e [3]float64
939 Ignore_f bool
940 Ignore_g string
941 Ignore_h []byte
942 Ignore_i *RT1
943 Ignore_m map[string]int
944 C float64
947 func TestIgnoredFields(t *testing.T) {
948 var it0 IT0
949 it0.A = 17
950 it0.B = "hello"
951 it0.C = 3.14159
952 it0.Ignore_d = []int{1, 2, 3}
953 it0.Ignore_e[0] = 1.0
954 it0.Ignore_e[1] = 2.0
955 it0.Ignore_e[2] = 3.0
956 it0.Ignore_f = true
957 it0.Ignore_g = "pay no attention"
958 it0.Ignore_h = []byte("to the curtain")
959 it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
960 it0.Ignore_m = map[string]int{"one": 1, "two": 2}
962 b := new(bytes.Buffer)
963 NewEncoder(b).Encode(it0)
964 dec := NewDecoder(b)
965 var rt1 RT1
966 // Wire type is IT0, local type is RT1.
967 err := dec.Decode(&rt1)
968 if err != nil {
969 t.Error("error: ", err)
971 if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
972 t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
976 type Bad0 struct {
977 ch chan int
978 c float64
981 var nilEncoder *Encoder
983 func TestInvalidField(t *testing.T) {
984 var bad0 Bad0
985 bad0.ch = make(chan int)
986 b := new(bytes.Buffer)
987 err := nilEncoder.encode(b, reflect.NewValue(&bad0))
988 if err == nil {
989 t.Error("expected error; got none")
990 } else if strings.Index(err.String(), "type") < 0 {
991 t.Error("expected type error; got", err)
995 type Indirect struct {
996 A ***[3]int
997 S ***[]int
998 M ****map[string]int
1001 type Direct struct {
1002 A [3]int
1003 S []int
1004 M map[string]int
1007 func TestIndirectSliceMapArray(t *testing.T) {
1008 // Marshal indirect, unmarshal to direct.
1009 i := new(Indirect)
1010 i.A = new(**[3]int)
1011 *i.A = new(*[3]int)
1012 **i.A = new([3]int)
1013 ***i.A = [3]int{1, 2, 3}
1014 i.S = new(**[]int)
1015 *i.S = new(*[]int)
1016 **i.S = new([]int)
1017 ***i.S = []int{4, 5, 6}
1018 i.M = new(***map[string]int)
1019 *i.M = new(**map[string]int)
1020 **i.M = new(*map[string]int)
1021 ***i.M = new(map[string]int)
1022 ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1023 b := new(bytes.Buffer)
1024 NewEncoder(b).Encode(i)
1025 dec := NewDecoder(b)
1026 var d Direct
1027 err := dec.Decode(&d)
1028 if err != nil {
1029 t.Error("error: ", err)
1031 if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1032 t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1034 if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1035 t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1037 if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1038 t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1040 // Marshal direct, unmarshal to indirect.
1041 d.A = [3]int{11, 22, 33}
1042 d.S = []int{44, 55, 66}
1043 d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1044 i = new(Indirect)
1045 b.Reset()
1046 NewEncoder(b).Encode(d)
1047 dec = NewDecoder(b)
1048 err = dec.Decode(&i)
1049 if err != nil {
1050 t.Fatal("error: ", err)
1052 if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1053 t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1055 if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1056 t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1058 if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1059 t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1063 // An interface with several implementations
1064 type Squarer interface {
1065 Square() int
1068 type Int int
1070 func (i Int) Square() int {
1071 return int(i * i)
1074 type Float float64
1076 func (f Float) Square() int {
1077 return int(f * f)
1080 type Vector []int
1082 func (v Vector) Square() int {
1083 sum := 0
1084 for _, x := range v {
1085 sum += x * x
1087 return sum
1090 type Point struct {
1091 a, b int
1094 func (p Point) Square() int {
1095 return p.a*p.a + p.b*p.b
1098 // A struct with interfaces in it.
1099 type InterfaceItem struct {
1100 I int
1101 Sq1, Sq2, Sq3 Squarer
1102 F float64
1103 Sq []Squarer
1106 // The same struct without interfaces
1107 type NoInterfaceItem struct {
1108 I int
1109 F float64
1112 func TestInterface(t *testing.T) {
1113 iVal := Int(3)
1114 fVal := Float(5)
1115 // Sending a Vector will require that the receiver define a type in the middle of
1116 // receiving the value for item2.
1117 vVal := Vector{1, 2, 3}
1118 b := new(bytes.Buffer)
1119 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1120 // Register the types.
1121 Register(Int(0))
1122 Register(Float(0))
1123 Register(Vector{})
1124 err := NewEncoder(b).Encode(item1)
1125 if err != nil {
1126 t.Error("expected no encode error; got", err)
1129 item2 := InterfaceItem{}
1130 err = NewDecoder(b).Decode(&item2)
1131 if err != nil {
1132 t.Fatal("decode:", err)
1134 if item2.I != item1.I {
1135 t.Error("normal int did not decode correctly")
1137 if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1138 t.Error("Int did not decode correctly")
1140 if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1141 t.Error("Float did not decode correctly")
1143 if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1144 t.Error("Vector did not decode correctly")
1146 if item2.F != item1.F {
1147 t.Error("normal float did not decode correctly")
1149 // Now check that we received a slice of Squarers correctly, including a nil element
1150 if len(item1.Sq) != len(item2.Sq) {
1151 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1153 for i, v1 := range item1.Sq {
1154 v2 := item2.Sq[i]
1155 if v1 == nil || v2 == nil {
1156 if v1 != nil || v2 != nil {
1157 t.Errorf("item %d inconsistent nils", i)
1159 continue
1160 if v1.Square() != v2.Square() {
1161 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1168 // A struct with all basic types, stored in interfaces.
1169 type BasicInterfaceItem struct {
1170 Int, Int8, Int16, Int32, Int64 interface{}
1171 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1172 Float32, Float64 interface{}
1173 Complex64, Complex128 interface{}
1174 Bool interface{}
1175 String interface{}
1176 Bytes interface{}
1179 func TestInterfaceBasic(t *testing.T) {
1180 b := new(bytes.Buffer)
1181 item1 := &BasicInterfaceItem{
1182 int(1), int8(1), int16(1), int32(1), int64(1),
1183 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1184 float32(1), 1.0,
1185 complex64(0i), complex128(0i),
1186 true,
1187 "hello",
1188 []byte("sailor"),
1190 err := NewEncoder(b).Encode(item1)
1191 if err != nil {
1192 t.Error("expected no encode error; got", err)
1195 item2 := &BasicInterfaceItem{}
1196 err = NewDecoder(b).Decode(&item2)
1197 if err != nil {
1198 t.Fatal("decode:", err)
1200 if !reflect.DeepEqual(item1, item2) {
1201 t.Errorf("encode expected %v got %v", item1, item2)
1203 // Hand check a couple for correct types.
1204 if v, ok := item2.Bool.(bool); !ok || !v {
1205 t.Error("boolean should be true")
1207 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1208 t.Errorf("string should be %v is %v", item1.String, v)
1212 type String string
1214 type PtrInterfaceItem struct {
1215 Str1 interface{} // basic
1216 Str2 interface{} // derived
1219 // We'll send pointers; should receive values.
1220 // Also check that we can register T but send *T.
1221 func TestInterfacePointer(t *testing.T) {
1222 b := new(bytes.Buffer)
1223 str1 := "howdy"
1224 str2 := String("kiddo")
1225 item1 := &PtrInterfaceItem{
1226 &str1,
1227 &str2,
1229 // Register the type.
1230 Register(str2)
1231 err := NewEncoder(b).Encode(item1)
1232 if err != nil {
1233 t.Error("expected no encode error; got", err)
1236 item2 := &PtrInterfaceItem{}
1237 err = NewDecoder(b).Decode(&item2)
1238 if err != nil {
1239 t.Fatal("decode:", err)
1241 // Hand test for correct types and values.
1242 if v, ok := item2.Str1.(string); !ok || v != str1 {
1243 t.Errorf("basic string failed: %q should be %q", v, str1)
1245 if v, ok := item2.Str2.(String); !ok || v != str2 {
1246 t.Errorf("derived type String failed: %q should be %q", v, str2)
1250 func TestIgnoreInterface(t *testing.T) {
1251 iVal := Int(3)
1252 fVal := Float(5)
1253 // Sending a Point will require that the receiver define a type in the middle of
1254 // receiving the value for item2.
1255 pVal := Point{2, 3}
1256 b := new(bytes.Buffer)
1257 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1258 // Register the types.
1259 Register(Int(0))
1260 Register(Float(0))
1261 Register(Point{})
1262 err := NewEncoder(b).Encode(item1)
1263 if err != nil {
1264 t.Error("expected no encode error; got", err)
1267 item2 := NoInterfaceItem{}
1268 err = NewDecoder(b).Decode(&item2)
1269 if err != nil {
1270 t.Fatal("decode:", err)
1272 if item2.I != item1.I {
1273 t.Error("normal int did not decode correctly")
1275 if item2.F != item2.F {
1276 t.Error("normal float did not decode correctly")
1280 type U struct {
1281 A int
1282 B string
1283 c float64
1284 D uint
1287 func TestUnexportedFields(t *testing.T) {
1288 var u0 U
1289 u0.A = 17
1290 u0.B = "hello"
1291 u0.c = 3.14159
1292 u0.D = 23
1293 b := new(bytes.Buffer)
1294 NewEncoder(b).Encode(u0)
1295 dec := NewDecoder(b)
1296 var u1 U
1297 u1.c = 1234.
1298 err := dec.Decode(&u1)
1299 if err != nil {
1300 t.Fatal("decode error:", err)
1302 if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1303 t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1305 if u1.c != 1234. {
1306 t.Error("u1.c modified")
1310 // A type that won't be defined in the gob until we send it in an interface value.
1311 type OnTheFly struct {
1312 A int
1315 type DT struct {
1316 // X OnTheFly
1317 A int
1318 B string
1319 C float64
1320 I interface{}
1321 J interface{}
1322 I_nil interface{}
1323 M map[string]int
1324 T [3]int
1325 S []string
1328 func TestDebug(t *testing.T) {
1329 if debugFunc == nil {
1330 return
1332 Register(OnTheFly{})
1333 var dt DT
1334 dt.A = 17
1335 dt.B = "hello"
1336 dt.C = 3.14159
1337 dt.I = 271828
1338 dt.J = OnTheFly{3}
1339 dt.I_nil = nil
1340 dt.M = map[string]int{"one": 1, "two": 2}
1341 dt.T = [3]int{11, 22, 33}
1342 dt.S = []string{"hi", "joe"}
1343 b := new(bytes.Buffer)
1344 err := NewEncoder(b).Encode(dt)
1345 if err != nil {
1346 t.Fatal("encode:", err)
1348 debugBuffer := bytes.NewBuffer(b.Bytes())
1349 dt2 := &DT{}
1350 err = NewDecoder(b).Decode(&dt2)
1351 if err != nil {
1352 t.Error("decode:", err)
1354 debugFunc(debugBuffer)