OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [encoding/] [gob/] [codec_test.go] - Blame information for rev 760

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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
        "errors"
10
        "math"
11
        "math/rand"
12
        "reflect"
13
        "strings"
14
        "testing"
15
        "time"
16
        "unsafe"
17
)
18
 
19
// Guarantee encoding format by comparing some encodings to hand-written values
20
type EncodeT struct {
21
        x uint64
22
        b []byte
23
}
24
 
25
var encodeT = []EncodeT{
26
        {0x00, []byte{0x00}},
27
        {0x0F, []byte{0x0F}},
28
        {0xFF, []byte{0xFF, 0xFF}},
29
        {0xFFFF, []byte{0xFE, 0xFF, 0xFF}},
30
        {0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}},
31
        {0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}},
32
        {0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
33
        {0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
34
        {0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
35
        {0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
36
        {0x1111, []byte{0xFE, 0x11, 0x11}},
37
        {0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
38
        {0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}},
39
        {1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
40
}
41
 
42
// testError is meant to be used as a deferred function to turn a panic(gobError) into a
43
// plain test.Error call.
44
func testError(t *testing.T) {
45
        if e := recover(); e != nil {
46
                t.Error(e.(gobError).err) // Will re-panic if not one of our errors, such as a runtime error.
47
        }
48
        return
49
}
50
 
51
// Test basic encode/decode routines for unsigned integers
52
func TestUintCodec(t *testing.T) {
53
        defer testError(t)
54
        b := new(bytes.Buffer)
55
        encState := newEncoderState(b)
56
        for _, tt := range encodeT {
57
                b.Reset()
58
                encState.encodeUint(tt.x)
59
                if !bytes.Equal(tt.b, b.Bytes()) {
60
                        t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
61
                }
62
        }
63
        decState := newDecodeState(b)
64
        for u := uint64(0); ; u = (u + 1) * 7 {
65
                b.Reset()
66
                encState.encodeUint(u)
67
                v := decState.decodeUint()
68
                if u != v {
69
                        t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
70
                }
71
                if u&(1<<63) != 0 {
72
                        break
73
                }
74
        }
75
}
76
 
77
func verifyInt(i int64, t *testing.T) {
78
        defer testError(t)
79
        var b = new(bytes.Buffer)
80
        encState := newEncoderState(b)
81
        encState.encodeInt(i)
82
        decState := newDecodeState(b)
83
        decState.buf = make([]byte, 8)
84
        j := decState.decodeInt()
85
        if i != j {
86
                t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
87
        }
88
}
89
 
90
// Test basic encode/decode routines for signed integers
91
func TestIntCodec(t *testing.T) {
92
        for u := uint64(0); ; u = (u + 1) * 7 {
93
                // Do positive and negative values
94
                i := int64(u)
95
                verifyInt(i, t)
96
                verifyInt(-i, t)
97
                verifyInt(^i, t)
98
                if u&(1<<63) != 0 {
99
                        break
100
                }
101
        }
102
        verifyInt(-1<<63, t) // a tricky case
103
}
104
 
105
// The result of encoding a true boolean with field number 7
106
var boolResult = []byte{0x07, 0x01}
107
 
108
// The result of encoding a number 17 with field number 7
109
var signedResult = []byte{0x07, 2 * 17}
110
var unsignedResult = []byte{0x07, 17}
111
var floatResult = []byte{0x07, 0xFE, 0x31, 0x40}
112
 
113
// The result of encoding a number 17+19i with field number 7
114
var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
115
 
116
// The result of encoding "hello" with field number 7
117
var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
118
 
119
func newDecodeState(buf *bytes.Buffer) *decoderState {
120
        d := new(decoderState)
121
        d.b = buf
122
        d.buf = make([]byte, uint64Size)
123
        return d
124
}
125
 
126
func newEncoderState(b *bytes.Buffer) *encoderState {
127
        b.Reset()
128
        state := &encoderState{enc: nil, b: b}
129
        state.fieldnum = -1
130
        return state
131
}
132
 
133
// Test instruction execution for encoding.
134
// Do not run the machine yet; instead do individual instructions crafted by hand.
135
func TestScalarEncInstructions(t *testing.T) {
136
        var b = new(bytes.Buffer)
137
 
138
        // bool
139
        {
140
                data := struct{ a bool }{true}
141
                instr := &encInstr{encBool, 6, 0, 0}
142
                state := newEncoderState(b)
143
                instr.op(instr, state, unsafe.Pointer(&data))
144
                if !bytes.Equal(boolResult, b.Bytes()) {
145
                        t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
146
                }
147
        }
148
 
149
        // int
150
        {
151
                b.Reset()
152
                data := struct{ a int }{17}
153
                instr := &encInstr{encInt, 6, 0, 0}
154
                state := newEncoderState(b)
155
                instr.op(instr, state, unsafe.Pointer(&data))
156
                if !bytes.Equal(signedResult, b.Bytes()) {
157
                        t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
158
                }
159
        }
160
 
161
        // uint
162
        {
163
                b.Reset()
164
                data := struct{ a uint }{17}
165
                instr := &encInstr{encUint, 6, 0, 0}
166
                state := newEncoderState(b)
167
                instr.op(instr, state, unsafe.Pointer(&data))
168
                if !bytes.Equal(unsignedResult, b.Bytes()) {
169
                        t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
170
                }
171
        }
172
 
173
        // int8
174
        {
175
                b.Reset()
176
                data := struct{ a int8 }{17}
177
                instr := &encInstr{encInt8, 6, 0, 0}
178
                state := newEncoderState(b)
179
                instr.op(instr, state, unsafe.Pointer(&data))
180
                if !bytes.Equal(signedResult, b.Bytes()) {
181
                        t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
182
                }
183
        }
184
 
185
        // uint8
186
        {
187
                b.Reset()
188
                data := struct{ a uint8 }{17}
189
                instr := &encInstr{encUint8, 6, 0, 0}
190
                state := newEncoderState(b)
191
                instr.op(instr, state, unsafe.Pointer(&data))
192
                if !bytes.Equal(unsignedResult, b.Bytes()) {
193
                        t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
194
                }
195
        }
196
 
197
        // int16
198
        {
199
                b.Reset()
200
                data := struct{ a int16 }{17}
201
                instr := &encInstr{encInt16, 6, 0, 0}
202
                state := newEncoderState(b)
203
                instr.op(instr, state, unsafe.Pointer(&data))
204
                if !bytes.Equal(signedResult, b.Bytes()) {
205
                        t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
206
                }
207
        }
208
 
209
        // uint16
210
        {
211
                b.Reset()
212
                data := struct{ a uint16 }{17}
213
                instr := &encInstr{encUint16, 6, 0, 0}
214
                state := newEncoderState(b)
215
                instr.op(instr, state, unsafe.Pointer(&data))
216
                if !bytes.Equal(unsignedResult, b.Bytes()) {
217
                        t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
218
                }
219
        }
220
 
221
        // int32
222
        {
223
                b.Reset()
224
                data := struct{ a int32 }{17}
225
                instr := &encInstr{encInt32, 6, 0, 0}
226
                state := newEncoderState(b)
227
                instr.op(instr, state, unsafe.Pointer(&data))
228
                if !bytes.Equal(signedResult, b.Bytes()) {
229
                        t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
230
                }
231
        }
232
 
233
        // uint32
234
        {
235
                b.Reset()
236
                data := struct{ a uint32 }{17}
237
                instr := &encInstr{encUint32, 6, 0, 0}
238
                state := newEncoderState(b)
239
                instr.op(instr, state, unsafe.Pointer(&data))
240
                if !bytes.Equal(unsignedResult, b.Bytes()) {
241
                        t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
242
                }
243
        }
244
 
245
        // int64
246
        {
247
                b.Reset()
248
                data := struct{ a int64 }{17}
249
                instr := &encInstr{encInt64, 6, 0, 0}
250
                state := newEncoderState(b)
251
                instr.op(instr, state, unsafe.Pointer(&data))
252
                if !bytes.Equal(signedResult, b.Bytes()) {
253
                        t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
254
                }
255
        }
256
 
257
        // uint64
258
        {
259
                b.Reset()
260
                data := struct{ a uint64 }{17}
261
                instr := &encInstr{encUint64, 6, 0, 0}
262
                state := newEncoderState(b)
263
                instr.op(instr, state, unsafe.Pointer(&data))
264
                if !bytes.Equal(unsignedResult, b.Bytes()) {
265
                        t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, 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 *decoderState, t *testing.T, p unsafe.Pointer) {
319
        defer testError(t)
320
        v := int(state.decodeUint())
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) *decoderState {
329
        b := bytes.NewBuffer(data)
330
        state := newDecodeState(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 := errors.New("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{decOpTable[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{decOpTable[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{decOpTable[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
        // float32
496
        {
497
                var data struct {
498
                        a float32
499
                }
500
                instr := &decInstr{decFloat32, 6, 0, 0, ovfl}
501
                state := newDecodeStateFromData(floatResult)
502
                execDec("float32", instr, state, t, unsafe.Pointer(&data))
503
                if data.a != 17 {
504
                        t.Errorf("float32 a = %v not 17", data.a)
505
                }
506
        }
507
 
508
        // float64
509
        {
510
                var data struct {
511
                        a float64
512
                }
513
                instr := &decInstr{decFloat64, 6, 0, 0, ovfl}
514
                state := newDecodeStateFromData(floatResult)
515
                execDec("float64", instr, state, t, unsafe.Pointer(&data))
516
                if data.a != 17 {
517
                        t.Errorf("float64 a = %v not 17", data.a)
518
                }
519
        }
520
 
521
        // complex64
522
        {
523
                var data struct {
524
                        a complex64
525
                }
526
                instr := &decInstr{decOpTable[reflect.Complex64], 6, 0, 0, ovfl}
527
                state := newDecodeStateFromData(complexResult)
528
                execDec("complex", instr, state, t, unsafe.Pointer(&data))
529
                if data.a != 17+19i {
530
                        t.Errorf("complex a = %v not 17+19i", data.a)
531
                }
532
        }
533
 
534
        // complex128
535
        {
536
                var data struct {
537
                        a complex128
538
                }
539
                instr := &decInstr{decOpTable[reflect.Complex128], 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
        // bytes == []uint8
548
        {
549
                var data struct {
550
                        a []byte
551
                }
552
                instr := &decInstr{decUint8Slice, 6, 0, 0, ovfl}
553
                state := newDecodeStateFromData(bytesResult)
554
                execDec("bytes", instr, state, t, unsafe.Pointer(&data))
555
                if string(data.a) != "hello" {
556
                        t.Errorf(`bytes a = %q not "hello"`, string(data.a))
557
                }
558
        }
559
 
560
        // string
561
        {
562
                var data struct {
563
                        a string
564
                }
565
                instr := &decInstr{decString, 6, 0, 0, ovfl}
566
                state := newDecodeStateFromData(bytesResult)
567
                execDec("bytes", instr, state, t, unsafe.Pointer(&data))
568
                if data.a != "hello" {
569
                        t.Errorf(`bytes a = %q not "hello"`, data.a)
570
                }
571
        }
572
}
573
 
574
func TestEndToEnd(t *testing.T) {
575
        type T2 struct {
576
                T string
577
        }
578
        s1 := "string1"
579
        s2 := "string2"
580
        type T1 struct {
581
                A, B, C  int
582
                M        map[string]*float64
583
                EmptyMap map[string]int // to check that we receive a non-nil map.
584
                N        *[3]float64
585
                Strs     *[2]string
586
                Int64s   *[]int64
587
                RI       complex64
588
                S        string
589
                Y        []byte
590
                T        *T2
591
        }
592
        pi := 3.14159
593
        e := 2.71828
594
        t1 := &T1{
595
                A:        17,
596
                B:        18,
597
                C:        -5,
598
                M:        map[string]*float64{"pi": &pi, "e": &e},
599
                EmptyMap: make(map[string]int),
600
                N:        &[3]float64{1.5, 2.5, 3.5},
601
                Strs:     &[2]string{s1, s2},
602
                Int64s:   &[]int64{77, 89, 123412342134},
603
                RI:       17 - 23i,
604
                S:        "Now is the time",
605
                Y:        []byte("hello, sailor"),
606
                T:        &T2{"this is T2"},
607
        }
608
        b := new(bytes.Buffer)
609
        err := NewEncoder(b).Encode(t1)
610
        if err != nil {
611
                t.Error("encode:", err)
612
        }
613
        var _t1 T1
614
        err = NewDecoder(b).Decode(&_t1)
615
        if err != nil {
616
                t.Fatal("decode:", err)
617
        }
618
        if !reflect.DeepEqual(t1, &_t1) {
619
                t.Errorf("encode expected %v got %v", *t1, _t1)
620
        }
621
        // Be absolutely sure the received map is non-nil.
622
        if t1.EmptyMap == nil {
623
                t.Errorf("nil map sent")
624
        }
625
        if _t1.EmptyMap == nil {
626
                t.Errorf("nil map received")
627
        }
628
}
629
 
630
func TestOverflow(t *testing.T) {
631
        type inputT struct {
632
                Maxi int64
633
                Mini int64
634
                Maxu uint64
635
                Maxf float64
636
                Minf float64
637
                Maxc complex128
638
                Minc complex128
639
        }
640
        var it inputT
641
        var err error
642
        b := new(bytes.Buffer)
643
        enc := NewEncoder(b)
644
        dec := NewDecoder(b)
645
 
646
        // int8
647
        b.Reset()
648
        it = inputT{
649
                Maxi: math.MaxInt8 + 1,
650
        }
651
        type outi8 struct {
652
                Maxi int8
653
                Mini int8
654
        }
655
        var o1 outi8
656
        enc.Encode(it)
657
        err = dec.Decode(&o1)
658
        if err == nil || err.Error() != `value for "Maxi" out of range` {
659
                t.Error("wrong overflow error for int8:", err)
660
        }
661
        it = inputT{
662
                Mini: math.MinInt8 - 1,
663
        }
664
        b.Reset()
665
        enc.Encode(it)
666
        err = dec.Decode(&o1)
667
        if err == nil || err.Error() != `value for "Mini" out of range` {
668
                t.Error("wrong underflow error for int8:", err)
669
        }
670
 
671
        // int16
672
        b.Reset()
673
        it = inputT{
674
                Maxi: math.MaxInt16 + 1,
675
        }
676
        type outi16 struct {
677
                Maxi int16
678
                Mini int16
679
        }
680
        var o2 outi16
681
        enc.Encode(it)
682
        err = dec.Decode(&o2)
683
        if err == nil || err.Error() != `value for "Maxi" out of range` {
684
                t.Error("wrong overflow error for int16:", err)
685
        }
686
        it = inputT{
687
                Mini: math.MinInt16 - 1,
688
        }
689
        b.Reset()
690
        enc.Encode(it)
691
        err = dec.Decode(&o2)
692
        if err == nil || err.Error() != `value for "Mini" out of range` {
693
                t.Error("wrong underflow error for int16:", err)
694
        }
695
 
696
        // int32
697
        b.Reset()
698
        it = inputT{
699
                Maxi: math.MaxInt32 + 1,
700
        }
701
        type outi32 struct {
702
                Maxi int32
703
                Mini int32
704
        }
705
        var o3 outi32
706
        enc.Encode(it)
707
        err = dec.Decode(&o3)
708
        if err == nil || err.Error() != `value for "Maxi" out of range` {
709
                t.Error("wrong overflow error for int32:", err)
710
        }
711
        it = inputT{
712
                Mini: math.MinInt32 - 1,
713
        }
714
        b.Reset()
715
        enc.Encode(it)
716
        err = dec.Decode(&o3)
717
        if err == nil || err.Error() != `value for "Mini" out of range` {
718
                t.Error("wrong underflow error for int32:", err)
719
        }
720
 
721
        // uint8
722
        b.Reset()
723
        it = inputT{
724
                Maxu: math.MaxUint8 + 1,
725
        }
726
        type outu8 struct {
727
                Maxu uint8
728
        }
729
        var o4 outu8
730
        enc.Encode(it)
731
        err = dec.Decode(&o4)
732
        if err == nil || err.Error() != `value for "Maxu" out of range` {
733
                t.Error("wrong overflow error for uint8:", err)
734
        }
735
 
736
        // uint16
737
        b.Reset()
738
        it = inputT{
739
                Maxu: math.MaxUint16 + 1,
740
        }
741
        type outu16 struct {
742
                Maxu uint16
743
        }
744
        var o5 outu16
745
        enc.Encode(it)
746
        err = dec.Decode(&o5)
747
        if err == nil || err.Error() != `value for "Maxu" out of range` {
748
                t.Error("wrong overflow error for uint16:", err)
749
        }
750
 
751
        // uint32
752
        b.Reset()
753
        it = inputT{
754
                Maxu: math.MaxUint32 + 1,
755
        }
756
        type outu32 struct {
757
                Maxu uint32
758
        }
759
        var o6 outu32
760
        enc.Encode(it)
761
        err = dec.Decode(&o6)
762
        if err == nil || err.Error() != `value for "Maxu" out of range` {
763
                t.Error("wrong overflow error for uint32:", err)
764
        }
765
 
766
        // float32
767
        b.Reset()
768
        it = inputT{
769
                Maxf: math.MaxFloat32 * 2,
770
        }
771
        type outf32 struct {
772
                Maxf float32
773
                Minf float32
774
        }
775
        var o7 outf32
776
        enc.Encode(it)
777
        err = dec.Decode(&o7)
778
        if err == nil || err.Error() != `value for "Maxf" out of range` {
779
                t.Error("wrong overflow error for float32:", err)
780
        }
781
 
782
        // complex64
783
        b.Reset()
784
        it = inputT{
785
                Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
786
        }
787
        type outc64 struct {
788
                Maxc complex64
789
                Minc complex64
790
        }
791
        var o8 outc64
792
        enc.Encode(it)
793
        err = dec.Decode(&o8)
794
        if err == nil || err.Error() != `value for "Maxc" out of range` {
795
                t.Error("wrong overflow error for complex64:", err)
796
        }
797
}
798
 
799
func TestNesting(t *testing.T) {
800
        type RT struct {
801
                A    string
802
                Next *RT
803
        }
804
        rt := new(RT)
805
        rt.A = "level1"
806
        rt.Next = new(RT)
807
        rt.Next.A = "level2"
808
        b := new(bytes.Buffer)
809
        NewEncoder(b).Encode(rt)
810
        var drt RT
811
        dec := NewDecoder(b)
812
        err := dec.Decode(&drt)
813
        if err != nil {
814
                t.Fatal("decoder error:", err)
815
        }
816
        if drt.A != rt.A {
817
                t.Errorf("nesting: encode expected %v got %v", *rt, drt)
818
        }
819
        if drt.Next == nil {
820
                t.Errorf("nesting: recursion failed")
821
        }
822
        if drt.Next.A != rt.Next.A {
823
                t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
824
        }
825
}
826
 
827
// These three structures have the same data with different indirections
828
type T0 struct {
829
        A int
830
        B int
831
        C int
832
        D int
833
}
834
type T1 struct {
835
        A int
836
        B *int
837
        C **int
838
        D ***int
839
}
840
type T2 struct {
841
        A ***int
842
        B **int
843
        C *int
844
        D int
845
}
846
 
847
func TestAutoIndirection(t *testing.T) {
848
        // First transfer t1 into t0
849
        var t1 T1
850
        t1.A = 17
851
        t1.B = new(int)
852
        *t1.B = 177
853
        t1.C = new(*int)
854
        *t1.C = new(int)
855
        **t1.C = 1777
856
        t1.D = new(**int)
857
        *t1.D = new(*int)
858
        **t1.D = new(int)
859
        ***t1.D = 17777
860
        b := new(bytes.Buffer)
861
        enc := NewEncoder(b)
862
        enc.Encode(t1)
863
        dec := NewDecoder(b)
864
        var t0 T0
865
        dec.Decode(&t0)
866
        if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
867
                t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
868
        }
869
 
870
        // Now transfer t2 into t0
871
        var t2 T2
872
        t2.D = 17777
873
        t2.C = new(int)
874
        *t2.C = 1777
875
        t2.B = new(*int)
876
        *t2.B = new(int)
877
        **t2.B = 177
878
        t2.A = new(**int)
879
        *t2.A = new(*int)
880
        **t2.A = new(int)
881
        ***t2.A = 17
882
        b.Reset()
883
        enc.Encode(t2)
884
        t0 = T0{}
885
        dec.Decode(&t0)
886
        if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
887
                t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
888
        }
889
 
890
        // Now transfer t0 into t1
891
        t0 = T0{17, 177, 1777, 17777}
892
        b.Reset()
893
        enc.Encode(t0)
894
        t1 = T1{}
895
        dec.Decode(&t1)
896
        if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
897
                t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
898
        }
899
 
900
        // Now transfer t0 into t2
901
        b.Reset()
902
        enc.Encode(t0)
903
        t2 = T2{}
904
        dec.Decode(&t2)
905
        if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
906
                t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
907
        }
908
 
909
        // Now do t2 again but without pre-allocated pointers.
910
        b.Reset()
911
        enc.Encode(t0)
912
        ***t2.A = 0
913
        **t2.B = 0
914
        *t2.C = 0
915
        t2.D = 0
916
        dec.Decode(&t2)
917
        if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
918
                t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
919
        }
920
}
921
 
922
type RT0 struct {
923
        A int
924
        B string
925
        C float64
926
}
927
type RT1 struct {
928
        C      float64
929
        B      string
930
        A      int
931
        NotSet string
932
}
933
 
934
func TestReorderedFields(t *testing.T) {
935
        var rt0 RT0
936
        rt0.A = 17
937
        rt0.B = "hello"
938
        rt0.C = 3.14159
939
        b := new(bytes.Buffer)
940
        NewEncoder(b).Encode(rt0)
941
        dec := NewDecoder(b)
942
        var rt1 RT1
943
        // Wire type is RT0, local type is RT1.
944
        err := dec.Decode(&rt1)
945
        if err != nil {
946
                t.Fatal("decode error:", err)
947
        }
948
        if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
949
                t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
950
        }
951
}
952
 
953
// Like an RT0 but with fields we'll ignore on the decode side.
954
type IT0 struct {
955
        A        int64
956
        B        string
957
        Ignore_d []int
958
        Ignore_e [3]float64
959
        Ignore_f bool
960
        Ignore_g string
961
        Ignore_h []byte
962
        Ignore_i *RT1
963
        Ignore_m map[string]int
964
        C        float64
965
}
966
 
967
func TestIgnoredFields(t *testing.T) {
968
        var it0 IT0
969
        it0.A = 17
970
        it0.B = "hello"
971
        it0.C = 3.14159
972
        it0.Ignore_d = []int{1, 2, 3}
973
        it0.Ignore_e[0] = 1.0
974
        it0.Ignore_e[1] = 2.0
975
        it0.Ignore_e[2] = 3.0
976
        it0.Ignore_f = true
977
        it0.Ignore_g = "pay no attention"
978
        it0.Ignore_h = []byte("to the curtain")
979
        it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
980
        it0.Ignore_m = map[string]int{"one": 1, "two": 2}
981
 
982
        b := new(bytes.Buffer)
983
        NewEncoder(b).Encode(it0)
984
        dec := NewDecoder(b)
985
        var rt1 RT1
986
        // Wire type is IT0, local type is RT1.
987
        err := dec.Decode(&rt1)
988
        if err != nil {
989
                t.Error("error: ", err)
990
        }
991
        if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
992
                t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
993
        }
994
}
995
 
996
func TestBadRecursiveType(t *testing.T) {
997
        type Rec ***Rec
998
        var rec Rec
999
        b := new(bytes.Buffer)
1000
        err := NewEncoder(b).Encode(&rec)
1001
        if err == nil {
1002
                t.Error("expected error; got none")
1003
        } else if strings.Index(err.Error(), "recursive") < 0 {
1004
                t.Error("expected recursive type error; got", err)
1005
        }
1006
        // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
1007
}
1008
 
1009
type Bad0 struct {
1010
        CH chan int
1011
        C  float64
1012
}
1013
 
1014
func TestInvalidField(t *testing.T) {
1015
        var bad0 Bad0
1016
        bad0.CH = make(chan int)
1017
        b := new(bytes.Buffer)
1018
        dummyEncoder := new(Encoder) // sufficient for this purpose.
1019
        dummyEncoder.encode(b, reflect.ValueOf(&bad0), userType(reflect.TypeOf(&bad0)))
1020
        if err := dummyEncoder.err; err == nil {
1021
                t.Error("expected error; got none")
1022
        } else if strings.Index(err.Error(), "type") < 0 {
1023
                t.Error("expected type error; got", err)
1024
        }
1025
}
1026
 
1027
type Indirect struct {
1028
        A ***[3]int
1029
        S ***[]int
1030
        M ****map[string]int
1031
}
1032
 
1033
type Direct struct {
1034
        A [3]int
1035
        S []int
1036
        M map[string]int
1037
}
1038
 
1039
func TestIndirectSliceMapArray(t *testing.T) {
1040
        // Marshal indirect, unmarshal to direct.
1041
        i := new(Indirect)
1042
        i.A = new(**[3]int)
1043
        *i.A = new(*[3]int)
1044
        **i.A = new([3]int)
1045
        ***i.A = [3]int{1, 2, 3}
1046
        i.S = new(**[]int)
1047
        *i.S = new(*[]int)
1048
        **i.S = new([]int)
1049
        ***i.S = []int{4, 5, 6}
1050
        i.M = new(***map[string]int)
1051
        *i.M = new(**map[string]int)
1052
        **i.M = new(*map[string]int)
1053
        ***i.M = new(map[string]int)
1054
        ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
1055
        b := new(bytes.Buffer)
1056
        NewEncoder(b).Encode(i)
1057
        dec := NewDecoder(b)
1058
        var d Direct
1059
        err := dec.Decode(&d)
1060
        if err != nil {
1061
                t.Error("error: ", err)
1062
        }
1063
        if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
1064
                t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
1065
        }
1066
        if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
1067
                t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
1068
        }
1069
        if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
1070
                t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
1071
        }
1072
        // Marshal direct, unmarshal to indirect.
1073
        d.A = [3]int{11, 22, 33}
1074
        d.S = []int{44, 55, 66}
1075
        d.M = map[string]int{"four": 4, "five": 5, "six": 6}
1076
        i = new(Indirect)
1077
        b.Reset()
1078
        NewEncoder(b).Encode(d)
1079
        dec = NewDecoder(b)
1080
        err = dec.Decode(&i)
1081
        if err != nil {
1082
                t.Fatal("error: ", err)
1083
        }
1084
        if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
1085
                t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
1086
        }
