-
Notifications
You must be signed in to change notification settings - Fork 3
/
encoder.go
63 lines (48 loc) · 959 Bytes
/
encoder.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
package message
import (
"bufio"
"encoding/binary"
"io"
"code.google.com/p/gogoprotobuf/proto"
)
type MsgEncoder struct {
bw *bufio.Writer
}
func NewMsgEncoder(w io.Writer) *MsgEncoder {
return &MsgEncoder{
bw: bufio.NewWriter(w),
}
}
func (me *MsgEncoder) EncodePb(m *PbMessage) error {
err := me.bw.WriteByte(byte(m.msgType))
if err != nil {
return err
}
var bytes []byte
if m.pb != nil {
bytes, err = proto.Marshal(m.pb)
if err != nil {
return err
}
}
size := len(bytes)
err = binary.Write(me.bw, binary.LittleEndian, uint32(size))
if err != nil {
return err
}
_, err = me.bw.Write(bytes)
return me.bw.Flush()
}
func (me *MsgEncoder) Encode(m *Message) error {
err := me.bw.WriteByte(byte(m.msgType))
if err != nil {
return err
}
size := len(m.bytes)
err = binary.Write(me.bw, binary.LittleEndian, uint32(size))
if err != nil {
return err
}
_, err = me.bw.Write(m.bytes)
return me.bw.Flush()
}