libgo: Merge to master revision 19184.
[official-gcc.git] / libgo / go / encoding / gob / codec_test.go
blobfa57f3761d0d3b9d21a1f607cfcf774b0d64b4f9
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 "errors"
10 "flag"
11 "math"
12 "math/rand"
13 "reflect"
14 "strings"
15 "testing"
16 "time"
17 "unsafe"
20 var doFuzzTests = flag.Bool("gob.fuzz", false, "run the fuzz tests, which are large and very slow")
22 // Guarantee encoding format by comparing some encodings to hand-written values
23 type EncodeT struct {
24 x uint64
25 b []byte
28 var encodeT = []EncodeT{
29 {0x00, []byte{0x00}},
30 {0x0F, []byte{0x0F}},
31 {0xFF, []byte{0xFF, 0xFF}},
32 {0xFFFF, []byte{0xFE, 0xFF, 0xFF}},
33 {0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}},
34 {0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}},
35 {0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
36 {0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
37 {0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
38 {0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
39 {0x1111, []byte{0xFE, 0x11, 0x11}},
40 {0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
41 {0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}},
42 {1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
45 // testError is meant to be used as a deferred function to turn a panic(gobError) into a
46 // plain test.Error call.
47 func testError(t *testing.T) {
48 if e := recover(); e != nil {
49 t.Error(e.(gobError).err) // Will re-panic if not one of our errors, such as a runtime error.
51 return
54 // Test basic encode/decode routines for unsigned integers
55 func TestUintCodec(t *testing.T) {
56 defer testError(t)
57 b := new(bytes.Buffer)
58 encState := newEncoderState(b)
59 for _, tt := range encodeT {
60 b.Reset()
61 encState.encodeUint(tt.x)
62 if !bytes.Equal(tt.b, b.Bytes()) {
63 t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
66 decState := newDecodeState(b)
67 for u := uint64(0); ; u = (u + 1) * 7 {
68 b.Reset()
69 encState.encodeUint(u)
70 v := decState.decodeUint()
71 if u != v {
72 t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
74 if u&(1<<63) != 0 {
75 break
80 func verifyInt(i int64, t *testing.T) {
81 defer testError(t)
82 var b = new(bytes.Buffer)
83 encState := newEncoderState(b)
84 encState.encodeInt(i)
85 decState := newDecodeState(b)
86 decState.buf = make([]byte, 8)
87 j := decState.decodeInt()
88 if i != j {
89 t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
93 // Test basic encode/decode routines for signed integers
94 func TestIntCodec(t *testing.T) {
95 for u := uint64(0); ; u = (u + 1) * 7 {
96 // Do positive and negative values
97 i := int64(u)
98 verifyInt(i, t)
99 verifyInt(-i, t)
100 verifyInt(^i, t)
101 if u&(1<<63) != 0 {
102 break
105 verifyInt(-1<<63, t) // a tricky case
108 // The result of encoding a true boolean with field number 7
109 var boolResult = []byte{0x07, 0x01}
111 // The result of encoding a number 17 with field number 7
112 var signedResult = []byte{0x07, 2 * 17}
113 var unsignedResult = []byte{0x07, 17}
114 var floatResult = []byte{0x07, 0xFE, 0x31, 0x40}
116 // The result of encoding a number 17+19i with field number 7
117 var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
119 // The result of encoding "hello" with field number 7
120 var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
122 func newDecodeState(buf *bytes.Buffer) *decoderState {
123 d := new(decoderState)
124 d.b = buf
125 d.buf = make([]byte, uint64Size)
126 return d
129 func newEncoderState(b *bytes.Buffer) *encoderState {
130 b.Reset()
131 state := &encoderState{enc: nil, b: b}
132 state.fieldnum = -1
133 return state
136 // Test instruction execution for encoding.
137 // Do not run the machine yet; instead do individual instructions crafted by hand.
138 func TestScalarEncInstructions(t *testing.T) {
139 var b = new(bytes.Buffer)
141 // bool
143 data := struct{ a bool }{true}
144 instr := &encInstr{encBool, 6, 0, 0}
145 state := newEncoderState(b)
146 instr.op(instr, state, unsafe.Pointer(&data))
147 if !bytes.Equal(boolResult, b.Bytes()) {
148 t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
152 // int
154 b.Reset()
155 data := struct{ a int }{17}
156 instr := &encInstr{encInt, 6, 0, 0}
157 state := newEncoderState(b)
158 instr.op(instr, state, unsafe.Pointer(&data))
159 if !bytes.Equal(signedResult, b.Bytes()) {
160 t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
164 // uint
166 b.Reset()
167 data := struct{ a uint }{17}
168 instr := &encInstr{encUint, 6, 0, 0}
169 state := newEncoderState(b)
170 instr.op(instr, state, unsafe.Pointer(&data))
171 if !bytes.Equal(unsignedResult, b.Bytes()) {
172 t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
176 // int8
178 b.Reset()
179 data := struct{ a int8 }{17}
180 instr := &encInstr{encInt8, 6, 0, 0}
181 state := newEncoderState(b)
182 instr.op(instr, state, unsafe.Pointer(&data))
183 if !bytes.Equal(signedResult, b.Bytes()) {
184 t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
188 // uint8
190 b.Reset()
191 data := struct{ a uint8 }{17}
192 instr := &encInstr{encUint8, 6, 0, 0}
193 state := newEncoderState(b)
194 instr.op(instr, state, unsafe.Pointer(&data))
195 if !bytes.Equal(unsignedResult, b.Bytes()) {
196 t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
200 // int16
202 b.Reset()
203 data := struct{ a int16 }{17}
204 instr := &encInstr{encInt16, 6, 0, 0}
205 state := newEncoderState(b)
206 instr.op(instr, state, unsafe.Pointer(&data))
207 if !bytes.Equal(signedResult, b.Bytes()) {
208 t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
212 // uint16
214 b.Reset()
215 data := struct{ a uint16 }{17}
216 instr := &encInstr{encUint16, 6, 0, 0}
217 state := newEncoderState(b)
218 instr.op(instr, state, unsafe.Pointer(&data))
219 if !bytes.Equal(unsignedResult, b.Bytes()) {
220 t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
224 // int32
226 b.Reset()
227 data := struct{ a int32 }{17}
228 instr := &encInstr{encInt32, 6, 0, 0}
229 state := newEncoderState(b)
230 instr.op(instr, state, unsafe.Pointer(&data))
231 if !bytes.Equal(signedResult, b.Bytes()) {
232 t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
236 // uint32
238 b.Reset()
239 data := struct{ a uint32 }{17}
240 instr := &encInstr{encUint32, 6, 0, 0}
241 state := newEncoderState(b)
242 instr.op(instr, state, unsafe.Pointer(&data))
243 if !bytes.Equal(unsignedResult, b.Bytes()) {
244 t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
248 // int64
250 b.Reset()
251 data := struct{ a int64 }{17}
252 instr := &encInstr{encInt64, 6, 0, 0}
253 state := newEncoderState(b)
254 instr.op(instr, state, unsafe.Pointer(&data))
255 if !bytes.Equal(signedResult, b.Bytes()) {
256 t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
260 // uint64
262 b.Reset()
263 data := struct{ a uint64 }{17}
264 instr := &encInstr{encUint64, 6, 0, 0}
265 state := newEncoderState(b)
266 instr.op(instr, state, unsafe.Pointer(&data))
267 if !bytes.Equal(unsignedResult, b.Bytes()) {
268 t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
272 // float32
274 b.Reset()
275 data := struct{ a float32 }{17}
276 instr := &encInstr{encFloat32, 6, 0, 0}
277 state := newEncoderState(b)
278 instr.op(instr, state, unsafe.Pointer(&data))
279 if !bytes.Equal(floatResult, b.Bytes()) {
280 t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
284 // float64
286 b.Reset()
287 data := struct{ a float64 }{17}
288 instr := &encInstr{encFloat64, 6, 0, 0}
289 state := newEncoderState(b)
290 instr.op(instr, state, unsafe.Pointer(&data))
291 if !bytes.Equal(floatResult, b.Bytes()) {
292 t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
296 // bytes == []uint8
298 b.Reset()
299 data := struct{ a []byte }{[]byte("hello")}
300 instr := &encInstr{encUint8Array, 6, 0, 0}
301 state := newEncoderState(b)
302 instr.op(instr, state, unsafe.Pointer(&data))
303 if !bytes.Equal(bytesResult, b.Bytes()) {
304 t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
308 // string
310 b.Reset()
311 data := struct{ a string }{"hello"}
312 instr := &encInstr{encString, 6, 0, 0}
313 state := newEncoderState(b)
314 instr.op(instr, state, unsafe.Pointer(&data))
315 if !bytes.Equal(bytesResult, b.Bytes()) {
316 t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
321 func execDec(typ string, instr *decInstr, state *decoderState, t *testing.T, p unsafe.Pointer) {
322 defer testError(t)
323 v := int(state.decodeUint())
324 if v+state.fieldnum != 6 {
325 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
327 instr.op(instr, state, decIndirect(p, instr.indir))
328 state.fieldnum = 6
331 func newDecodeStateFromData(data []byte) *decoderState {
332 b := bytes.NewBuffer(data)
333 state := newDecodeState(b)
334 state.fieldnum = -1
335 return state
338 // Test instruction execution for decoding.
339 // Do not run the machine yet; instead do individual instructions crafted by hand.
340 func TestScalarDecInstructions(t *testing.T) {
341 ovfl := errors.New("overflow")
343 // bool
345 var data struct {
346 a bool
348 instr := &decInstr{decBool, 6, 0, 0, ovfl}
349 state := newDecodeStateFromData(boolResult)
350 execDec("bool", instr, state, t, unsafe.Pointer(&data))
351 if data.a != true {
352 t.Errorf("bool a = %v not true", data.a)
355 // int
357 var data struct {
358 a int
360 instr := &decInstr{decOpTable[reflect.Int], 6, 0, 0, ovfl}
361 state := newDecodeStateFromData(signedResult)
362 execDec("int", instr, state, t, unsafe.Pointer(&data))
363 if data.a != 17 {
364 t.Errorf("int a = %v not 17", data.a)
368 // uint
370 var data struct {
371 a uint
373 instr := &decInstr{decOpTable[reflect.Uint], 6, 0, 0, ovfl}
374 state := newDecodeStateFromData(unsignedResult)
375 execDec("uint", instr, state, t, unsafe.Pointer(&data))
376 if data.a != 17 {
377 t.Errorf("uint a = %v not 17", data.a)
381 // int8
383 var data struct {
384 a int8
386 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
387 state := newDecodeStateFromData(signedResult)
388 execDec("int8", instr, state, t, unsafe.Pointer(&data))
389 if data.a != 17 {
390 t.Errorf("int8 a = %v not 17", data.a)
394 // uint8
396 var data struct {
397 a uint8
399 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
400 state := newDecodeStateFromData(unsignedResult)
401 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
402 if data.a != 17 {
403 t.Errorf("uint8 a = %v not 17", data.a)
407 // int16
409 var data struct {
410 a int16
412 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
413 state := newDecodeStateFromData(signedResult)
414 execDec("int16", instr, state, t, unsafe.Pointer(&data))
415 if data.a != 17 {
416 t.Errorf("int16 a = %v not 17", data.a)
420 // uint16
422 var data struct {
423 a uint16
425 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
426 state := newDecodeStateFromData(unsignedResult)
427 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
428 if data.a != 17 {
429 t.Errorf("uint16 a = %v not 17", data.a)
433 // int32
435 var data struct {
436 a int32
438 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
439 state := newDecodeStateFromData(signedResult)
440 execDec("int32", instr, state, t, unsafe.Pointer(&data))
441 if data.a != 17 {
442 t.Errorf("int32 a = %v not 17", data.a)
446 // uint32
448 var data struct {
449 a uint32
451 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
452 state := newDecodeStateFromData(unsignedResult)
453 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
454 if data.a != 17 {
455 t.Errorf("uint32 a = %v not 17", data.a)
459 // uintptr
461 var data struct {
462 a uintptr
464 instr := &decInstr{decOpTable[reflect.Uintptr], 6, 0, 0, ovfl}
465 state := newDecodeStateFromData(unsignedResult)
466 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
467 if data.a != 17 {
468 t.Errorf("uintptr a = %v not 17", data.a)
472 // int64
474 var data struct {
475 a int64
477 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
478 state := newDecodeStateFromData(signedResult)
479 execDec("int64", instr, state, t, unsafe.Pointer(&data))
480 if data.a != 17 {
481 t.Errorf("int64 a = %v not 17", data.a)
485 // uint64
487 var data struct {
488 a uint64
490 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
491 state := newDecodeStateFromData(unsignedResult)
492 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
493 if data.a != 17 {
494 t.Errorf("uint64 a = %v not 17", data.a)
498 // float32
500 var data struct {
501 a float32
503 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
504 state := newDecodeStateFromData(floatResult)
505 execDec("float32", instr, state, t, unsafe.Pointer(&data))
506 if data.a != 17 {
507 t.Errorf("float32 a = %v not 17", data.a)
511 // float64
513 var data struct {
514 a float64
516 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
517 state := newDecodeStateFromData(floatResult)
518 execDec("float64", instr, state, t, unsafe.Pointer(&data))
519 if data.a != 17 {
520 t.Errorf("float64 a = %v not 17", data.a)
524 // complex64
526 var data struct {
527 a complex64
529 instr := &decInstr{decOpTable[reflect.Complex64], 6, 0, 0, ovfl}
530 state := newDecodeStateFromData(complexResult)
531 execDec("complex", instr, state, t, unsafe.Pointer(&data))
532 if data.a != 17+19i {
533 t.Errorf("complex a = %v not 17+19i", data.a)
537 // complex128
539 var data struct {
540 a complex128
542 instr := &decInstr{decOpTable[reflect.Complex128], 6, 0, 0, ovfl}
543 state := newDecodeStateFromData(complexResult)
544 execDec("complex", instr, state, t, unsafe.Pointer(&data))
545 if data.a != 17+19i {
546 t.Errorf("complex a = %v not 17+19i", data.a)
550 // bytes == []uint8
552 var data struct {
553 a []byte
555 instr := &decInstr{decUint8Slice, 6, 0, 0, ovfl}
556 state := newDecodeStateFromData(bytesResult)
557 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
558 if string(data.a) != "hello" {
559 t.Errorf(`bytes a = %q not "hello"`, string(data.a))
563 // string
565 var data struct {
566 a string
568 instr := &decInstr{decString, 6, 0, 0, ovfl}
569 state := newDecodeStateFromData(bytesResult)
570 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
571 if data.a != "hello" {
572 t.Errorf(`bytes a = %q not "hello"`, data.a)
577 func TestEndToEnd(t *testing.T) {
578 type T2 struct {
579 T string
581 s1 := "string1"
582 s2 := "string2"
583 type T1 struct {
584 A, B, C int
585 M map[string]*float64
586 EmptyMap map[string]int // to check that we receive a non-nil map.
587 N *[3]float64
588 Strs *[2]string
589 Int64s *[]int64
590 RI complex64
591 S string
592 Y []byte
593 T *T2
595 pi := 3.14159
596 e := 2.71828
597 t1 := &T1{
598 A: 17,
599 B: 18,
600 C: -5,
601 M: map[string]*float64{"pi": &pi, "e": &e},
602 EmptyMap: make(map[string]int),
603 N: &[3]float64{1.5, 2.5, 3.5},
604 Strs: &[2]string{s1, s2},
605 Int64s: &[]int64{77, 89, 123412342134},
606 RI: 17 - 23i,
607 S: "Now is the time",
608 Y: []byte("hello, sailor"),
609 T: &T2{"this is T2"},
611 b := new(bytes.Buffer)
612 err := NewEncoder(b).Encode(t1)
613 if err != nil {
614 t.Error("encode:", err)
616 var _t1 T1
617 err = NewDecoder(b).Decode(&_t1)
618 if err != nil {
619 t.Fatal("decode:", err)
621 if !reflect.DeepEqual(t1, &_t1) {
622 t.Errorf("encode expected %v got %v", *t1, _t1)
624 // Be absolutely sure the received map is non-nil.
625 if t1.EmptyMap == nil {
626 t.Errorf("nil map sent")
628 if _t1.EmptyMap == nil {
629 t.Errorf("nil map received")
633 func TestOverflow(t *testing.T) {
634 type inputT struct {
635 Maxi int64
636 Mini int64
637 Maxu uint64
638 Maxf float64
639 Minf float64
640 Maxc complex128
641 Minc complex128
643 var it inputT
644 var err error
645 b := new(bytes.Buffer)
646 enc := NewEncoder(b)
647 dec := NewDecoder(b)
649 // int8
650 b.Reset()
651 it = inputT{
652 Maxi: math.MaxInt8 + 1,
654 type outi8 struct {
655 Maxi int8
656 Mini int8
658 var o1 outi8
659 enc.Encode(it)
660 err = dec.Decode(&o1)
661 if err == nil || err.Error() != `value for "Maxi" out of range` {
662 t.Error("wrong overflow error for int8:", err)
664 it = inputT{
665 Mini: math.MinInt8 - 1,
667 b.Reset()
668 enc.Encode(it)
669 err = dec.Decode(&o1)
670 if err == nil || err.Error() != `value for "Mini" out of range` {
671 t.Error("wrong underflow error for int8:", err)
674 // int16
675 b.Reset()
676 it = inputT{
677 Maxi: math.MaxInt16 + 1,
679 type outi16 struct {
680 Maxi int16
681 Mini int16
683 var o2 outi16
684 enc.Encode(it)
685 err = dec.Decode(&o2)
686 if err == nil || err.Error() != `value for "Maxi" out of range` {
687 t.Error("wrong overflow error for int16:", err)
689 it = inputT{
690 Mini: math.MinInt16 - 1,
692 b.Reset()
693 enc.Encode(it)
694 err = dec.Decode(&o2)
695 if err == nil || err.Error() != `value for "Mini" out of range` {
696 t.Error("wrong underflow error for int16:", err)
699 // int32
700 b.Reset()
701 it = inputT{
702 Maxi: math.MaxInt32 + 1,
704 type outi32 struct {
705 Maxi int32
706 Mini int32
708 var o3 outi32
709 enc.Encode(it)
710 err = dec.Decode(&o3)
711 if err == nil || err.Error() != `value for "Maxi" out of range` {
712 t.Error("wrong overflow error for int32:", err)
714 it = inputT{
715 Mini: math.MinInt32 - 1,
717 b.Reset()
718 enc.Encode(it)
719 err = dec.Decode(&o3)
720 if err == nil || err.Error() != `value for "Mini" out of range` {
721 t.Error("wrong underflow error for int32:", err)
724 // uint8
725 b.Reset()
726 it = inputT{
727 Maxu: math.MaxUint8 + 1,
729 type outu8 struct {
730 Maxu uint8
732 var o4 outu8
733 enc.Encode(it)
734 err = dec.Decode(&o4)
735 if err == nil || err.Error() != `value for "Maxu" out of range` {
736 t.Error("wrong overflow error for uint8:", err)
739 // uint16
740 b.Reset()
741 it = inputT{
742 Maxu: math.MaxUint16 + 1,
744 type outu16 struct {
745 Maxu uint16
747 var o5 outu16
748 enc.Encode(it)
749 err = dec.Decode(&o5)
750 if err == nil || err.Error() != `value for "Maxu" out of range` {
751 t.Error("wrong overflow error for uint16:", err)
754 // uint32
755 b.Reset()
756 it = inputT{
757 Maxu: math.MaxUint32 + 1,
759 type outu32 struct {
760 Maxu uint32
762 var o6 outu32
763 enc.Encode(it)
764 err = dec.Decode(&o6)
765 if err == nil || err.Error() != `value for "Maxu" out of range` {
766 t.Error("wrong overflow error for uint32:", err)
769 // float32
770 b.Reset()
771 it = inputT{
772 Maxf: math.MaxFloat32 * 2,
774 type outf32 struct {
775 Maxf float32
776 Minf float32
778 var o7 outf32
779 enc.Encode(it)
780 err = dec.Decode(&o7)
781 if err == nil || err.Error() != `value for "Maxf" out of range` {
782 t.Error("wrong overflow error for float32:", err)
785 // complex64
786 b.Reset()
787 it = inputT{
788 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
790 type outc64 struct {
791 Maxc complex64
792 Minc complex64
794 var o8 outc64
795 enc.Encode(it)
796 err = dec.Decode(&o8)
797 if err == nil || err.Error() != `value for "Maxc" out of range` {
798 t.Error("wrong overflow error for complex64:", err)
802 func TestNesting(t *testing.T) {
803 type RT struct {
804 A string
805 Next *RT
807 rt := new(RT)
808 rt.A = "level1"
809 rt.Next = new(RT)
810 rt.Next.A = "level2"
811 b := new(bytes.Buffer)
812 NewEncoder(b).Encode(rt)
813 var drt RT
814 dec := NewDecoder(b)
815 err := dec.Decode(&drt)
816 if err != nil {
817 t.Fatal("decoder error:", err)
819 if drt.A != rt.A {
820 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
822 if drt.Next == nil {
823 t.Errorf("nesting: recursion failed")
825 if drt.Next.A != rt.Next.A {
826 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
830 // These three structures have the same data with different indirections
831 type T0 struct {
832 A int
833 B int
834 C int
835 D int
837 type T1 struct {
838 A int
839 B *int
840 C **int
841 D ***int
843 type T2 struct {
844 A ***int
845 B **int
846 C *int
847 D int
850 func TestAutoIndirection(t *testing.T) {
851 // First transfer t1 into t0
852 var t1 T1
853 t1.A = 17
854 t1.B = new(int)
855 *t1.B = 177
856 t1.C = new(*int)
857 *t1.C = new(int)
858 **t1.C = 1777
859 t1.D = new(**int)
860 *t1.D = new(*int)
861 **t1.D = new(int)
862 ***t1.D = 17777
863 b := new(bytes.Buffer)
864 enc := NewEncoder(b)
865 enc.Encode(t1)
866 dec := NewDecoder(b)
867 var t0 T0
868 dec.Decode(&t0)
869 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
870 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
873 // Now transfer t2 into t0
874 var t2 T2
875 t2.D = 17777
876 t2.C = new(int)
877 *t2.C = 1777
878 t2.B = new(*int)
879 *t2.B = new(int)
880 **t2.B = 177
881 t2.A = new(**int)
882 *t2.A = new(*int)
883 **t2.A = new(int)
884 ***t2.A = 17
885 b.Reset()
886 enc.Encode(t2)
887 t0 = T0{}
888 dec.Decode(&t0)
889 if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
890 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
893 // Now transfer t0 into t1
894 t0 = T0{17, 177, 1777, 17777}
895 b.Reset()
896 enc.Encode(t0)
897 t1 = T1{}
898 dec.Decode(&t1)
899 if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
900 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
903 // Now transfer t0 into t2
904 b.Reset()
905 enc.Encode(t0)
906 t2 = T2{}
907 dec.Decode(&t2)
908 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
909 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
912 // Now do t2 again but without pre-allocated pointers.
913 b.Reset()
914 enc.Encode(t0)
915 ***t2.A = 0
916 **t2.B = 0
917 *t2.C = 0
918 t2.D = 0
919 dec.Decode(&t2)
920 if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
921 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
925 type RT0 struct {
926 A int
927 B string
928 C float64
930 type RT1 struct {
931 C float64
932 B string
933 A int
934 NotSet string
937 func TestReorderedFields(t *testing.T) {
938 var rt0 RT0
939 rt0.A = 17
940 rt0.B = "hello"
941 rt0.C = 3.14159
942 b := new(bytes.Buffer)
943 NewEncoder(b).Encode(rt0)
944 dec := NewDecoder(b)
945 var rt1 RT1
946 // Wire type is RT0, local type is RT1.
947 err := dec.Decode(&rt1)
948 if err != nil {
949 t.Fatal("decode error:", err)
951 if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
952 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
956 // Like an RT0 but with fields we'll ignore on the decode side.
957 type IT0 struct {
958 A int64
959 B string
960 Ignore_d []int
961 Ignore_e [3]float64
962 Ignore_f bool
963 Ignore_g string
964 Ignore_h []byte
965 Ignore_i *RT1
966 Ignore_m map[string]int
967 C float64
970 func TestIgnoredFields(t *testing.T) {
971 var it0 IT0
972 it0.A = 17
973 it0.B = "hello"
974 it0.C = 3.14159
975 it0.Ignore_d = []int{1, 2, 3}
976 it0.Ignore_e[0] = 1.0
977 it0.Ignore_e[1] = 2.0
978 it0.Ignore_e[2] = 3.0
979 it0.Ignore_f = true
980 it0.Ignore_g = "pay no attention"
981 it0.Ignore_h = []byte("to the curtain")
982 it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
983 it0.Ignore_m = map[string]int{"one": 1, "two": 2}
985 b := new(bytes.Buffer)
986 NewEncoder(b).Encode(it0)
987 dec := NewDecoder(b)
988 var rt1 RT1
989 // Wire type is IT0, local type is RT1.
990 err := dec.Decode(&rt1)
991 if err != nil {
992 t.Error("error: ", err)
994 if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
995 t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
999 func TestBadRecursiveType(t *testing.T) {
1000 type Rec ***Rec
1001 var rec Rec
1002 b := new(bytes.Buffer)
1003 err := NewEncoder(b).Encode(&rec)
1004 if err == nil {
1005 t.Error("expected error; got none")
1006 } else if strings.Index(err.Error(), "recursive") < 0 {
1007 t.Error("expected recursive type error; got", err)
1009 // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
1012 type Indirect struct {
1013 A ***[3]int
1014 S ***[]int
1015 M ****map[string]int
1018 type Direct struct {
1019 A [3]int
1020 S []int
1021 M map[string]int
1024 func TestIndirectSliceMapArray(t *testing.T) {
1025 // Marshal indirect, unmarshal to direct.
1026 i := new(Indirect)
1027 i.A = new(**[3]int)
1028 *i.A = new(*[3]int)
1029 **i.A = new([3]int)
1030 ***i.A = [3]int{1, 2, 3}
1031 i.S = new(**[]int)
1032 *i.S = new(*[]int)
1033 **i.S = new([]int)
1034 ***i.S = []int{4, 5, 6}
1035 i.M = new(***map[string]int)
1036 *i.M = new(**map[string]int)
1037 **i.M = new(*map[string]int)
1038 ***i.M = new(map[string]int)
1039 ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1040 b := new(bytes.Buffer)
1041 NewEncoder(b).Encode(i)
1042 dec := NewDecoder(b)
1043 var d Direct
1044 err := dec.Decode(&d)
1045 if err != nil {
1046 t.Error("error: ", err)
1048 if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1049 t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1051 if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1052 t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1054 if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1055 t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1057 // Marshal direct, unmarshal to indirect.
1058 d.A = [3]int{11, 22, 33}
1059 d.S = []int{44, 55, 66}
1060 d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1061 i = new(Indirect)
1062 b.Reset()
1063 NewEncoder(b).Encode(d)
1064 dec = NewDecoder(b)
1065 err = dec.Decode(&i)
1066 if err != nil {
1067 t.Fatal("error: ", err)
1069 if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1070 t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1072 if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1073 t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1075 if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1076 t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1080 // An interface with several implementations
1081 type Squarer interface {
1082 Square() int
1085 type Int int
1087 func (i Int) Square() int {
1088 return int(i * i)
1091 type Float float64
1093 func (f Float) Square() int {
1094 return int(f * f)
1097 type Vector []int
1099 func (v Vector) Square() int {
1100 sum := 0
1101 for _, x := range v {
1102 sum += x * x
1104 return sum
1107 type Point struct {
1108 X, Y int
1111 func (p Point) Square() int {
1112 return p.X*p.X + p.Y*p.Y
1115 // A struct with interfaces in it.
1116 type InterfaceItem struct {
1117 I int
1118 Sq1, Sq2, Sq3 Squarer
1119 F float64
1120 Sq []Squarer
1123 // The same struct without interfaces
1124 type NoInterfaceItem struct {
1125 I int
1126 F float64
1129 func TestInterface(t *testing.T) {
1130 iVal := Int(3)
1131 fVal := Float(5)
1132 // Sending a Vector will require that the receiver define a type in the middle of
1133 // receiving the value for item2.
1134 vVal := Vector{1, 2, 3}
1135 b := new(bytes.Buffer)
1136 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1137 // Register the types.
1138 Register(Int(0))
1139 Register(Float(0))
1140 Register(Vector{})
1141 err := NewEncoder(b).Encode(item1)
1142 if err != nil {
1143 t.Error("expected no encode error; got", err)
1146 item2 := InterfaceItem{}
1147 err = NewDecoder(b).Decode(&item2)
1148 if err != nil {
1149 t.Fatal("decode:", err)
1151 if item2.I != item1.I {
1152 t.Error("normal int did not decode correctly")
1154 if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1155 t.Error("Int did not decode correctly")
1157 if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1158 t.Error("Float did not decode correctly")
1160 if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1161 t.Error("Vector did not decode correctly")
1163 if item2.F != item1.F {
1164 t.Error("normal float did not decode correctly")
1166 // Now check that we received a slice of Squarers correctly, including a nil element
1167 if len(item1.Sq) != len(item2.Sq) {
1168 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1170 for i, v1 := range item1.Sq {
1171 v2 := item2.Sq[i]
1172 if v1 == nil || v2 == nil {
1173 if v1 != nil || v2 != nil {
1174 t.Errorf("item %d inconsistent nils", i)
1176 } else if v1.Square() != v2.Square() {
1177 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1182 // A struct with all basic types, stored in interfaces.
1183 type BasicInterfaceItem struct {
1184 Int, Int8, Int16, Int32, Int64 interface{}
1185 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1186 Float32, Float64 interface{}
1187 Complex64, Complex128 interface{}
1188 Bool interface{}
1189 String interface{}
1190 Bytes interface{}
1193 func TestInterfaceBasic(t *testing.T) {
1194 b := new(bytes.Buffer)
1195 item1 := &BasicInterfaceItem{
1196 int(1), int8(1), int16(1), int32(1), int64(1),
1197 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1198 float32(1), 1.0,
1199 complex64(1i), complex128(1i),
1200 true,
1201 "hello",
1202 []byte("sailor"),
1204 err := NewEncoder(b).Encode(item1)
1205 if err != nil {
1206 t.Error("expected no encode error; got", err)
1209 item2 := &BasicInterfaceItem{}
1210 err = NewDecoder(b).Decode(&item2)
1211 if err != nil {
1212 t.Fatal("decode:", err)
1214 if !reflect.DeepEqual(item1, item2) {
1215 t.Errorf("encode expected %v got %v", item1, item2)
1217 // Hand check a couple for correct types.
1218 if v, ok := item2.Bool.(bool); !ok || !v {
1219 t.Error("boolean should be true")
1221 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1222 t.Errorf("string should be %v is %v", item1.String, v)
1226 type String string
1228 type PtrInterfaceItem struct {
1229 Str1 interface{} // basic
1230 Str2 interface{} // derived
1233 // We'll send pointers; should receive values.
1234 // Also check that we can register T but send *T.
1235 func TestInterfacePointer(t *testing.T) {
1236 b := new(bytes.Buffer)
1237 str1 := "howdy"
1238 str2 := String("kiddo")
1239 item1 := &PtrInterfaceItem{
1240 &str1,
1241 &str2,
1243 // Register the type.
1244 Register(str2)
1245 err := NewEncoder(b).Encode(item1)
1246 if err != nil {
1247 t.Error("expected no encode error; got", err)
1250 item2 := &PtrInterfaceItem{}
1251 err = NewDecoder(b).Decode(&item2)
1252 if err != nil {
1253 t.Fatal("decode:", err)
1255 // Hand test for correct types and values.
1256 if v, ok := item2.Str1.(string); !ok || v != str1 {
1257 t.Errorf("basic string failed: %q should be %q", v, str1)
1259 if v, ok := item2.Str2.(String); !ok || v != str2 {
1260 t.Errorf("derived type String failed: %q should be %q", v, str2)
1264 func TestIgnoreInterface(t *testing.T) {
1265 iVal := Int(3)
1266 fVal := Float(5)
1267 // Sending a Point will require that the receiver define a type in the middle of
1268 // receiving the value for item2.
1269 pVal := Point{2, 3}
1270 b := new(bytes.Buffer)
1271 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1272 // Register the types.
1273 Register(Int(0))
1274 Register(Float(0))
1275 Register(Point{})
1276 err := NewEncoder(b).Encode(item1)
1277 if err != nil {
1278 t.Error("expected no encode error; got", err)
1281 item2 := NoInterfaceItem{}
1282 err = NewDecoder(b).Decode(&item2)
1283 if err != nil {
1284 t.Fatal("decode:", err)
1286 if item2.I != item1.I {
1287 t.Error("normal int did not decode correctly")
1289 if item2.F != item2.F {
1290 t.Error("normal float did not decode correctly")
1294 type U struct {
1295 A int
1296 B string
1297 c float64
1298 D uint
1301 func TestUnexportedFields(t *testing.T) {
1302 var u0 U
1303 u0.A = 17
1304 u0.B = "hello"
1305 u0.c = 3.14159
1306 u0.D = 23
1307 b := new(bytes.Buffer)
1308 NewEncoder(b).Encode(u0)
1309 dec := NewDecoder(b)
1310 var u1 U
1311 u1.c = 1234.
1312 err := dec.Decode(&u1)
1313 if err != nil {
1314 t.Fatal("decode error:", err)
1316 if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1317 t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1319 if u1.c != 1234. {
1320 t.Error("u1.c modified")
1324 var singletons = []interface{}{
1325 true,
1327 3.2,
1328 "hello",
1329 [3]int{11, 22, 33},
1330 []float32{0.5, 0.25, 0.125},
1331 map[string]int{"one": 1, "two": 2},
1334 func TestDebugSingleton(t *testing.T) {
1335 if debugFunc == nil {
1336 return
1338 b := new(bytes.Buffer)
1339 // Accumulate a number of values and print them out all at once.
1340 for _, x := range singletons {
1341 err := NewEncoder(b).Encode(x)
1342 if err != nil {
1343 t.Fatal("encode:", err)
1346 debugFunc(b)
1349 // A type that won't be defined in the gob until we send it in an interface value.
1350 type OnTheFly struct {
1351 A int
1354 type DT struct {
1355 // X OnTheFly
1356 A int
1357 B string
1358 C float64
1359 I interface{}
1360 J interface{}
1361 I_nil interface{}
1362 M map[string]int
1363 T [3]int
1364 S []string
1367 func newDT() DT {
1368 var dt DT
1369 dt.A = 17
1370 dt.B = "hello"
1371 dt.C = 3.14159
1372 dt.I = 271828
1373 dt.J = OnTheFly{3}
1374 dt.I_nil = nil
1375 dt.M = map[string]int{"one": 1, "two": 2}
1376 dt.T = [3]int{11, 22, 33}
1377 dt.S = []string{"hi", "joe"}
1378 return dt
1381 func TestDebugStruct(t *testing.T) {
1382 if debugFunc == nil {
1383 return
1385 Register(OnTheFly{})
1386 dt := newDT()
1387 b := new(bytes.Buffer)
1388 err := NewEncoder(b).Encode(dt)
1389 if err != nil {
1390 t.Fatal("encode:", err)
1392 debugBuffer := bytes.NewBuffer(b.Bytes())
1393 dt2 := &DT{}
1394 err = NewDecoder(b).Decode(&dt2)
1395 if err != nil {
1396 t.Error("decode:", err)
1398 debugFunc(debugBuffer)
1401 func encFuzzDec(rng *rand.Rand, in interface{}) error {
1402 buf := new(bytes.Buffer)
1403 enc := NewEncoder(buf)
1404 if err := enc.Encode(&in); err != nil {
1405 return err
1408 b := buf.Bytes()
1409 for i, bi := range b {
1410 if rng.Intn(10) < 3 {
1411 b[i] = bi + uint8(rng.Intn(256))
1415 dec := NewDecoder(buf)
1416 var e interface{}
1417 if err := dec.Decode(&e); err != nil {
1418 return err
1420 return nil
1423 // This does some "fuzz testing" by attempting to decode a sequence of random bytes.
1424 func TestFuzz(t *testing.T) {
1425 if !*doFuzzTests {
1426 t.Logf("disabled; run with -gob.fuzz to enable")
1427 return
1430 // all possible inputs
1431 input := []interface{}{
1432 new(int),
1433 new(float32),
1434 new(float64),
1435 new(complex128),
1436 &ByteStruct{255},
1437 &ArrayStruct{},
1438 &StringStruct{"hello"},
1439 &GobTest1{0, &StringStruct{"hello"}},
1441 testFuzz(t, time.Now().UnixNano(), 100, input...)
1444 func TestFuzzRegressions(t *testing.T) {
1445 if !*doFuzzTests {
1446 t.Logf("disabled; run with -gob.fuzz to enable")
1447 return
1450 // An instance triggering a type name of length ~102 GB.
1451 testFuzz(t, 1328492090837718000, 100, new(float32))
1452 // An instance triggering a type name of 1.6 GB.
1453 // Note: can take several minutes to run.
1454 testFuzz(t, 1330522872628565000, 100, new(int))
1457 func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) {
1458 for _, e := range input {
1459 t.Logf("seed=%d n=%d e=%T", seed, n, e)
1460 rng := rand.New(rand.NewSource(seed))
1461 for i := 0; i < n; i++ {
1462 encFuzzDec(rng, e)
1467 // TestFuzzOneByte tries to decode corrupted input sequences
1468 // and checks that no panic occurs.
1469 func TestFuzzOneByte(t *testing.T) {
1470 buf := new(bytes.Buffer)
1471 Register(OnTheFly{})
1472 dt := newDT()
1473 if err := NewEncoder(buf).Encode(dt); err != nil {
1474 t.Fatal(err)
1476 s := buf.String()
1478 indices := make([]int, 0, len(s))
1479 for i := 0; i < len(s); i++ {
1480 switch i {
1481 case 14, 167, 231, 265: // a slice length, corruptions are not handled yet.
1482 continue
1484 indices = append(indices, i)
1486 if testing.Short() {
1487 indices = []int{1, 111, 178} // known fixed panics
1489 for _, i := range indices {
1490 for j := 0; j < 256; j += 3 {
1491 b := []byte(s)
1492 b[i] ^= byte(j)
1493 var e DT
1494 func() {
1495 defer func() {
1496 if p := recover(); p != nil {
1497 t.Errorf("crash for b[%d] ^= 0x%x", i, j)
1498 panic(p)
1501 err := NewDecoder(bytes.NewReader(b)).Decode(&e)
1502 _ = err