1087
        if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
1088
                t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
1089
        }
1090
        if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
1091
                t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
1092
        }
1093
}
1094
 
1095
// An interface with several implementations
1096
type Squarer interface {
1097
        Square() int
1098
}
1099
 
1100
type Int int
1101
 
1102
func (i Int) Square() int {
1103
        return int(i * i)
1104
}
1105
 
1106
type Float float64
1107
 
1108
func (f Float) Square() int {
1109
        return int(f * f)
1110
}
1111
 
1112
type Vector []int
1113
 
1114
func (v Vector) Square() int {
1115
        sum := 0
1116
        for _, x := range v {
1117
                sum += x * x
1118
        }
1119
        return sum
1120
}
1121
 
1122
type Point struct {
1123
        X, Y int
1124
}
1125
 
1126
func (p Point) Square() int {
1127
        return p.X*p.X + p.Y*p.Y
1128
}
1129
 
1130
// A struct with interfaces in it.
1131
type InterfaceItem struct {
1132
        I             int
1133
        Sq1, Sq2, Sq3 Squarer
1134
        F             float64
1135
        Sq            []Squarer
1136
}
1137
 
1138
// The same struct without interfaces
1139
type NoInterfaceItem struct {
1140
        I int
1141
        F float64
1142
}
1143
 
