]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/gob/codec_test.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.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(nil, b)
54 for _, tt := range encodeT {
55 b.Reset()
56 encodeUint(encState, tt.x)
57 if !bytes.Equal(tt.b, b.Bytes()) {
58 t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
59 }
60 }
61 decState := newDecodeState(nil, &b)
62 for u := uint64(0); ; u = (u + 1) * 7 {
63 b.Reset()
64 encodeUint(encState, u)
65 v := decodeUint(decState)
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(nil, b)
79 encodeInt(encState, i)
80 decState := newDecodeState(nil, &b)
81 decState.buf = make([]byte, 8)
82 j := decodeInt(decState)
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 newencoderState(b *bytes.Buffer) *encoderState {
115 b.Reset()
116 state := newEncoderState(nil, b)
117 state.fieldnum = -1
118 return state
119 }
120
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)
125
126 // bool
127 {
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())
134 }
135 }
136
137 // int
138 {
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())
146 }
147 }
148
149 // uint
150 {
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())
158 }
159 }
160
161 // int8
162 {
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())
170 }
171 }
172
173 // uint8
174 {
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())
182 }
183 }
184
185 // int16
186 {
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())
194 }
195 }
196
197 // uint16
198 {
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())
206 }
207 }
208
209 // int32
210 {
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())
218 }
219 }
220
221 // uint32
222 {
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())
230 }
231 }
232
233 // int64
234 {
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())
242 }
243 }
244
245 // uint64
246 {
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())
254 }
255 }
256
257 // float
258 {
259 b.Reset()
260 data := struct{ a float }{17}
261 instr := &encInstr{encFloat, 6, 0, 0}
262 state := newencoderState(b)
263 instr.op(instr, state, unsafe.Pointer(&data))
264 if !bytes.Equal(floatResult, b.Bytes()) {
265 t.Errorf("float enc instructions: expected % x got % x", floatResult, b.Bytes())
266 }
267 }
268
269 // float32
270 {
271 b.Reset()
272 data := struct{ a float32 }{17}
273 instr := &encInstr{encFloat32, 6, 0, 0}
274 state := newencoderState(b)
275 instr.op(instr, state, unsafe.Pointer(&data))
276 if !bytes.Equal(floatResult, b.Bytes()) {
277 t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
278 }
279 }
280
281 // float64
282 {
283 b.Reset()
284 data := struct{ a float64 }{17}
285 instr := &encInstr{encFloat64, 6, 0, 0}
286 state := newencoderState(b)
287 instr.op(instr, state, unsafe.Pointer(&data))
288 if !bytes.Equal(floatResult, b.Bytes()) {
289 t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
290 }
291 }
292
293 // bytes == []uint8
294 {
295 b.Reset()
296 data := struct{ a []byte }{[]byte("hello")}
297 instr := &encInstr{encUint8Array, 6, 0, 0}
298 state := newencoderState(b)
299 instr.op(instr, state, unsafe.Pointer(&data))
300 if !bytes.Equal(bytesResult, b.Bytes()) {
301 t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
302 }
303 }
304
305 // string
306 {
307 b.Reset()
308 data := struct{ a string }{"hello"}
309 instr := &encInstr{encString, 6, 0, 0}
310 state := newencoderState(b)
311 instr.op(instr, state, unsafe.Pointer(&data))
312 if !bytes.Equal(bytesResult, b.Bytes()) {
313 t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
314 }
315 }
316 }
317
318 func execDec(typ string, instr *decInstr, state *decodeState, t *testing.T, p unsafe.Pointer) {
319 defer testError(t)
320 v := int(decodeUint(state))
321 if v+state.fieldnum != 6 {
322 t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
323 }
324 instr.op(instr, state, decIndirect(p, instr.indir))
325 state.fieldnum = 6
326 }
327
328 func newDecodeStateFromData(data []byte) *decodeState {
329 b := bytes.NewBuffer(data)
330 state := newDecodeState(nil, &b)
331 state.fieldnum = -1
332 return state
333 }
334
335 // Test instruction execution for decoding.
336 // Do not run the machine yet; instead do individual instructions crafted by hand.
337 func TestScalarDecInstructions(t *testing.T) {
338 ovfl := os.ErrorString("overflow")
339
340 // bool
341 {
342 var data struct {
343 a bool
344 }
345 instr := &decInstr{decBool, 6, 0, 0, ovfl}
346 state := newDecodeStateFromData(boolResult)
347 execDec("bool", instr, state, t, unsafe.Pointer(&data))
348 if data.a != true {
349 t.Errorf("bool a = %v not true", data.a)
350 }
351 }
352 // int
353 {
354 var data struct {
355 a int
356 }
357 instr := &decInstr{decOpMap[reflect.Int], 6, 0, 0, ovfl}
358 state := newDecodeStateFromData(signedResult)
359 execDec("int", instr, state, t, unsafe.Pointer(&data))
360 if data.a != 17 {
361 t.Errorf("int a = %v not 17", data.a)
362 }
363 }
364
365 // uint
366 {
367 var data struct {
368 a uint
369 }
370 instr := &decInstr{decOpMap[reflect.Uint], 6, 0, 0, ovfl}
371 state := newDecodeStateFromData(unsignedResult)
372 execDec("uint", instr, state, t, unsafe.Pointer(&data))
373 if data.a != 17 {
374 t.Errorf("uint a = %v not 17", data.a)
375 }
376 }
377
378 // int8
379 {
380 var data struct {
381 a int8
382 }
383 instr := &decInstr{decInt8, 6, 0, 0, ovfl}
384 state := newDecodeStateFromData(signedResult)
385 execDec("int8", instr, state, t, unsafe.Pointer(&data))
386 if data.a != 17 {
387 t.Errorf("int8 a = %v not 17", data.a)
388 }
389 }
390
391 // uint8
392 {
393 var data struct {
394 a uint8
395 }
396 instr := &decInstr{decUint8, 6, 0, 0, ovfl}
397 state := newDecodeStateFromData(unsignedResult)
398 execDec("uint8", instr, state, t, unsafe.Pointer(&data))
399 if data.a != 17 {
400 t.Errorf("uint8 a = %v not 17", data.a)
401 }
402 }
403
404 // int16
405 {
406 var data struct {
407 a int16
408 }
409 instr := &decInstr{decInt16, 6, 0, 0, ovfl}
410 state := newDecodeStateFromData(signedResult)
411 execDec("int16", instr, state, t, unsafe.Pointer(&data))
412 if data.a != 17 {
413 t.Errorf("int16 a = %v not 17", data.a)
414 }
415 }
416
417 // uint16
418 {
419 var data struct {
420 a uint16
421 }
422 instr := &decInstr{decUint16, 6, 0, 0, ovfl}
423 state := newDecodeStateFromData(unsignedResult)
424 execDec("uint16", instr, state, t, unsafe.Pointer(&data))
425 if data.a != 17 {
426 t.Errorf("uint16 a = %v not 17", data.a)
427 }
428 }
429
430 // int32
431 {
432 var data struct {
433 a int32
434 }
435 instr := &decInstr{decInt32, 6, 0, 0, ovfl}
436 state := newDecodeStateFromData(signedResult)
437 execDec("int32", instr, state, t, unsafe.Pointer(&data))
438 if data.a != 17 {
439 t.Errorf("int32 a = %v not 17", data.a)
440 }
441 }
442
443 // uint32
444 {
445 var data struct {
446 a uint32
447 }
448 instr := &decInstr{decUint32, 6, 0, 0, ovfl}
449 state := newDecodeStateFromData(unsignedResult)
450 execDec("uint32", instr, state, t, unsafe.Pointer(&data))
451 if data.a != 17 {
452 t.Errorf("uint32 a = %v not 17", data.a)
453 }
454 }
455
456 // uintptr
457 {
458 var data struct {
459 a uintptr
460 }
461 instr := &decInstr{decOpMap[reflect.Uintptr], 6, 0, 0, ovfl}
462 state := newDecodeStateFromData(unsignedResult)
463 execDec("uintptr", instr, state, t, unsafe.Pointer(&data))
464 if data.a != 17 {
465 t.Errorf("uintptr a = %v not 17", data.a)
466 }
467 }
468
469 // int64
470 {
471 var data struct {
472 a int64
473 }
474 instr := &decInstr{decInt64, 6, 0, 0, ovfl}
475 state := newDecodeStateFromData(signedResult)
476 execDec("int64", instr, state, t, unsafe.Pointer(&data))
477 if data.a != 17 {
478 t.Errorf("int64 a = %v not 17", data.a)
479 }
480 }
481
482 // uint64
483 {
484 var data struct {
485 a uint64
486 }
487 instr := &decInstr{decUint64, 6, 0, 0, ovfl}
488 state := newDecodeStateFromData(unsignedResult)
489 execDec("uint64", instr, state, t, unsafe.Pointer(&data))
490 if data.a != 17 {
491 t.Errorf("uint64 a = %v not 17", data.a)
492 }
493 }
494
495 // float
496 {
497 var data struct {
498 a float
499 }
500 instr := &decInstr{decOpMap[reflect.Float], 6, 0, 0, ovfl}
501 state := newDecodeStateFromData(floatResult)
502 execDec("float", instr, state, t, unsafe.Pointer(&data))
503 if data.a != 17 {
504 t.Errorf("float a = %v not 17", data.a)
505 }
506 }
507
508 // float32
509 {
510 var data struct {
511 a float32
512 }
513 instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
514 state := newDecodeStateFromData(floatResult)
515 execDec("float32", instr, state, t, unsafe.Pointer(&data))
516 if data.a != 17 {
517 t.Errorf("float32 a = %v not 17", data.a)
518 }
519 }
520
521 // float64
522 {
523 var data struct {
524 a float64
525 }
526 instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
527 state := newDecodeStateFromData(floatResult)
528 execDec("float64", instr, state, t, unsafe.Pointer(&data))
529 if data.a != 17 {
530 t.Errorf("float64 a = %v not 17", data.a)
531 }
532 }
533
534 // complex
535 {
536 var data struct {
537 a complex
538 }
539 instr := &decInstr{decOpMap[reflect.Complex], 6, 0, 0, ovfl}
540 state := newDecodeStateFromData(complexResult)
541 execDec("complex", instr, state, t, unsafe.Pointer(&data))
542 if data.a != 17+19i {
543 t.Errorf("complex a = %v not 17+19i", data.a)
544 }
545 }
546
547 // complex64
548 {
549 var data struct {
550 a complex64
551 }
552 instr := &decInstr{decOpMap[reflect.Complex64], 6, 0, 0, ovfl}
553 state := newDecodeStateFromData(complexResult)
554 execDec("complex", instr, state, t, unsafe.Pointer(&data))
555 if data.a != 17+19i {
556 t.Errorf("complex a = %v not 17+19i", data.a)
557 }
558 }
559
560 // complex128
561 {
562 var data struct {
563 a complex128
564 }
565 instr := &decInstr{decOpMap[reflect.Complex128], 6, 0, 0, ovfl}
566 state := newDecodeStateFromData(complexResult)
567 execDec("complex", instr, state, t, unsafe.Pointer(&data))
568 if data.a != 17+19i {
569 t.Errorf("complex a = %v not 17+19i", data.a)
570 }
571 }
572
573 // bytes == []uint8
574 {
575 var data struct {
576 a []byte
577 }
578 instr := &decInstr{decUint8Array, 6, 0, 0, ovfl}
579 state := newDecodeStateFromData(bytesResult)
580 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
581 if string(data.a) != "hello" {
582 t.Errorf(`bytes a = %q not "hello"`, string(data.a))
583 }
584 }
585
586 // string
587 {
588 var data struct {
589 a string
590 }
591 instr := &decInstr{decString, 6, 0, 0, ovfl}
592 state := newDecodeStateFromData(bytesResult)
593 execDec("bytes", instr, state, t, unsafe.Pointer(&data))
594 if data.a != "hello" {
595 t.Errorf(`bytes a = %q not "hello"`, data.a)
596 }
597 }
598 }
599
600 func TestEndToEnd(t *testing.T) {
601 type T2 struct {
602 t string
603 }
604 s1 := "string1"
605 s2 := "string2"
606 type T1 struct {
607 a, b, c int
608 m map[string]*float
609 n *[3]float
610 strs *[2]string
611 int64s *[]int64
612 ri complex64
613 s string
614 y []byte
615 t *T2
616 }
617 pi := 3.14159
618 e := 2.71828
619 t1 := &T1{
620 a: 17,
621 b: 18,
622 c: -5,
623 m: map[string]*float{"pi": &pi, "e": &e},
624 n: &[3]float{1.5, 2.5, 3.5},
625 strs: &[2]string{s1, s2},
626 int64s: &[]int64{77, 89, 123412342134},
627 ri: 17 - 23i,
628 s: "Now is the time",
629 y: []byte("hello, sailor"),
630 t: &T2{"this is T2"},
631 }
632 b := new(bytes.Buffer)
633 err := NewEncoder(b).Encode(t1)
634 if err != nil {
635 t.Error("encode:", err)
636 }
637 var _t1 T1
638 err = NewDecoder(b).Decode(&_t1)
639 if err != nil {
640 t.Fatal("decode:", err)
641 }
642 if !reflect.DeepEqual(t1, &_t1) {
643 t.Errorf("encode expected %v got %v", *t1, _t1)
644 }
645 }
646
647 func TestOverflow(t *testing.T) {
648 type inputT struct {
649 maxi int64
650 mini int64
651 maxu uint64
652 maxf float64
653 minf float64
654 maxc complex128
655 minc complex128
656 }
657 var it inputT
658 var err os.Error
659 b := new(bytes.Buffer)
660 enc := NewEncoder(b)
661 dec := NewDecoder(b)
662
663 // int8
664 b.Reset()
665 it = inputT{
666 maxi: math.MaxInt8 + 1,
667 }
668 type outi8 struct {
669 maxi int8
670 mini int8
671 }
672 var o1 outi8
673 enc.Encode(it)
674 err = dec.Decode(&o1)
675 if err == nil || err.String() != `value for "maxi" out of range` {
676 t.Error("wrong overflow error for int8:", err)
677 }
678 it = inputT{
679 mini: math.MinInt8 - 1,
680 }
681 b.Reset()
682 enc.Encode(it)
683 err = dec.Decode(&o1)
684 if err == nil || err.String() != `value for "mini" out of range` {
685 t.Error("wrong underflow error for int8:", err)
686 }
687
688 // int16
689 b.Reset()
690 it = inputT{
691 maxi: math.MaxInt16 + 1,
692 }
693 type outi16 struct {
694 maxi int16
695 mini int16
696 }
697 var o2 outi16
698 enc.Encode(it)
699 err = dec.Decode(&o2)
700 if err == nil || err.String() != `value for "maxi" out of range` {
701 t.Error("wrong overflow error for int16:", err)
702 }
703 it = inputT{
704 mini: math.MinInt16 - 1,
705 }
706 b.Reset()
707 enc.Encode(it)
708 err = dec.Decode(&o2)
709 if err == nil || err.String() != `value for "mini" out of range` {
710 t.Error("wrong underflow error for int16:", err)
711 }
712
713 // int32
714 b.Reset()
715 it = inputT{
716 maxi: math.MaxInt32 + 1,
717 }
718 type outi32 struct {
719 maxi int32
720 mini int32
721 }
722 var o3 outi32
723 enc.Encode(it)
724 err = dec.Decode(&o3)
725 if err == nil || err.String() != `value for "maxi" out of range` {
726 t.Error("wrong overflow error for int32:", err)
727 }
728 it = inputT{
729 mini: math.MinInt32 - 1,
730 }
731 b.Reset()
732 enc.Encode(it)
733 err = dec.Decode(&o3)
734 if err == nil || err.String() != `value for "mini" out of range` {
735 t.Error("wrong underflow error for int32:", err)
736 }
737
738 // uint8
739 b.Reset()
740 it = inputT{
741 maxu: math.MaxUint8 + 1,
742 }
743 type outu8 struct {
744 maxu uint8
745 }
746 var o4 outu8
747 enc.Encode(it)
748 err = dec.Decode(&o4)
749 if err == nil || err.String() != `value for "maxu" out of range` {
750 t.Error("wrong overflow error for uint8:", err)
751 }
752
753 // uint16
754 b.Reset()
755 it = inputT{
756 maxu: math.MaxUint16 + 1,
757 }
758 type outu16 struct {
759 maxu uint16
760 }
761 var o5 outu16
762 enc.Encode(it)
763 err = dec.Decode(&o5)
764 if err == nil || err.String() != `value for "maxu" out of range` {
765 t.Error("wrong overflow error for uint16:", err)
766 }
767
768 // uint32
769 b.Reset()
770 it = inputT{
771 maxu: math.MaxUint32 + 1,
772 }
773 type outu32 struct {
774 maxu uint32
775 }
776 var o6 outu32
777 enc.Encode(it)
778 err = dec.Decode(&o6)
779 if err == nil || err.String() != `value for "maxu" out of range` {
780 t.Error("wrong overflow error for uint32:", err)
781 }
782
783 // float32
784 b.Reset()
785 it = inputT{
786 maxf: math.MaxFloat32 * 2,
787 }
788 type outf32 struct {
789 maxf float32
790 minf float32
791 }
792 var o7 outf32
793 enc.Encode(it)
794 err = dec.Decode(&o7)
795 if err == nil || err.String() != `value for "maxf" out of range` {
796 t.Error("wrong overflow error for float32:", err)
797 }
798
799 // complex64
800 b.Reset()
801 it = inputT{
802 maxc: cmplx(math.MaxFloat32*2, math.MaxFloat32*2),
803 }
804 type outc64 struct {
805 maxc complex64
806 minc complex64
807 }
808 var o8 outc64
809 enc.Encode(it)
810 err = dec.Decode(&o8)
811 if err == nil || err.String() != `value for "maxc" out of range` {
812 t.Error("wrong overflow error for complex64:", err)
813 }
814 }
815
816
817 func TestNesting(t *testing.T) {
818 type RT struct {
819 a string
820 next *RT
821 }
822 rt := new(RT)
823 rt.a = "level1"
824 rt.next = new(RT)
825 rt.next.a = "level2"
826 b := new(bytes.Buffer)
827 NewEncoder(b).Encode(rt)
828 var drt RT
829 dec := NewDecoder(b)
830 err := dec.Decode(&drt)
831 if err != nil {
832 t.Errorf("decoder error:", err)
833 }
834 if drt.a != rt.a {
835 t.Errorf("nesting: encode expected %v got %v", *rt, drt)
836 }
837 if drt.next == nil {
838 t.Errorf("nesting: recursion failed")
839 }
840 if drt.next.a != rt.next.a {
841 t.Errorf("nesting: encode expected %v got %v", *rt.next, *drt.next)
842 }
843 }
844
845 // These three structures have the same data with different indirections
846 type T0 struct {
847 a int
848 b int
849 c int
850 d int
851 }
852 type T1 struct {
853 a int
854 b *int
855 c **int
856 d ***int
857 }
858 type T2 struct {
859 a ***int
860 b **int
861 c *int
862 d int
863 }
864
865 func TestAutoIndirection(t *testing.T) {
866 // First transfer t1 into t0
867 var t1 T1
868 t1.a = 17
869 t1.b = new(int)
870 *t1.b = 177
871 t1.c = new(*int)
872 *t1.c = new(int)
873 **t1.c = 1777
874 t1.d = new(**int)
875 *t1.d = new(*int)
876 **t1.d = new(int)
877 ***t1.d = 17777
878 b := new(bytes.Buffer)
879 enc := NewEncoder(b)
880 enc.Encode(t1)
881 dec := NewDecoder(b)
882 var t0 T0
883 dec.Decode(&t0)
884 if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 {
885 t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
886 }
887
888 // Now transfer t2 into t0
889 var t2 T2
890 t2.d = 17777
891 t2.c = new(int)
892 *t2.c = 1777
893 t2.b = new(*int)
894 *t2.b = new(int)
895 **t2.b = 177
896 t2.a = new(**int)
897 *t2.a = new(*int)
898 **t2.a = new(int)
899 ***t2.a = 17
900 b.Reset()
901 enc.Encode(t2)
902 t0 = T0{}
903 dec.Decode(&t0)
904 if t0.a != 17 || t0.b != 177 || t0.c != 1777 || t0.d != 17777 {
905 t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
906 }
907
908 // Now transfer t0 into t1
909 t0 = T0{17, 177, 1777, 17777}
910 b.Reset()
911 enc.Encode(t0)
912 t1 = T1{}
913 dec.Decode(&t1)
914 if t1.a != 17 || *t1.b != 177 || **t1.c != 1777 || ***t1.d != 17777 {
915 t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.a, *t1.b, **t1.c, ***t1.d)
916 }
917
918 // Now transfer t0 into t2
919 b.Reset()
920 enc.Encode(t0)
921 t2 = T2{}
922 dec.Decode(&t2)
923 if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 {
924 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d)
925 }
926
927 // Now do t2 again but without pre-allocated pointers.
928 b.Reset()
929 enc.Encode(t0)
930 ***t2.a = 0
931 **t2.b = 0
932 *t2.c = 0
933 t2.d = 0
934 dec.Decode(&t2)
935 if ***t2.a != 17 || **t2.b != 177 || *t2.c != 1777 || t2.d != 17777 {
936 t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.a, **t2.b, *t2.c, t2.d)
937 }
938 }
939
940 type RT0 struct {
941 a int
942 b string
943 c float
944 }
945 type RT1 struct {
946 c float
947 b string
948 a int
949 notSet string
950 }
951
952 func TestReorderedFields(t *testing.T) {
953 var rt0 RT0
954 rt0.a = 17
955 rt0.b = "hello"
956 rt0.c = 3.14159
957 b := new(bytes.Buffer)
958 NewEncoder(b).Encode(rt0)
959 dec := NewDecoder(b)
960 var rt1 RT1
961 // Wire type is RT0, local type is RT1.
962 err := dec.Decode(&rt1)
963 if err != nil {
964 t.Error("decode error:", err)
965 }
966 if rt0.a != rt1.a || rt0.b != rt1.b || rt0.c != rt1.c {
967 t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
968 }
969 }
970
971 // Like an RT0 but with fields we'll ignore on the decode side.
972 type IT0 struct {
973 a int64
974 b string
975 ignore_d []int
976 ignore_e [3]float
977 ignore_f bool
978 ignore_g string
979 ignore_h []byte
980 ignore_i *RT1
981 ignore_m map[string]int
982 c float
983 }
984
985 func TestIgnoredFields(t *testing.T) {
986 var it0 IT0
987 it0.a = 17
988 it0.b = "hello"
989 it0.c = 3.14159
990 it0.ignore_d = []int{1, 2, 3}
991 it0.ignore_e[0] = 1.0
992 it0.ignore_e[1] = 2.0
993 it0.ignore_e[2] = 3.0
994 it0.ignore_f = true
995 it0.ignore_g = "pay no attention"
996 it0.ignore_h = []byte("to the curtain")
997 it0.ignore_i = &RT1{3.1, "hi", 7, "hello"}
998 it0.ignore_m = map[string]int{"one": 1, "two": 2}
999
1000 b := new(bytes.Buffer)
1001 NewEncoder(b).Encode(it0)
1002 dec := NewDecoder(b)
1003 var rt1 RT1
1004 // Wire type is IT0, local type is RT1.
1005 err := dec.Decode(&rt1)
1006 if err != nil {
1007 t.Error("error: ", err)
1008 }
1009 if int(it0.a) != rt1.a || it0.b != rt1.b || it0.c != rt1.c {
1010 t.Errorf("rt1->rt0: expected %v; got %v", it0, rt1)
1011 }
1012 }
1013
1014 type Bad0 struct {
1015 ch chan int
1016 c float
1017 }
1018
1019 var nilEncoder *Encoder
1020
1021 func TestInvalidField(t *testing.T) {
1022 var bad0 Bad0
1023 bad0.ch = make(chan int)
1024 b := new(bytes.Buffer)
1025 err := nilEncoder.encode(b, reflect.NewValue(&bad0))
1026 if err == nil {
1027 t.Error("expected error; got none")
1028 } else if strings.Index(err.String(), "type") < 0 {
1029 t.Error("expected type error; got", err)
1030 }
1031 }
1032
1033 type Indirect struct {
1034 a ***[3]int
1035 s ***[]int
1036 m ****map[string]int
1037 }
1038
1039 type Direct struct {
1040 a [3]int
1041 s []int
1042 m map[string]int
1043 }
1044
1045 func TestIndirectSliceMapArray(t *testing.T) {
1046 // Marshal indirect, unmarshal to direct.
1047 i := new(Indirect)
1048 i.a = new(**[3]int)
1049 *i.a = new(*[3]int)
1050 **i.a = new([3]int)
1051 ***i.a = [3]int{1, 2, 3}
1052 i.s = new(**[]int)
1053 *i.s = new(*[]int)
1054 **i.s = new([]int)
1055 ***i.s = []int{4, 5, 6}
1056 i.m = new(***map[string]int)
1057 *i.m = new(**map[string]int)
1058 **i.m = new(*map[string]int)
1059 ***i.m = new(map[string]int)
1060 ****i.m = map[string]int{"one": 1, "two": 2, "three": 3}
1061 b := new(bytes.Buffer)
1062 NewEncoder(b).Encode(i)
1063 dec := NewDecoder(b)
1064 var d Direct
1065 err := dec.Decode(&d)
1066 if err != nil {
1067 t.Error("error: ", err)
1068 }
1069 if len(d.a) != 3 || d.a[0] != 1 || d.a[1] != 2 || d.a[2] != 3 {
1070 t.Errorf("indirect to direct: d.a is %v not %v", d.a, ***i.a)
1071 }
1072 if len(d.s) != 3 || d.s[0] != 4 || d.s[1] != 5 || d.s[2] != 6 {
1073 t.Errorf("indirect to direct: d.s is %v not %v", d.s, ***i.s)
1074 }
1075 if len(d.m) != 3 || d.m["one"] != 1 || d.m["two"] != 2 || d.m["three"] != 3 {
1076 t.Errorf("indirect to direct: d.m is %v not %v", d.m, ***i.m)
1077 }
1078 // Marshal direct, unmarshal to indirect.
1079 d.a = [3]int{11, 22, 33}
1080 d.s = []int{44, 55, 66}
1081 d.m = map[string]int{"four": 4, "five": 5, "six": 6}
1082 i = new(Indirect)
1083 b.Reset()
1084 NewEncoder(b).Encode(d)
1085 dec = NewDecoder(b)
1086 err = dec.Decode(&i)
1087 if err != nil {
1088 t.Error("error: ", err)
1089 }
1090 if len(***i.a) != 3 || (***i.a)[0] != 11 || (***i.a)[1] != 22 || (***i.a)[2] != 33 {
1091 t.Errorf("direct to indirect: ***i.a is %v not %v", ***i.a, d.a)
1092 }
1093 if len(***i.s) != 3 || (***i.s)[0] != 44 || (***i.s)[1] != 55 || (***i.s)[2] != 66 {
1094 t.Errorf("direct to indirect: ***i.s is %v not %v", ***i.s, ***i.s)
1095 }
1096 if len(****i.m) != 3 || (****i.m)["four"] != 4 || (****i.m)["five"] != 5 || (****i.m)["six"] != 6 {
1097 t.Errorf("direct to indirect: ****i.m is %v not %v", ****i.m, d.m)
1098 }
1099 }
1100
1101 // An interface with several implementations
1102 type Squarer interface {
1103 Square() int
1104 }
1105
1106 type Int int
1107
1108 func (i Int) Square() int {
1109 return int(i * i)
1110 }
1111
1112 type Float float
1113
1114 func (f Float) Square() int {
1115 return int(f * f)
1116 }
1117
1118 type Vector []int
1119
1120 func (v Vector) Square() int {
1121 sum := 0
1122 for _, x := range v {
1123 sum += x * x
1124 }
1125 return sum
1126 }
1127
1128 type Point struct {
1129 a, b int
1130 }
1131
1132 func (p Point) Square() int {
1133 return p.a*p.a + p.b*p.b
1134 }
1135
1136 // A struct with interfaces in it.
1137 type InterfaceItem struct {
1138 i int
1139 sq1, sq2, sq3 Squarer
1140 f float
1141 sq []Squarer
1142 }
1143
1144 // The same struct without interfaces
1145 type NoInterfaceItem struct {
1146 i int
1147 f float
1148 }
1149
1150 func TestInterface(t *testing.T) {
1151 iVal := Int(3)
1152 fVal := Float(5)
1153 // Sending a Vector will require that the receiver define a type in the middle of
1154 // receiving the value for item2.
1155 vVal := Vector{1, 2, 3}
1156 b := new(bytes.Buffer)
1157 item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1158 // Register the types.
1159 Register(Int(0))
1160 Register(Float(0))
1161 Register(Vector{})
1162 err := NewEncoder(b).Encode(item1)
1163 if err != nil {
1164 t.Error("expected no encode error; got", err)
1165 }
1166
1167 item2 := InterfaceItem{}
1168 err = NewDecoder(b).Decode(&item2)
1169 if err != nil {
1170 t.Fatal("decode:", err)
1171 }
1172 if item2.i != item1.i {
1173 t.Error("normal int did not decode correctly")
1174 }
1175 if item2.sq1 == nil || item2.sq1.Square() != iVal.Square() {
1176 t.Error("Int did not decode correctly")
1177 }
1178 if item2.sq2 == nil || item2.sq2.Square() != fVal.Square() {
1179 t.Error("Float did not decode correctly")
1180 }
1181 if item2.sq3 == nil || item2.sq3.Square() != vVal.Square() {
1182 t.Error("Vector did not decode correctly")
1183 }
1184 if item2.f != item1.f {
1185 t.Error("normal float did not decode correctly")
1186 }
1187 // Now check that we received a slice of Squarers correctly, including a nil element
1188 if len(item1.sq) != len(item2.sq) {
1189 t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.sq), len(item1.sq))
1190 }
1191 for i, v1 := range item1.sq {
1192 v2 := item2.sq[i]
1193 if v1 == nil || v2 == nil {
1194 if v1 != nil || v2 != nil {
1195 t.Errorf("item %d inconsistent nils", i)
1196 }
1197 continue
1198 if v1.Square() != v2.Square() {
1199 t.Errorf("item %d inconsistent values: %v %v", v1, v2)
1200 }
1201 }
1202 }
1203
1204 }
1205
1206 // A struct with all basic types, stored in interfaces.
1207 type BasicInterfaceItem struct {
1208 Int, Int8, Int16, Int32, Int64 interface{}
1209 Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1210 Float, Float32, Float64 interface{}
1211 Complex, Complex64, Complex128 interface{}
1212 Bool interface{}
1213 String interface{}
1214 Bytes interface{}
1215 }
1216
1217 func TestInterfaceBasic(t *testing.T) {
1218 b := new(bytes.Buffer)
1219 item1 := &BasicInterfaceItem{
1220 int(1), int8(1), int16(1), int32(1), int64(1),
1221 uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1222 float(1), float32(1), float64(1),
1223 complex(0i), complex64(0i), complex128(0i),
1224 true,
1225 "hello",
1226 []byte("sailor"),
1227 }
1228 err := NewEncoder(b).Encode(item1)
1229 if err != nil {
1230 t.Error("expected no encode error; got", err)
1231 }
1232
1233 item2 := &BasicInterfaceItem{}
1234 err = NewDecoder(b).Decode(&item2)
1235 if err != nil {
1236 t.Fatal("decode:", err)
1237 }
1238 if !reflect.DeepEqual(item1, item2) {
1239 t.Errorf("encode expected %v got %v", item1, item2)
1240 }
1241 // Hand check a couple for correct types.
1242 if v, ok := item2.Bool.(bool); !ok || !v {
1243 t.Error("boolean should be true")
1244 }
1245 if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1246 t.Errorf("string should be %v is %v", item1.String, v)
1247 }
1248 }
1249
1250 type String string
1251
1252 type PtrInterfaceItem struct {
1253 str interface{} // basic
1254 Str interface{} // derived
1255 }
1256
1257 // We'll send pointers; should receive values.
1258 // Also check that we can register T but send *T.
1259 func TestInterfacePointer(t *testing.T) {
1260 b := new(bytes.Buffer)
1261 str1 := "howdy"
1262 str2 := String("kiddo")
1263 item1 := &PtrInterfaceItem{
1264 &str1,
1265 &str2,
1266 }
1267 // Register the type.
1268 Register(str2)
1269 err := NewEncoder(b).Encode(item1)
1270 if err != nil {
1271 t.Error("expected no encode error; got", err)
1272 }
1273
1274 item2 := &PtrInterfaceItem{}
1275 err = NewDecoder(b).Decode(&item2)
1276 if err != nil {
1277 t.Fatal("decode:", err)
1278 }
1279 // Hand test for correct types and values.
1280 if v, ok := item2.str.(string); !ok || v != str1 {
1281 t.Errorf("basic string failed: %q should be %q", v, str1)
1282 }
1283 if v, ok := item2.Str.(String); !ok || v != str2 {
1284 t.Errorf("derived type String failed: %q should be %q", v, str2)
1285 }
1286 }
1287
1288 func TestIgnoreInterface(t *testing.T) {
1289 iVal := Int(3)
1290 fVal := Float(5)
1291 // Sending a Point will require that the receiver define a type in the middle of
1292 // receiving the value for item2.
1293 pVal := Point{2, 3}
1294 b := new(bytes.Buffer)
1295 item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1296 // Register the types.
1297 Register(Int(0))
1298 Register(Float(0))
1299 Register(Point{})
1300 err := NewEncoder(b).Encode(item1)
1301 if err != nil {
1302 t.Error("expected no encode error; got", err)
1303 }
1304
1305 item2 := NoInterfaceItem{}
1306 err = NewDecoder(b).Decode(&item2)
1307 if err != nil {
1308 t.Fatal("decode:", err)
1309 }
1310 if item2.i != item1.i {
1311 t.Error("normal int did not decode correctly")
1312 }
1313 if item2.f != item2.f {
1314 t.Error("normal float did not decode correctly")
1315 }
1316 }
1317
1318 // A type that won't be defined in the gob until we send it in an interface value.
1319 type OnTheFly struct {
1320 a int
1321 }
1322
1323 type DT struct {
1324 // X OnTheFly
1325 a int
1326 b string
1327 c float
1328 i interface{}
1329 j interface{}
1330 i_nil interface{}
1331 m map[string]int
1332 r [3]int
1333 s []string
1334 }
1335
1336 func TestDebug(t *testing.T) {
1337 if debugFunc == nil {
1338 return
1339 }
1340 Register(OnTheFly{})
1341 var dt DT
1342 dt.a = 17
1343 dt.b = "hello"
1344 dt.c = 3.14159
1345 dt.i = 271828
1346 dt.j = OnTheFly{3}
1347 dt.i_nil = nil
1348 dt.m = map[string]int{"one": 1, "two": 2}
1349 dt.r = [3]int{11, 22, 33}
1350 dt.s = []string{"hi", "joe"}
1351 b := new(bytes.Buffer)
1352 err := NewEncoder(b).Encode(dt)
1353 if err != nil {
1354 t.Fatal("encode:", err)
1355 }
1356 debugBuffer := bytes.NewBuffer(b.Bytes())
1357 dt2 := &DT{}
1358 err = NewDecoder(b).Decode(&dt2)
1359 if err != nil {
1360 t.Error("decode:", err)
1361 }
1362 debugFunc(debugBuffer)
1363 }