-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_test.go
163 lines (151 loc) · 2.56 KB
/
decode_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package bare
import (
"bytes"
"testing"
)
func TestDecodeIntoUInt(t *testing.T) {
r := bytes.NewBuffer([]byte{0xff, 0x01})
var res uint
if err := Decode(r, &res); err != nil {
t.Fatal(err)
}
if res != 255 {
t.Fatal("expected 255")
}
}
func TestDecodeIntoUIntArray(t *testing.T) {
r := bytes.NewBuffer([]byte{0xfe, 0x03, 0x7e, 0x80, 0x01})
var res [3]int
if err := Decode(r, &res); err != nil {
t.Fatal(err)
}
if res[0] != 255 || res[1] != 63 || res[2] != 64 {
t.Fatalf("unexpected value: %#v", res)
}
}
func TestDecodeUInt(t *testing.T) {
tests := []struct {
Encoded []byte
Res uint
}{
{
Encoded: []byte{0x00},
Res: 0,
},
{
Encoded: []byte{0x01},
Res: 1,
},
{
Encoded: []byte{0x7e},
Res: 126,
},
{
Encoded: []byte{0x7f},
Res: 127,
},
{
Encoded: []byte{0x80, 0x01},
Res: 128,
},
{
Encoded: []byte{0x81, 0x01},
Res: 129,
},
{
Encoded: []byte{0xff, 0x01},
Res: 255,
},
}
for _, test := range tests {
r := bytes.NewBuffer(test.Encoded)
decoded, err := DecodeUInt(r)
if err != nil {
t.Fatal(err)
}
if decoded != test.Res {
t.Fatalf("expected: %#v, got: %#v", test.Res, decoded)
}
if r.Available() != 0 {
t.Fatal("leftover bytes")
}
}
}
func TestDecodeInt(t *testing.T) {
tests := []struct {
Encoded []byte
Res int
}{
{
Encoded: []byte{0x00},
Res: 0,
},
{
Encoded: []byte{0x02},
Res: 1,
},
{
Encoded: []byte{0x01},
Res: -1,
},
{
Encoded: []byte{0x7e},
Res: 63,
},
{
Encoded: []byte{0x7d},
Res: -63,
},
{
Encoded: []byte{0x80, 0x01},
Res: 64,
},
{
Encoded: []byte{0x7f},
Res: -64,
},
{
Encoded: []byte{0x82, 0x01},
Res: 65,
},
{
Encoded: []byte{0x81, 0x01},
Res: -65,
},
{
Encoded: []byte{0xfe, 0x03},
Res: 255,
},
{
Encoded: []byte{0xfd, 0x03},
Res: -255,
},
}
for _, test := range tests {
r := bytes.NewBuffer(test.Encoded)
decoded, err := DecodeInt(r)
if err != nil {
t.Fatal(err)
}
if decoded != test.Res {
t.Fatalf("expected: %#v, got: %#v", test.Res, decoded)
}
if r.Available() != 0 {
t.Fatal("leftover bytes")
}
}
}
func TestStruct(t *testing.T) {
s := struct {
Foo uint
Bar int
Buzz string
}{}
r := bytes.NewBuffer([]byte{0xFF, 0x01, 0xFD, 0x03, 0x04, 0x42, 0x41, 0x52, 0x45})
if err := Decode(r, &s); err != nil {
t.Fatal(err)
}
if s.Foo != 255 || s.Bar != -255 || s.Buzz != "BARE" {
t.Fatalf("expected a different struct: %#v", s)
}
}