1144
func TestInterface(t *testing.T) {
1145
        iVal := Int(3)
1146
        fVal := Float(5)
1147
        // Sending a Vector will require that the receiver define a type in the middle of
1148
        // receiving the value for item2.
1149
        vVal := Vector{1, 2, 3}
1150
        b := new(bytes.Buffer)
1151
        item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
1152
        // Register the types.
1153
        Register(Int(0))
1154
        Register(Float(0))
1155
        Register(Vector{})
1156
        err := NewEncoder(b).Encode(item1)
1157
        if err != nil {
1158
                t.Error("expected no encode error; got", err)
1159
        }
1160
 
1161
        item2 := InterfaceItem{}
1162
        err = NewDecoder(b).Decode(&item2)
1163
        if err != nil {
1164
                t.Fatal("decode:", err)
1165
        }
1166
        if item2.I != item1.I {
1167
                t.Error("normal int did not decode correctly")
1168
        }
1169
        if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
1170
                t.Error("Int did not decode correctly")
1171
        }
1172
        if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
1173
                t.Error("Float did not decode correctly")
1174
        }
1175
        if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
1176
                t.Error("Vector did not decode correctly")
1177
        }
1178
        if item2.F != item1.F {
1179
                t.Error("normal float did not decode correctly")
1180
        }
