OSDN Git Service

Update to current version of Go library.
[pf3gnuchains/gcc-fork.git] / libgo / go / gob / codec_test.go
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.
4
5 package gob
6
7 import (
8         "bytes"
9         "math"
10         "os"
11         "reflect"
12         "strings"
13         "testing"
14         "unsafe"
15 )
16
17 // Guarantee encoding format by comparing some encodings to hand-written values
18 type EncodeT struct {
19         x uint64
20         b []byte
21 }
22
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}},
38 }
39
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.
45         }
46         return
47 }
48
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(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())
59                 }
60         }
61         decState := newDecodeState(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)
68                 }
69                 if u&(1<<63) != 0 {
70                         break
71                 }
72         }
73 }
74
75 func verifyInt(i int64, t *testing.T) {
76         defer testError(t)
77         var b = new(bytes.Buffer)
78         encState := newEncoderState(b)
79         encState.encodeInt(i)
80         decState := newDecodeState(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))
85         }
86 }
87
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
98                 }
99         }
100         verifyInt(-1<<63, t) // a tricky case
101 }
102
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'}
113
114 func newDecodeState(buf *bytes.Buffer) *decoderState {
115         d := new(decoderState)
116         d.b = buf
117         d.buf = make([]byte, uint64Size)
118         return d
119 }
120
121 func newEncoderState(b *bytes.Buffer) *encoderState {
122         b.Reset()
123         state := &encoderState{enc: nil, b: b}
124         state.fieldnum = -1
125         return state
126 }
127
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)
132
133         // bool
134         {
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())
141                 }
142         }
143
144         // int
145         {
146                 b.Reset()
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())
153                 }
154         }
155
156         // uint
157         {
158                 b.Reset()
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())
165                 }
166         }
167
168         // int8
169         {
170                 b.Reset()
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())
177                 }
178         }
179
180         // uint8
181         {
182                 b.Reset()
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())
189                 }
190         }
191
192         // int16
193         {
194                 b.Reset()
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())
201                 }
202         }
203
204         // uint16
205         {
206                 b.Reset()
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())
213                 }
214         }
215
216         // int32
217         {
218                 b.Reset()
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())
225                 }
226         }
227
228         // uint32
229         {
230                 b.Reset()
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())
237                 }
238         }
239
240         // int64
241         {
242                 b.Reset()
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())
249                 }
250         }
251
252         // uint64
253         {
254                 b.Reset()
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())
261                 }
262         }
263
264         // float32
265         {
266                 b.Reset()
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())
273                 }
274         }
275
276         // float64
277         {
278                 b.Reset()
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())
285                 }
286         }
287
288         // bytes == []uint8
289         {
290                 b.Reset()
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())
297                 }
298         }
299
300         // string
301         {
302                 b.Reset()
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())
309                 }
310         }
311 }
312
313 func execDec(typ string, instr *decInstr, state *decoderState, t *testing.T, p unsafe.Pointer) {
314         defer testError(t)
315         v := int(state.decodeUint())
316         if v+state.fieldnum != 6 {
317                 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
318         }
319         instr.op(instr, state, decIndirect(p, instr.indir))
320         state.fieldnum = 6
321 }
322
323 func newDecodeStateFromData(data []byte) *decoderState {
324         b := bytes.NewBuffer(data)
325         state := newDecodeState(b)
326         state.fieldnum = -1
327         return state
328 }
329
330 // Test instruction execution for decoding.
331 // Do not run the machine yet; instead do individual instructions crafted by hand.
332 func TestScalarDecInstructions(t *testing.T) {
333         ovfl := os.ErrorString("overflow")
334
335         // bool
336         {
337                 var data struct {
338                         a bool
339                 }
340                 instr := &decInstr{decBool, 6, 0, 0, ovfl}
341                 state := newDecodeStateFromData(boolResult)
342                 execDec("bool", instr, state, t, unsafe.Pointer(&data))
343                 if data.a != true {
344                         t.Errorf("bool a = %v not true", data.a)
345                 }
346         }
347         // int
348         {
349                 var data struct {
350                         a int
351                 }
352                 instr := &decInstr{decOpTable[reflect.Int], 6, 0, 0, ovfl}
353                 state := newDecodeStateFromData(signedResult)
354                 execDec("int", instr, state, t, unsafe.Pointer(&data))
355                 if data.a != 17 {
356                         t.Errorf("int a = %v not 17", data.a)
357                 }
358         }
359
360         // uint
361         {
362                 var data struct {
363                         a uint
364                 }
365                 instr := &decInstr{decOpTable[reflect.Uint], 6, 0, 0, ovfl}
366                 state := newDecodeStateFromData(unsignedResult)
367                 execDec("uint", instr, state, t, unsafe.Pointer(&data))
368                 if data.a != 17 {
369                         t.Errorf("uint a = %v not 17", data.a)
370                 }
371         }
372
373         // int8
374         {
375                 var data struct {
376                         a int8
377                 }
378                 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
379                 state := newDecodeStateFromData(signedResult)
380                 execDec("int8", instr, state, t, unsafe.Pointer(&data))
381                 if data.a != 17 {
382                         t.Errorf("int8 a = %v not 17", data.a)
383                 }
384         }
385
386         // uint8
387         {
388                 var data struct {
389                         a uint8
390                 }
391                 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
392                 state := newDecodeStateFromData(unsignedResult)
393                 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
394                 if data.a != 17 {
395                         t.Errorf("uint8 a = %v not 17", data.a)
396                 }
397         }
398
399         // int16
400         {
401                 var data struct {
402                         a int16
403                 }
404                 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
405                 state := newDecodeStateFromData(signedResult)
406                 execDec("int16", instr, state, t, unsafe.Pointer(&data))
407                 if data.a != 17 {
408                         t.Errorf("int16 a = %v not 17", data.a)
409                 }
410         }
411
412         // uint16
413         {
414                 var data struct {
415                         a uint16
416                 }
417                 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
418                 state := newDecodeStateFromData(unsignedResult)
419                 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
420                 if data.a != 17 {
421                         t.Errorf("uint16 a = %v not 17", data.a)
422                 }
423         }
424
425         // int32
426         {
427                 var data struct {
428                         a int32
429                 }
430                 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
431                 state := newDecodeStateFromData(signedResult)
432                 execDec("int32", instr, state, t, unsafe.Pointer(&data))
433                 if data.a != 17 {
434                         t.Errorf("int32 a = %v not 17", data.a)
435                 }
436         }
437
438         // uint32
439         {
440                 var data struct {
441                         a uint32
442                 }
443                 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
444                 state := newDecodeStateFromData(unsignedResult)
445                 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
446                 if data.a != 17 {
447                         t.Errorf("uint32 a = %v not 17", data.a)
448                 }
449         }
450
451         // uintptr
452         {
453                 var data struct {
454                         a uintptr
455                 }
456                 instr := &decInstr{decOpTable[reflect.Uintptr], 6, 0, 0, ovfl}
457                 state := newDecodeStateFromData(unsignedResult)
458                 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
459                 if data.a != 17 {
460                         t.Errorf("uintptr a = %v not 17", data.a)
461                 }
462         }
463
464         // int64
465         {
466                 var data struct {
467                         a int64
468                 }
469                 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
470                 state := newDecodeStateFromData(signedResult)
471                 execDec("int64", instr, state, t, unsafe.Pointer(&data))
472                 if data.a != 17 {
473                         t.Errorf("int64 a = %v not 17", data.a)
474                 }
475         }
476
477         // uint64
478         {
479                 var data struct {
480                         a uint64
481                 }
482                 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
483                 state := newDecodeStateFromData(unsignedResult)
484                 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
485                 if data.a != 17 {
486                         t.Errorf("uint64 a = %v not 17", data.a)
487                 }
488         }
489
490         // float32
491         {
492                 var data struct {
493                         a float32
494                 }
495                 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
496                 state := newDecodeStateFromData(floatResult)
497                 execDec("float32", instr, state, t, unsafe.Pointer(&data))
498                 if data.a != 17 {
499                         t.Errorf("float32 a = %v not 17", data.a)
500                 }
501         }
502
503         // float64
504         {
505                 var data struct {
506                         a float64
507                 }
508                 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
509                 state := newDecodeStateFromData(floatResult)
510                 execDec("float64", instr, state, t, unsafe.Pointer(&data))
511                 if data.a != 17 {
512                         t.Errorf("float64 a = %v not 17", data.a)
513                 }
514         }
515
516         // complex64
517         {
518                 var data struct {
519                         a complex64
520                 }
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)
526                 }
527         }
528
529         // complex128
530         {
531                 var data struct {
532                         a complex128
533                 }
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)
539                 }
540         }
541
542         // bytes == []uint8
543         {
544                 var data struct {
545                         a []byte
546                 }
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))
552                 }
553         }
554
555         // string
556         {
557                 var data struct {
558                         a string
559                 }
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)
565                 }
566         }
567 }
568
569 func TestEndToEnd(t *testing.T) {
570         type T2 struct {
571                 T string
572         }
573         s1 := "string1"
574         s2 := "string2"
575         type T1 struct {
576                 A, B, C int
577                 M       map[string]*float64
578                 N       *[3]float64
579                 Strs    *[2]string
580                 Int64s  *[]int64
581                 RI      complex64
582                 S       string
583                 Y       []byte
584                 T       *T2
585         }
586         pi := 3.14159
587         e := 2.71828
588         t1 := &T1{
589                 A:      17,
590                 B:      18,
591                 C:      -5,
592                 M:      map[string]*float64{"pi": &pi, "e": &e},
593                 N:      &[3]float64{1.5, 2.5, 3.5},
594                 Strs:   &[2]string{s1, s2},
595                 Int64s: &[]int64{77, 89, 123412342134},
596                 RI:     17 - 23i,
597                 S:      "Now is the time",
598                 Y:      []byte("hello, sailor"),
599                 T:      &T2{"this is T2"},
600         }
601         b := new(bytes.Buffer)
602         err := NewEncoder(b).Encode(t1)
603         if err != nil {
604                 t.Error("encode:", err)
605         }
606         var _t1 T1
607         err = NewDecoder(b).Decode(&_t1)
608         if err != nil {
609                 t.Fatal("decode:", err)
610         }
611         if !reflect.DeepEqual(t1, &_t1) {
612                 t.Errorf("encode expected %v got %v", *t1, _t1)
613         }
614 }
615
616 func TestOverflow(t *testing.T) {
617         type inputT struct {
618                 Maxi int64
619                 Mini int64
620                 Maxu uint64
621                 Maxf float64
622                 Minf float64
623                 Maxc complex128
624                 Minc complex128
625         }
626         var it inputT
627         var err os.Error
628         b := new(bytes.Buffer)
629         enc := NewEncoder(b)
630         dec := NewDecoder(b)
631
632         // int8
633         b.Reset()
634         it = inputT{
635                 Maxi: math.MaxInt8 + 1,
636         }
637         type outi8 struct {
638                 Maxi int8
639                 Mini int8
640         }
641         var o1 outi8
642         enc.Encode(it)
643         err = dec.Decode(&o1)
644         if err == nil || err.String() != `value for "Maxi" out of range` {
645                 t.Error("wrong overflow error for int8:", err)
646         }
647         it = inputT{
648                 Mini: math.MinInt8 - 1,
649         }
650         b.Reset()
651         enc.Encode(it)
652         err = dec.Decode(&o1)
653         if err == nil || err.String() != `value for "Mini" out of range` {
654                 t.Error("wrong underflow error for int8:", err)
655         }
656
657         // int16
658         b.Reset()
659         it = inputT{
660                 Maxi: math.MaxInt16 + 1,
661         }
662         type outi16 struct {
663                 Maxi int16
664                 Mini int16
665         }
666         var o2 outi16
667         enc.Encode(it)
668         err = dec.Decode(&o2)
669         if err == nil || err.String() != `value for "Maxi" out of range` {
670                 t.Error("wrong overflow error for int16:", err)
671         }
672         it = inputT{
673                 Mini: math.MinInt16 - 1,
674         }
675         b.Reset()
676         enc.Encode(it)
677         err = dec.Decode(&o2)
678         if err == nil || err.String() != `value for "Mini" out of range` {
679                 t.Error("wrong underflow error for int16:", err)
680         }
681
682         // int32
683         b.Reset()
684         it = inputT{
685                 Maxi: math.MaxInt32 + 1,
686         }
687         type outi32 struct {
688                 Maxi int32
689                 Mini int32
690         }
691         var o3 outi32
692         enc.Encode(it)
693         err = dec.Decode(&o3)
694         if err == nil || err.String() != `value for "Maxi" out of range` {
695                 t.Error("wrong overflow error for int32:", err)
696         }
697         it = inputT{
698                 Mini: math.MinInt32 - 1,
699         }
700         b.Reset()
701         enc.Encode(it)
702         err = dec.Decode(&o3)
703         if err == nil || err.String() != `value for "Mini" out of range` {
704                 t.Error("wrong underflow error for int32:", err)
705         }
706
707         // uint8
708         b.Reset()
709         it = inputT{
710                 Maxu: math.MaxUint8 + 1,
711         }
712         type outu8 struct {
713                 Maxu uint8
714         }
715         var o4 outu8
716         enc.Encode(it)
717         err = dec.Decode(&o4)
718         if err == nil || err.String() != `value for "Maxu" out of range` {
719                 t.Error("wrong overflow error for uint8:", err)
720         }
721
722         // uint16
723         b.Reset()
724         it = inputT{
725                 Maxu: math.MaxUint16 + 1,
726         }
727         type outu16 struct {
728                 Maxu uint16
729         }
730         var o5 outu16
731         enc.Encode(it)
732         err = dec.Decode(&o5)
733         if err == nil || err.String() != `value for "Maxu" out of range` {
734                 t.Error("wrong overflow error for uint16:", err)
735         }
736
737         // uint32
738         b.Reset()
739         it = inputT{
740                 Maxu: math.MaxUint32 + 1,
741         }
742         type outu32 struct {
743                 Maxu uint32
744         }
745         var o6 outu32
746         enc.Encode(it)
747         err = dec.Decode(&o6)
748         if err == nil || err.String() != `value for "Maxu" out of range` {
749                 t.Error("wrong overflow error for uint32:", err)
750         }
751
752         // float32
753         b.Reset()
754         it = inputT{
755                 Maxf: math.MaxFloat32 * 2,
756         }
757         type outf32 struct {
758                 Maxf float32
759                 Minf float32
760         }
761         var o7 outf32
762         enc.Encode(it)
763         err = dec.Decode(&o7)
764         if err == nil || err.String() != `value for "Maxf" out of range` {
765                 t.Error("wrong overflow error for float32:", err)
766         }
767
768         // complex64
769         b.Reset()
770         it = inputT{
771                 Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
772         }
773         type outc64 struct {
774                 Maxc complex64
775                 Minc complex64
776         }
777         var o8 outc64
778         enc.Encode(it)
779         err = dec.Decode(&o8)
780         if err == nil || err.String() != `value for "Maxc" out of range` {
781                 t.Error("wrong overflow error for complex64:", err)
782         }
783 }
784
785
786 func TestNesting(t *testing.T) {
787         type RT struct {
788                 A    string
789                 Next *RT
790         }
791         rt := new(RT)
792         rt.A = "level1"
793         rt.Next = new(RT)
794         rt.Next.A = "level2"
795         b := new(bytes.Buffer)
796         NewEncoder(b).Encode(rt)
797         var drt RT
798         dec := NewDecoder(b)
799         err := dec.Decode(&drt)
800         if err != nil {
801                 t.Fatal("decoder error:", err)
802         }
803         if drt.A != rt.A {
804                 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
805         }
806         if drt.Next == nil {
807                 t.Errorf("nesting: recursion failed")
808         }
809         if drt.Next.A != rt.Next.A {
810                 t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
811         }
812 }
813
814 // These three structures have the same data with different indirections
815 type T0 struct {
816         A int
817         B int
818         C int
819         D int
820 }
821 type T1 struct {
822         A int
823         B *int
824         C **int
825         D ***int
826 }
827 type T2 struct {
828         A ***int
829         B **int
830         C *int
831         D int
832 }
833
834 func TestAutoIndirection(t *testing.T) {
835         // First transfer t1 into t0
836         var t1 T1
837         t1.A = 17
838         t1.B = new(int)
839         *t1.B = 177
840         t1.C = new(*int)
841         *t1.C = new(int)
842         **t1.C = 1777
843         t1.D = new(**int)
844         *t1.D = new(*int)
845         **t1.D = new(int)
846         ***t1.D = 17777
847         b := new(bytes.Buffer)
848         enc := NewEncoder(b)
849         enc.Encode(t1)
850         dec := NewDecoder(b)
851         var t0 T0
852         dec.Decode(&t0)
853         if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
854                 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
855         }
856
857         // Now transfer t2 into t0
858         var t2 T2
859         t2.D = 17777
860         t2.C = new(int)
861         *t2.C = 1777
862         t2.B = new(*int)
863         *t2.B = new(int)
864         **t2.B = 177
865         t2.A = new(**int)
866         *t2.A = new(*int)
867         **t2.A = new(int)
868         ***t2.A = 17
869         b.Reset()
870         enc.Encode(t2)
871         t0 = T0{}
872         dec.Decode(&t0)
873         if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
874                 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
875         }
876
877         // Now transfer t0 into t1
878         t0 = T0{17, 177, 1777, 17777}
879         b.Reset()
880         enc.Encode(t0)
881         t1 = T1{}
882         dec.Decode(&t1)
883         if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
884                 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
885         }
886
887         // Now transfer t0 into t2
888         b.Reset()
889         enc.Encode(t0)
890         t2 = T2{}
891         dec.Decode(&t2)
892         if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
893                 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
894         }
895
896         // Now do t2 again but without pre-allocated pointers.
897         b.Reset()
898         enc.Encode(t0)
899         ***t2.A = 0
900         **t2.B = 0
901         *t2.C = 0
902         t2.D = 0
903         dec.Decode(&t2)
904         if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
905                 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
906         }
907 }
908
909 type RT0 struct {
910         A int
911         B string
912         C float64
913 }
914 type RT1 struct {
915         C      float64
916         B      string
917         A      int
918         NotSet string
919 }
920
921 func TestReorderedFields(t *testing.T) {
922         var rt0 RT0
923         rt0.A = 17
924         rt0.B = "hello"
925         rt0.C = 3.14159
926         b := new(bytes.Buffer)
927         NewEncoder(b).Encode(rt0)
928         dec := NewDecoder(b)
929         var rt1 RT1
930         // Wire type is RT0, local type is RT1.
931         err := dec.Decode(&rt1)
932         if err != nil {
933                 t.Fatal("decode error:", err)
934         }
935         if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
936                 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
937         }
938 }
939
940 // Like an RT0 but with fields we'll ignore on the decode side.
941 type IT0 struct {
942         A        int64
943         B        string
944         Ignore_d []int
945         Ignore_e [3]float64
946         Ignore_f bool
947         Ignore_g string
948         Ignore_h []byte
949         Ignore_i *RT1
950         Ignore_m map[string]int
951         C        float64
952 }
953
954 func TestIgnoredFields(t *testing.T) {
955         var it0 IT0
956         it0.A = 17
957         it0.B = "hello"
958         it0.C = 3.14159
959         it0.Ignore_d = []int{1, 2, 3}
960         it0.Ignore_e[0] = 1.0
961         it0.Ignore_e[1] = 2.0
962         it0.Ignore_e[2] = 3.0
963         it0.Ignore_f = true
964         it0.Ignore_g = "pay no attention"
965         it0.Ignore_h = []byte("to the curtain")
966         it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
967         it0.Ignore_m = map[string]int{"one": 1, "two": 2}
968
969         b := new(bytes.Buffer)
970         NewEncoder(b).Encode(it0)
971         dec := NewDecoder(b)
972         var rt1 RT1
973         // Wire type is IT0, local type is RT1.
974         err := dec.Decode(&rt1)
975         if err != nil {
976                 t.Error("error: ", err)
977         }
978         if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
979                 t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
980         }
981 }
982
983
984 func TestBadRecursiveType(t *testing.T) {
985         type Rec ***Rec
986         var rec Rec
987         b := new(bytes.Buffer)
988         err := NewEncoder(b).Encode(&rec)
989         if err == nil {
990                 t.Error("expected error; got none")
991         } else if strings.Index(err.String(), "recursive") < 0 {
992                 t.Error("expected recursive type error; got", err)
993         }
994         // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
995 }
996
997 type Bad0 struct {
998         CH chan int
999         C  float64
1000 }
1001
1002 func TestInvalidField(t *testing.T) {
1003         var bad0 Bad0
1004         bad0.CH = make(chan int)
1005         b := new(bytes.Buffer)
1006         dummyEncoder := new(Encoder) // sufficient for this purpose.
1007         dummyEncoder.encode(b, reflect.ValueOf(&bad0), userType(reflect.TypeOf(&bad0)))
1008         if err := dummyEncoder.err; err == nil {
1009                 t.Error("expected error; got none")
1010         } else if strings.Index(err.String(), "type") < 0 {
1011                 t.Error("expected type error; got", err)
1012         }
1013 }
1014
1015 type Indirect struct {
1016         A ***[3]int
1017         S ***[]int
1018         M ****map[string]int
1019 }
1020
1021 type Direct struct {
1022         A [3]int
1023         S []int
1024         M map[string]int
1025 }
1026
1027 func TestIndirectSliceMapArray(t *testing.T) {
1028         // Marshal indirect, unmarshal to direct.
1029         i := new(Indirect)
1030         i.A = new(**[3]int)
1031         *i.A = new(*[3]int)
1032         **i.A = new([3]int)
1033         ***i.A = [3]int{1, 2, 3}
1034         i.S = new(**[]int)
1035         *i.S = new(*[]int)
1036         **i.S = new([]int)
1037         ***i.S = []int{4, 5, 6}
1038         i.M = new(***map[string]int)
1039         *i.M = new(**map[string]int)
1040         **i.M = new(*map[string]int)
1041         ***i.M = new(map[string]int)
1042         ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1043         b := new(bytes.Buffer)
1044         NewEncoder(b).Encode(i)
1045         dec := NewDecoder(b)
1046         var d Direct
1047         err := dec.Decode(&d)
1048         if err != nil {
1049                 t.Error("error: ", err)
1050         }
1051         if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1052                 t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1053         }
1054         if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1055                 t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1056         }
1057         if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1058                 t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1059         }
1060         // Marshal direct, unmarshal to indirect.
1061         d.A = [3]int{11, 22, 33}
1062         d.S = []int{44, 55, 66}
1063         d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1064         i = new(Indirect)
1065         b.Reset()
1066         NewEncoder(b).Encode(d)
1067         dec = NewDecoder(b)
1068         err = dec.Decode(&i)
1069         if err != nil {
1070                 t.Fatal("error: ", err)
1071         }
1072         if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1073                 t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1074         }
1075         if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1076                 t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1077         }
1078         if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1079                 t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1080         }
1081 }
1082
1083 // An interface with several implementations
1084 type Squarer interface {
1085         Square() int
1086 }
1087
1088 type Int int
1089
1090 func (i Int) Square() int {
1091         return int(i * i)
1092 }
1093
1094 type Float float64
1095
1096 func (f Float) Square() int {
1097         return int(f * f)
1098 }
1099
1100 type Vector []int
1101
1102 func (v Vector) Square() int {
1103         sum := 0
1104         for _, x := range v {
1105                 sum += x * x
1106         }
1107         return sum
1108 }
1109
1110 type Point struct {
1111         X, Y int
1112 }
1113
1114 func (p Point) Square() int {
1115         return p.X*p.X + p.Y*p.Y
1116 }
1117
1118 // A struct with interfaces in it.
1119 type InterfaceItem struct {
1120         I             int
1121         Sq1, Sq2, Sq3 Squarer
1122         F             float64
1123         Sq            []Squarer
1124 }
1125
1126 // The same struct without interfaces
1127 type NoInterfaceItem struct {
1128         I int
1129         F float64
1130 }
1131
1132 func TestInterface(t *testing.T) {
1133         iVal := Int(3)
1134         fVal := Float(5)
1135         // Sending a Vector will require that the receiver define a type in the middle of
1136         // receiving the value for item2.
1137         vVal := Vector{1, 2, 3}
1138         b := new(bytes.Buffer)
1139         item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1140         // Register the types.
1141         Register(Int(0))
1142         Register(Float(0))
1143         Register(Vector{})
1144         err := NewEncoder(b).Encode(item1)
1145         if err != nil {
1146                 t.Error("expected no encode error; got", err)
1147         }
1148
1149         item2 := InterfaceItem{}
1150         err = NewDecoder(b).Decode(&item2)
1151         if err != nil {
1152                 t.Fatal("decode:", err)
1153         }
1154         if item2.I != item1.I {
1155                 t.Error("normal int did not decode correctly")
1156         }
1157         if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1158                 t.Error("Int did not decode correctly")
1159         }
1160         if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1161                 t.Error("Float did not decode correctly")
1162         }
1163         if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1164                 t.Error("Vector did not decode correctly")
1165         }
1166         if item2.F != item1.F {
1167                 t.Error("normal float did not decode correctly")
1168         }
1169         // Now check that we received a slice of Squarers correctly, including a nil element
1170         if len(item1.Sq) != len(item2.Sq) {
1171                 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1172         }
1173         for i, v1 := range item1.Sq {
1174                 v2 := item2.Sq[i]
1175                 if v1 == nil || v2 == nil {
1176                         if v1 != nil || v2 != nil {
1177                                 t.Errorf("item %d inconsistent nils", i)
1178                         }
1179                         continue
1180                         if v1.Square() != v2.Square() {
1181                                 t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1182                         }
1183                 }
1184         }
1185 }
1186
1187 // A struct with all basic types, stored in interfaces.
1188 type BasicInterfaceItem struct {
1189         Int, Int8, Int16, Int32, Int64      interface{}
1190         Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1191         Float32, Float64                    interface{}
1192         Complex64, Complex128               interface{}
1193         Bool                                interface{}
1194         String                              interface{}
1195         Bytes                               interface{}
1196 }
1197
1198 func TestInterfaceBasic(t *testing.T) {
1199         b := new(bytes.Buffer)
1200         item1 := &BasicInterfaceItem{
1201                 int(1), int8(1), int16(1), int32(1), int64(1),
1202                 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1203                 float32(1), 1.0,
1204                 complex64(1i), complex128(1i),
1205                 true,
1206                 "hello",
1207                 []byte("sailor"),
1208         }
1209         err := NewEncoder(b).Encode(item1)
1210         if err != nil {
1211                 t.Error("expected no encode error; got", err)
1212         }
1213
1214         item2 := &BasicInterfaceItem{}
1215         err = NewDecoder(b).Decode(&item2)
1216         if err != nil {
1217                 t.Fatal("decode:", err)
1218         }
1219         if !reflect.DeepEqual(item1, item2) {
1220                 t.Errorf("encode expected %v got %v", item1, item2)
1221         }
1222         // Hand check a couple for correct types.
1223         if v, ok := item2.Bool.(bool); !ok || !v {
1224                 t.Error("boolean should be true")
1225         }
1226         if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1227                 t.Errorf("string should be %v is %v", item1.String, v)
1228         }
1229 }
1230
1231 type String string
1232
1233 type PtrInterfaceItem struct {
1234         Str1 interface{} // basic
1235         Str2 interface{} // derived
1236 }
1237
1238 // We'll send pointers; should receive values.
1239 // Also check that we can register T but send *T.
1240 func TestInterfacePointer(t *testing.T) {
1241         b := new(bytes.Buffer)
1242         str1 := "howdy"
1243         str2 := String("kiddo")
1244         item1 := &PtrInterfaceItem{
1245                 &str1,
1246                 &str2,
1247         }
1248         // Register the type.
1249         Register(str2)
1250         err := NewEncoder(b).Encode(item1)
1251         if err != nil {
1252                 t.Error("expected no encode error; got", err)
1253         }
1254
1255         item2 := &PtrInterfaceItem{}
1256         err = NewDecoder(b).Decode(&item2)
1257         if err != nil {
1258                 t.Fatal("decode:", err)
1259         }
1260         // Hand test for correct types and values.
1261         if v, ok := item2.Str1.(string); !ok || v != str1 {
1262                 t.Errorf("basic string failed: %q should be %q", v, str1)
1263         }
1264         if v, ok := item2.Str2.(String); !ok || v != str2 {
1265                 t.Errorf("derived type String failed: %q should be %q", v, str2)
1266         }
1267 }
1268
1269 func TestIgnoreInterface(t *testing.T) {
1270         iVal := Int(3)
1271         fVal := Float(5)
1272         // Sending a Point will require that the receiver define a type in the middle of
1273         // receiving the value for item2.
1274         pVal := Point{2, 3}
1275         b := new(bytes.Buffer)
1276         item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1277         // Register the types.
1278         Register(Int(0))
1279         Register(Float(0))
1280         Register(Point{})
1281         err := NewEncoder(b).Encode(item1)
1282         if err != nil {
1283                 t.Error("expected no encode error; got", err)
1284         }
1285
1286         item2 := NoInterfaceItem{}
1287         err = NewDecoder(b).Decode(&item2)
1288         if err != nil {
1289                 t.Fatal("decode:", err)
1290         }
1291         if item2.I != item1.I {
1292                 t.Error("normal int did not decode correctly")
1293         }
1294         if item2.F != item2.F {
1295                 t.Error("normal float did not decode correctly")
1296         }
1297 }
1298
1299 type U struct {
1300         A int
1301         B string
1302         c float64
1303         D uint
1304 }
1305
1306 func TestUnexportedFields(t *testing.T) {
1307         var u0 U
1308         u0.A = 17
1309         u0.B = "hello"
1310         u0.c = 3.14159
1311         u0.D = 23
1312         b := new(bytes.Buffer)
1313         NewEncoder(b).Encode(u0)
1314         dec := NewDecoder(b)
1315         var u1 U
1316         u1.c = 1234.
1317         err := dec.Decode(&u1)
1318         if err != nil {
1319                 t.Fatal("decode error:", err)
1320         }
1321         if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1322                 t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1323         }
1324         if u1.c != 1234. {
1325                 t.Error("u1.c modified")
1326         }
1327 }
1328
1329 var singletons = []interface{}{
1330         true,
1331         7,
1332         3.2,
1333         "hello",
1334         [3]int{11, 22, 33},
1335         []float32{0.5, 0.25, 0.125},
1336         map[string]int{"one": 1, "two": 2},
1337 }
1338
1339 func TestDebugSingleton(t *testing.T) {
1340         if debugFunc == nil {
1341                 return
1342         }
1343         b := new(bytes.Buffer)
1344         // Accumulate a number of values and print them out all at once.
1345         for _, x := range singletons {
1346                 err := NewEncoder(b).Encode(x)
1347                 if err != nil {
1348                         t.Fatal("encode:", err)
1349                 }
1350         }
1351         debugFunc(b)
1352 }
1353
1354 // A type that won't be defined in the gob until we send it in an interface value.
1355 type OnTheFly struct {
1356         A int
1357 }
1358
1359 type DT struct {
1360         //      X OnTheFly
1361         A     int
1362         B     string
1363         C     float64
1364         I     interface{}
1365         J     interface{}
1366         I_nil interface{}
1367         M     map[string]int
1368         T     [3]int
1369         S     []string
1370 }
1371
1372 func TestDebugStruct(t *testing.T) {
1373         if debugFunc == nil {
1374                 return
1375         }
1376         Register(OnTheFly{})
1377         var dt DT
1378         dt.A = 17
1379         dt.B = "hello"
1380         dt.C = 3.14159
1381         dt.I = 271828
1382         dt.J = OnTheFly{3}
1383         dt.I_nil = nil
1384         dt.M = map[string]int{"one": 1, "two": 2}
1385         dt.T = [3]int{11, 22, 33}
1386         dt.S = []string{"hi", "joe"}
1387         b := new(bytes.Buffer)
1388         err := NewEncoder(b).Encode(dt)
1389         if err != nil {
1390                 t.Fatal("encode:", err)
1391         }
1392         debugBuffer := bytes.NewBuffer(b.Bytes())
1393         dt2 := &DT{}
1394         err = NewDecoder(b).Decode(&dt2)
1395         if err != nil {
1396                 t.Error("decode:", err)
1397         }
1398         debugFunc(debugBuffer)
1399 }