-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpbio.go
74 lines (61 loc) · 1.36 KB
/
pbio.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
package pbio
import (
"bufio"
"encoding/binary"
"io"
"google.golang.org/protobuf/proto"
)
// Encoder encodes protobuf messages and writes to the underlying writer.
type Encoder struct {
w io.Writer
buf []byte
}
// NewEncoder inits a new encoder.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: w,
buf: make([]byte, binary.MaxVarintLen64),
}
}
// Encode encodes a message.
func (e *Encoder) Encode(msg proto.Message) error {
opt := proto.MarshalOptions{}
sz := opt.Size(msg)
e.buf = e.buf[:binary.PutUvarint(e.buf, uint64(sz))]
data, err := opt.MarshalAppend(e.buf, msg)
if err != nil {
return err
}
e.buf = data
_, err = e.w.Write(data)
return err
}
// --------------------------------------------------------------------
// Decoder decodes protobuf messages from an underlying reader.
type Decoder struct {
r *bufio.Reader
buf []byte
}
// NewDecoder inits a new Decoder.
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
r: bufio.NewReader(r),
}
}
// Decode decodes a message.
func (d *Decoder) Decode(msg proto.Message) error {
sz, err := binary.ReadUvarint(d.r)
if err != nil {
return err
}
if n := int(sz); cap(d.buf) < n {
d.buf = make([]byte, n)
} else {
d.buf = d.buf[:n]
}
if _, err := io.ReadFull(d.r, d.buf); err != nil {
return err
}
opt := proto.UnmarshalOptions{}
return opt.Unmarshal(d.buf, msg)
}