1181
        // Now check that we received a slice of Squarers correctly, including a nil element
1182
        if len(item1.Sq) != len(item2.Sq) {
1183
                t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
1184
        }
1185
        for i, v1 := range item1.Sq {
1186
                v2 := item2.Sq[i]
1187
                if v1 == nil || v2 == nil {
1188
                        if v1 != nil || v2 != nil {
1189
                                t.Errorf("item %d inconsistent nils", i)
1190
                        }
1191
                        continue
1192
                        if v1.Square() != v2.Square() {
1193
                                t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
1194
                        }
1195
                }
1196
        }
1197
}
1198
 
1199
// A struct with all basic types, stored in interfaces.
1200
type BasicInterfaceItem struct {
1201
        Int, Int8, Int16, Int32, Int64      interface{}
1202
        Uint, Uint8, Uint16, Uint32, Uint64 interface{}
1203
        Float32, Float64                    interface{}
1204
        Complex64, Complex128               interface{}
1205
        Bool                                interface{}
1206
        String                              interface{}
1207
        Bytes                               interface{}
1208
}
1209
 
1210
func TestInterfaceBasic(t *testing.T) {
1211
        b := new(bytes.Buffer)
1212
        item1 := &BasicInterfaceItem{
1213
                int(1), int8(1), int16(1), int32(1), int64(1),
1214
                uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
1215
                float32(1), 1.0,
1216
                complex64(1i), complex128(1i),
1217
                true,
1218
                "hello",
1219
                []byte("sailor"),
1220
        }
1221
        err := NewEncoder(b).Encode(item1)
1222
        if err != nil {
1223
                t.Error("expected no encode error; got", err)
1224
        }
1225
 
1226
        item2 := &BasicInterfaceItem{}
1227
        err = NewDecoder(b).Decode(&item2)
1228
        if err != nil {
1229
                t.Fatal("decode:", err)
1230
        }
1231
        if !reflect.DeepEqual(item1, item2) {
1232
                t.Errorf("encode expected %v got %v", item1, item2)
1233
        }
1234
        // Hand check a couple for correct types.
1235
        if v, ok := item2.Bool.(bool); !ok || !v {
1236
                t.Error("boolean should be true")
1237
        }
1238
        if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
1239
                t.Errorf("string should be %v is %v", item1.String, v)
1240
        }
