-
Notifications
You must be signed in to change notification settings - Fork 1
/
decoder.go
144 lines (111 loc) · 2.25 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package cypress
import (
"bufio"
"encoding/binary"
"encoding/json"
"io"
"strings"
)
type typeDecoder func(d *Decoder) (*Message, error)
// A type that, given a stream of many shapes, decodes it and generates
// Messages.
type Decoder struct {
r *bufio.Reader
decoder typeDecoder
kv *KVParser
js *json.Decoder
}
// Create a new Decoder reading data from r
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
r: bufio.NewReader(r),
}
}
// Peek at the input and detect the stream type
func (d *Decoder) probe() error {
b, err := d.r.ReadByte()
if err != nil {
return err
}
err = d.r.UnreadByte()
if err != nil {
return err
}
switch b {
case '+':
d.decoder = decodeNative
case '>':
d.kv = NewKVParser(d.r)
d.decoder = decodeKV
case '{':
d.js = json.NewDecoder(d.r)
d.decoder = decodeJSON
default:
d.decoder = decodeBare
}
return nil
}
// Decode the next Message in the stream
func (d *Decoder) Decode() (*Message, error) {
if d.decoder == nil {
err := d.probe()
if err != nil {
return nil, err
}
}
return d.decoder(d)
}
// Decodes messages encoded in the native protobuf format
func decodeNative(d *Decoder) (*Message, error) {
b, err := d.r.ReadByte()
if err != nil {
return nil, err
}
if b != '+' {
return nil, ErrUnknownStreamType
}
dataLen, err := binary.ReadUvarint(d.r)
if err != nil {
return nil, err
}
buf := pbBufPool.Get().([]byte)
if uint64(len(buf)) < dataLen {
buf = make([]byte, dataLen)
}
sbuf := buf[:dataLen]
_, err = io.ReadFull(d.r, sbuf)
if err != nil {
pbBufPool.Put(buf)
return nil, err
}
m := &Message{Version: DEFAULT_VERSION}
err = m.Unmarshal(sbuf)
pbBufPool.Put(buf)
if err != nil {
return nil, err
}
return m, nil
}
// Decodes messages in the native Key/Value format
func decodeKV(d *Decoder) (*Message, error) {
return d.kv.Generate()
}
// Decodes messages in JSON format
func decodeJSON(d *Decoder) (*Message, error) {
m := &Message{}
err := d.js.Decode(m)
if err != nil {
return nil, err
}
m.Version = DEFAULT_VERSION
return m, nil
}
func decodeBare(d *Decoder) (*Message, error) {
m := Log()
line, err := d.r.ReadString('\n')
if err != nil {
return nil, err
}
m.Add("message", strings.TrimRight(line, " \t\n"))
return m, nil
}