-
Notifications
You must be signed in to change notification settings - Fork 1
/
encoder.go
76 lines (57 loc) · 1.24 KB
/
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
64
65
66
67
68
69
70
71
72
73
74
75
76
package cypress
import (
"encoding/binary"
"io"
)
// A type which encodes messages given to it in native protobuf format
// and writes them out.
type Encoder struct {
w io.Writer
}
// Create an Encoder that will write it's output to w
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: w,
}
}
// Encode and write a Message
func (e *Encoder) Encode(m *Message) (uint64, error) {
sz := m.Size()
buf := pbBufPool.Get().([]byte)
buf[0] = '+'
cnt := binary.PutUvarint(buf[1:], uint64(sz))
_, err := e.w.Write(buf[:cnt+1])
if err != nil {
pbBufPool.Put(buf)
return 0, err
}
if len(buf) < sz {
buf = make([]byte, sz)
}
cnt, err = m.MarshalTo(buf)
if err != nil {
pbBufPool.Put(buf)
return 0, err
}
_, err = e.w.Write(buf[:cnt])
pbBufPool.Put(buf)
if err != nil {
return 0, err
}
return uint64(sz) + 5, nil
}
// An encoder that writes messages in Key/Value format
type KVEncoder struct {
w io.Writer
}
// Create a KVEncoder that writes it's output to w
func NewKVEncoder(w io.Writer) *KVEncoder {
return &KVEncoder{w}
}
// Encode and write a message
func (kv *KVEncoder) Encode(m *Message) (uint64, error) {
str := m.KVString()
kv.w.Write([]byte(str))
kv.w.Write([]byte("\n"))
return uint64(len(str) + 1), nil
}