1241
}
1242
 
1243
type String string
1244
 
1245
type PtrInterfaceItem struct {
1246
        Str1 interface{} // basic
1247
        Str2 interface{} // derived
1248
}
1249
 
1250
// We'll send pointers; should receive values.
1251
// Also check that we can register T but send *T.
1252
func TestInterfacePointer(t *testing.T) {
1253
        b := new(bytes.Buffer)
1254
        str1 := "howdy"
1255
        str2 := String("kiddo")
1256
        item1 := &PtrInterfaceItem{
1257
                &str1,
1258
                &str2,
1259
        }
1260
        // Register the type.
1261
        Register(str2)
1262
        err := NewEncoder(b).Encode(item1)
1263
        if err != nil {
1264
                t.Error("expected no encode error; got", err)
1265
        }
1266
 
1267
        item2 := &PtrInterfaceItem{}
1268
        err = NewDecoder(b).Decode(&item2)
1269
        if err != nil {
1270
                t.Fatal("decode:", err)
1271
        }
1272
        // Hand test for correct types and values.
1273
        if v, ok := item2.Str1.(string); !ok || v != str1 {
1274
                t.Errorf("basic string failed: %q should be %q", v, str1)
1275
        }
1276
        if v, ok := item2.Str2.(String); !ok || v != str2 {
1277
                t.Errorf("derived type String failed: %q should be %q", v, str2)
1278
        }
1279
}
1280
 
