-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreader.go
56 lines (46 loc) · 1015 Bytes
/
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
package parser
import (
"io"
)
const readSize = 1024
type ioerror struct {
err error
}
func (ioe ioerror) String() string {
return ioe.err.Error()
}
func (ioe ioerror) Error() string {
return ioe.err.Error()
}
type Reader struct {
r io.Reader
buf []byte
cur int
}
func NewReader(r io.Reader) *Reader {
return &Reader{r: r}
}
func (r *Reader) read(n int) ([]byte, *Reader, error) {
for r.needToRead(n) {
fresh := make([]byte, 1024)
c, err := r.r.Read(fresh)
r.buf = append(r.buf, fresh[0:c]...)
if err != nil {
// Don't worry about cleanup on an ioerror
return nil, r, ioerror{err}
}
}
low, high := r.cur, r.cur+n
bytes := r.buf[low:high]
return bytes, r.clone(high), nil
}
func (r *Reader) needToRead(desired int) bool {
return r.cur+desired > len(r.buf)
}
func (r *Reader) clone(cur int) *Reader {
return &Reader{
r: r.r,
buf: r.buf,
cur: cur,
}
}