-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstream_encode_test.go
97 lines (79 loc) · 2.08 KB
/
stream_encode_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
package y3
import (
"bufio"
"bytes"
"io"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStreamEncoder(t *testing.T) {
expected := []byte{
0x10, 0x0B,
0x11, 0x02, 0x01, 0x02,
0x12, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05}
data := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
s := new(bytes.Buffer)
s.Write(data)
encoder := NewStreamEncoder(0x10)
//-> 0x11, 0x02, 0x01, 0x02,
n11 := NewPrimitivePacketEncoder(0x11)
n11.AddBytes([]byte{0x01, 0x02})
encoder.AddPacket(n11)
// -> 0x12, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05
encoder.AddStreamPacket(0x12, len(data), s)
assert.EqualValues(t, len(expected), encoder.GetLen())
n, err := io.ReadAll(encoder.GetReader())
assert.NoError(t, err)
assert.Equal(t, expected, n[:encoder.GetLen()])
}
func TestStreamEncoder3BytesBatch(t *testing.T) {
expected := []byte{
0x10, 0x0B,
0x11, 0x02, 0x01, 0x02,
0x12, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05}
data := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
s := new(bytes.Buffer)
s.Write(data)
encoder := NewStreamEncoder(0x10)
//-> 0x11, 0x02, 0x01, 0x02,
encoder.AddPacketBuffer([]byte{0x11, 0x02, 0x01, 0x02})
// -> 0x12, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05
encoder.AddStreamPacket(0x12, len(data), s)
assert.EqualValues(t, len(expected), encoder.GetLen())
final := new(bytes.Buffer)
buf := make([]byte, 3)
r := bufio.NewReader(encoder.GetReader())
for {
v, err := r.Read(buf)
t.Logf("-->v=%d, err=%v", v, err)
if err != nil {
if err == io.EOF {
final.Write(buf[:v])
break
}
}
final.Write(buf[:v])
}
assert.Equal(t, expected, final.Bytes())
}
func TestStreamEncoderNilReader(t *testing.T) {
encoder := NewStreamEncoder(0x10)
//-> 0x11, 0x02, 0x01, 0x02,
encoder.AddPacketBuffer([]byte{0x11, 0x02, 0x01, 0x02})
assert.EqualValues(t, 0, encoder.GetLen())
final := new(bytes.Buffer)
buf := make([]byte, 3)
r := bufio.NewReader(encoder.GetReader())
for {
v, err := r.Read(buf)
t.Logf("-->v=%d, err=%v", v, err)
if err != nil {
if err == io.EOF {
final.Write(buf[:v])
break
}
}
final.Write(buf[:v])
}
assert.Equal(t, []byte(nil), final.Bytes())
}