1281
func TestIgnoreInterface(t *testing.T) {
1282
        iVal := Int(3)
1283
        fVal := Float(5)
1284
        // Sending a Point will require that the receiver define a type in the middle of
1285
        // receiving the value for item2.
1286
        pVal := Point{2, 3}
1287
        b := new(bytes.Buffer)
1288
        item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
1289
        // Register the types.
1290
        Register(Int(0))
1291
        Register(Float(0))
1292
        Register(Point{})
1293
        err := NewEncoder(b).Encode(item1)
1294
        if err != nil {
1295
                t.Error("expected no encode error; got", err)
1296
        }
1297
 
1298
        item2 := NoInterfaceItem{}
1299
        err = NewDecoder(b).Decode(&item2)
1300
        if err != nil {
1301
                t.Fatal("decode:", err)
1302
        }
1303
        if item2.I != item1.I {
1304
                t.Error("normal int did not decode correctly")
1305
        }
1306
        if item2.F != item2.F {
1307
                t.Error("normal float did not decode correctly")
1308
        }
1309
}
1310
 
1311
type U struct {
1312
        A int
1313
        B string
1314
        c float64
1315
        D uint
1316
}
1317
 
1318
func TestUnexportedFields(t *testing.T) {
1319
        var u0 U
1320
        u0.A = 17
1321
        u0.B = "hello"
1322
        u0.c = 3.14159
1323
        u0.D = 23
1324
        b := new(bytes.Buffer)
1325
        NewEncoder(b).Encode(u0)
1326
        dec := NewDecoder(b)
1327
        var u1 U
1328
        u1.c = 1234.
1329
        err := dec.Decode(&u1)
1330
        if err != nil {
1331
                t.Fatal("decode error:", err)
1332
        }
1333
        if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D {
1334
                t.Errorf("u1->u0: expected %v; got %v", u0, u1)
1335
        }
1336
        if u1.c != 1234. {
1337
                t.Error("u1.c modified")
1338
        }
1339
}
1340
 
