forked from streamingfast/binary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface_test.go
54 lines (45 loc) · 1 KB
/
interface_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
package bin
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
type Example struct {
Prefix byte
Value uint32
}
func (e *Example) UnmarshalBinary(decoder *Decoder) (err error) {
if e.Prefix, err = decoder.ReadByte(); err != nil {
return err
}
if e.Value, err = decoder.ReadUint32(BE()); err != nil {
return err
}
return nil
}
func (e *Example) MarshalBinary(encoder *Encoder) error {
if err := encoder.WriteByte(e.Prefix); err != nil {
return err
}
return encoder.WriteUint32(e.Value, BE())
}
func TestMarshalBinary(t *testing.T) {
buf := new(bytes.Buffer)
e := &Example{Value: 72, Prefix: 0xaa}
enc := NewEncoder(buf)
enc.Encode(e)
assert.Equal(t, []byte{
0xaa, 0x00, 0x00, 0x00, 0x48,
}, buf.Bytes())
}
func TestUnmarshalBinary(t *testing.T) {
buf := []byte{
0xaa, 0x00, 0x00, 0x00, 0x48,
}
e := &Example{}
d := NewDecoder(buf)
err := d.Decode(e)
assert.NoError(t, err)
assert.Equal(t, e, &Example{Value: 72, Prefix: 0xaa})
assert.Equal(t, 0, d.Remaining())
}