-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathreader.go
301 lines (265 loc) · 6.85 KB
/
reader.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package shared
import (
"bytes"
"errors"
"io"
)
const (
scratchByteArrayLen = 32
)
var (
zeroByteSlice = []byte{}[:0:0]
)
var (
_ SlickReader = &SlickReaderStream{}
_ SlickReader = &SlickReaderSlice{}
)
func NewReader(r io.Reader) SlickReader {
return &SlickReaderStream{br: &readerToScanner{r: r}}
}
func NewBytesReader(buf *bytes.Buffer) SlickReader {
return &SlickReaderStream{br: buf}
}
func NewSliceReader(b []byte) SlickReader {
return &SlickReaderSlice{b: b}
}
// SlickReader is a hybrid of reader and buffer interfaces with methods giving
// specific attention to the performance needs found in a decoder.
// Implementations cover io.Reader as well as []byte directly.
//
// In particular, it allows:
//
// - returning byte-slices with zero-copying (you were warned!) when possible
// - returning byte-slices for short reads which will be reused (you were warned!)
// - putting a 'track' point in the buffer, and later yielding all those bytes at once
// - counting the number of bytes read (for use in parser error messages, mainly)
//
// All of these shortcuts mean correct usage is essential to avoid unexpected behaviors,
// but in return allow avoiding many, many common sources of memory allocations in a parser.
type SlickReader interface {
// Read n bytes into a byte slice which may be shared and must not be reused
// After any additional calls to this reader.
// Readnzc will use the implementation scratch buffer if possible,
// i.e. n < len(scratchbuf), or may return a view of the []byte being decoded from.
// Requesting a zero length read will return `zeroByteSlice`, a len-zero cap-zero slice.
Readnzc(n int) ([]byte, error)
// Read n bytes into a new byte slice.
// If zero-copy views into existing buffers are acceptable (e.g. you know you
// won't later mutate, reference or expose this memory again), prefer `Readnzc`.
// If you already have an existing slice of sufficient size to reuse, prefer `Readb`.
// Requesting a zero length read will return `zeroByteSlice`, a len-zero cap-zero slice.
Readn(n int) ([]byte, error)
// Read `len(b)` bytes into the given slice, starting at its beginning,
// overwriting all values, and disregarding any extra capacity.
Readb(b []byte) error
Readn1() (uint8, error)
Unreadn1()
NumRead() int // number of bytes read
Track()
StopTrack() []byte
}
// SlickReaderStream is a SlickReader that reads off an io.Reader.
// Initialize it by wrapping an ioDecByteScanner around your io.Reader and dumping it in.
// While this implementation does use some internal buffers, it's still advisable
// to use a buffered reader to avoid small reads for any external IO like disk or network.
type SlickReaderStream struct {
br readerScanner
scratch [scratchByteArrayLen]byte // temp byte array re-used internally for efficiency during read.
n int // num read
tracking []byte // tracking bytes read
isTracking bool
}
func (z *SlickReaderStream) NumRead() int {
return z.n
}
func (z *SlickReaderStream) Readnzc(n int) (bs []byte, err error) {
if n == 0 {
return zeroByteSlice, nil
}
if n < len(z.scratch) {
bs = z.scratch[:n]
} else {
bs = make([]byte, n)
}
err = z.Readb(bs)
return
}
func (z *SlickReaderStream) Readn(n int) (bs []byte, err error) {
if n == 0 {
return zeroByteSlice, nil
}
bs = make([]byte, n)
err = z.Readb(bs)
return
}
func (z *SlickReaderStream) Readb(bs []byte) error {
if len(bs) == 0 {
return nil
}
n, err := io.ReadAtLeast(z.br, bs, len(bs))
z.n += n
if z.isTracking {
z.tracking = append(z.tracking, bs...)
}
return err
}
func (z *SlickReaderStream) Readn1() (b uint8, err error) {
b, err = z.br.ReadByte()
if err != nil {
return
}
z.n++
if z.isTracking {
z.tracking = append(z.tracking, b)
}
return
}
func (z *SlickReaderStream) Unreadn1() {
err := z.br.UnreadByte()
if err != nil {
panic(err)
}
z.n--
if z.isTracking {
if l := len(z.tracking) - 1; l >= 0 {
z.tracking = z.tracking[:l]
}
}
}
func (z *SlickReaderStream) Track() {
if z.tracking != nil {
z.tracking = z.tracking[:0]
}
z.isTracking = true
}
func (z *SlickReaderStream) StopTrack() (bs []byte) {
z.isTracking = false
return z.tracking
}
// SlickReaderSlice implements SlickReader by reading a byte slice directly.
// Often this means the zero-copy methods can simply return subslices.
type SlickReaderSlice struct {
b []byte // data
c int // cursor
a int // available
t int // track start
}
func (z *SlickReaderSlice) reset(in []byte) {
z.b = in
z.a = len(in)
z.c = 0
z.t = 0
}
func (z *SlickReaderSlice) NumRead() int {
return z.c
}
func (z *SlickReaderSlice) Unreadn1() {
if z.c == 0 || len(z.b) == 0 {
panic(errors.New("cannot unread last byte read"))
}
z.c--
z.a++
return
}
func (z *SlickReaderSlice) Readnzc(n int) (bs []byte, err error) {
if n == 0 {
return zeroByteSlice, nil
} else if z.a == 0 {
return zeroByteSlice, io.EOF
} else if n > z.a {
return zeroByteSlice, io.ErrUnexpectedEOF
} else {
c0 := z.c
z.c = c0 + n
z.a = z.a - n
bs = z.b[c0:z.c]
}
return
}
func (z *SlickReaderSlice) Readn(n int) (bs []byte, err error) {
if n == 0 {
return zeroByteSlice, nil
}
bs = make([]byte, n)
err = z.Readb(bs)
return
}
func (z *SlickReaderSlice) Readn1() (v uint8, err error) {
if z.a == 0 {
panic(io.EOF)
}
v = z.b[z.c]
z.c++
z.a--
return
}
func (z *SlickReaderSlice) Readb(bs []byte) error {
bs2, err := z.Readnzc(len(bs))
copy(bs, bs2)
return err
}
func (z *SlickReaderSlice) Track() {
z.t = z.c
}
func (z *SlickReaderSlice) StopTrack() (bs []byte) {
return z.b[z.t:z.c]
}
// conjoin the io.Reader and io.ByteScanner interfaces.
type readerScanner interface {
io.Reader
io.ByteScanner
}
// readerToScanner decorates an `io.Reader` with all the methods to also
// fulfill the `io.ByteScanner` interface.
type readerToScanner struct {
r io.Reader
l byte // last byte
ls byte // last byte status. 0: init-canDoNothing, 1: canRead, 2: canUnread
b [1]byte // tiny buffer for reading single bytes
}
func (z *readerToScanner) Read(p []byte) (n int, err error) {
var firstByte bool
if z.ls == 1 {
z.ls = 2
p[0] = z.l
if len(p) == 1 {
n = 1
return
}
firstByte = true
p = p[1:]
}
n, err = z.r.Read(p)
if n > 0 {
if err == io.EOF && n == len(p) {
err = nil // read was successful, so postpone EOF (till next time)
}
z.l = p[n-1]
z.ls = 2
}
if firstByte {
n++
}
return
}
func (z *readerToScanner) ReadByte() (c byte, err error) {
n, err := z.Read(z.b[:])
if n == 1 {
c = z.b[0]
if err == io.EOF {
err = nil // read was successful, so postpone EOF (till next time)
}
}
return
}
func (z *readerToScanner) UnreadByte() (err error) {
x := z.ls
if x == 0 {
err = errors.New("cannot unread - nothing has been read")
} else if x == 1 {
err = errors.New("cannot unread - last byte has not been read")
} else if x == 2 {
z.ls = 1
}
return
}