-
Notifications
You must be signed in to change notification settings - Fork 3
/
decoder.go
76 lines (58 loc) · 1.27 KB
/
decoder.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
package message
import (
"bufio"
"encoding/binary"
"io"
"reflect"
"code.google.com/p/gogoprotobuf/proto"
)
type MsgDecoder struct {
br *bufio.Reader
}
func NewMsgDecoder(r io.Reader) *MsgDecoder {
return &MsgDecoder{
br: bufio.NewReader(r),
}
}
func (md *MsgDecoder) DecodePb(m *PbMessage) error {
msgType, err := md.br.ReadByte()
if err != nil {
return err
}
m.msgType = uint8(msgType)
t, ok := registry[m.msgType]
if !ok {
panic("unknown type") // TODO error handle
}
// since reflect.New() returns a pointer type,
// so m.pb's underlying type is actually a pointer
v := reflect.New(t)
m.pb = v.Interface().(proto.Message)
var size uint32
err = binary.Read(md.br, binary.LittleEndian, &size)
if size == 0 || err != nil { // no need to read and unmarshal
m.pb = nil
return err
}
bytes := make([]byte, size)
_, err = io.ReadFull(md.br, bytes)
if err != nil {
return err
}
return proto.Unmarshal(bytes, m.pb)
}
func (md *MsgDecoder) Decode(m *Message) error {
msgType, err := md.br.ReadByte()
if err != nil {
return err
}
m.msgType = uint8(msgType)
var size uint32
err = binary.Read(md.br, binary.LittleEndian, &size)
if err != nil {
return err
}
m.bytes = make([]byte, size)
_, err = io.ReadFull(md.br, m.bytes)
return err
}