1341
var singletons = []interface{}{
1342
        true,
1343
        7,
1344
        3.2,
1345
        "hello",
1346
        [3]int{11, 22, 33},
1347
        []float32{0.5, 0.25, 0.125},
1348
        map[string]int{"one": 1, "two": 2},
1349
}
1350
 
1351
func TestDebugSingleton(t *testing.T) {
1352
        if debugFunc == nil {
1353
                return
1354
        }
1355
        b := new(bytes.Buffer)
1356
        // Accumulate a number of values and print them out all at once.
1357
        for _, x := range singletons {
1358
                err := NewEncoder(b).Encode(x)
1359
                if err != nil {
1360
                        t.Fatal("encode:", err)
1361
                }
1362
        }
1363
        debugFunc(b)
1364
}
1365
 
1366
// A type that won't be defined in the gob until we send it in an interface value.
1367
type OnTheFly struct {
1368
        A int
1369
}
1370
 
1371
type DT struct {
1372
        //      X OnTheFly
1373
        A     int
1374
        B     string
1375
        C     float64
1376
        I     interface{}
1377
        J     interface{}
1378
        I_nil interface{}
1379
        M     map[string]int
1380
        T     [3]int
1381
        S     []string
1382
}
1383
 
1384
func TestDebugStruct(t *testing.T) {
1385
        if debugFunc == nil {
1386
                return
1387
        }
1388
        Register(OnTheFly{})
1389
        var dt DT
1390
        dt.A = 17
1391
        dt.B = "hello"
1392
        dt.C = 3.14159
1393
        dt.I = 271828
1394
        dt.J = OnTheFly{3}
1395
        dt.I_nil = nil
1396
        dt.M = map[string]int{"one": 1, "two": 2}
1397
        dt.T = [3]int{11, 22, 33}
1398
        dt.S = []string{"hi", "joe"}
1399
        b := new(bytes.Buffer)
1400
        err := NewEncoder(b).Encode(dt)
1401
        if err != nil {
1402
                t.Fatal("encode:", err)
1403
        }
1404
        debugBuffer := bytes.NewBuffer(b.Bytes())
1405
        dt2 := &DT{}
1406
        err = NewDecoder(b).Decode(&dt2)
1407
        if err != nil {
1408
                t.Error("decode:", err)
1409
        }
1410
        debugFunc(debugBuffer)
1411
}
1412
 
1413
func encFuzzDec(rng *rand.Rand, in interface{}) error {
1414
        buf := new(bytes.Buffer)
1415
        enc := NewEncoder(buf)
1416
        if err := enc.Encode(&in); err != nil {
1417
                return err
1418
        }
1419
 
1420
        b := buf.Bytes()
1421
        for i, bi := range b {
1422
                if rng.Intn(10) < 3 {
1423
                        b[i] = bi + uint8(rng.Intn(256))
1424
                }
1425
        }
1426
 
1427
        dec := NewDecoder(buf)
1428
        var e interface{}
1429
        if err := dec.Decode(&e); err != nil {
1430
                return err
1431
        }
1432
        return nil
1433
}
1434
 
1435
// This does some "fuzz testing" by attempting to decode a sequence of random bytes.
1436
func TestFuzz(t *testing.T) {
1437
        if testing.Short() {
1438
                return
1439
        }
1440
 
1441
        // all possible inputs
1442
        input := []interface{}{
1443
                new(int),
1444
                new(float32),
1445
                new(float64),
1446
                new(complex128),
1447
                &ByteStruct{255},
1448
                &ArrayStruct{},
1449
                &StringStruct{"hello"},
1450
                &GobTest1{0, &StringStruct{"hello"}},
1451
        }
1452
        testFuzz(t, time.Now().UnixNano(), 100, input...)
1453
}
1454
 
1455
func TestFuzzRegressions(t *testing.T) {
1456
        // An instance triggering a type name of length ~102 GB.
1457
        testFuzz(t, 1328492090837718000, 100, new(float32))
1458
}
1459
 
1460
func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) {
1461
        t.Logf("seed=%d n=%d\n", seed, n)
1462
        for _, e := range input {
1463
                rng := rand.New(rand.NewSource(seed))
1464
                for i := 0; i < n; i++ {
1465
                        encFuzzDec(rng, e)
1466
                }
1467
        }
1468
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.