-
Notifications
You must be signed in to change notification settings - Fork 485
/
readbuffer.go
112 lines (94 loc) · 2.12 KB
/
readbuffer.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
package core
import (
"errors"
"io"
)
const ProbeSize = 1024 * 1024 // 1MB
const (
BufferDisable = 0
BufferDrainAndClear = -1
)
// ReadBuffer support buffering and Seek over buffer
// positive BufferSize will enable buffering mode
// Seek to negative offset will clear buffer
// Seek with a positive BufferSize will continue buffering after the last read from the buffer
// Seek with a negative BufferSize will clear buffer after the last read from the buffer
// Read more than BufferSize will raise error
type ReadBuffer struct {
io.Reader
BufferSize int
buf []byte
pos int
}
func NewReadBuffer(rd io.Reader) *ReadBuffer {
if rs, ok := rd.(*ReadBuffer); ok {
return rs
}
return &ReadBuffer{Reader: rd}
}
func (r *ReadBuffer) Read(p []byte) (n int, err error) {
// with zero buffer - read as usual
if r.BufferSize == BufferDisable {
return r.Reader.Read(p)
}
// if buffer not empty - read from it
if r.pos < len(r.buf) {
n = copy(p, r.buf[r.pos:])
r.pos += n
return
}
// with negative buffer - empty it and read as usual
if r.BufferSize < 0 {
r.BufferSize = BufferDisable
r.buf = nil
r.pos = 0
return r.Reader.Read(p)
}
n, err = r.Reader.Read(p)
if len(r.buf)+n > r.BufferSize {
return 0, errors.New("probe reader overflow")
}
r.buf = append(r.buf, p[:n]...)
r.pos += n
return
}
func (r *ReadBuffer) Close() error {
if closer, ok := r.Reader.(io.Closer); ok {
return closer.Close()
}
return nil
}
func (r *ReadBuffer) Seek(offset int64, whence int) (int64, error) {
var pos int
switch whence {
case io.SeekStart:
pos = int(offset)
case io.SeekCurrent:
pos = r.pos + int(offset)
case io.SeekEnd:
pos = len(r.buf) + int(offset)
}
// negative offset - empty buffer
if pos < 0 {
r.buf = nil
r.pos = 0
} else if pos >= len(r.buf) {
r.pos = len(r.buf)
} else {
r.pos = pos
}
return int64(r.pos), nil
}
func (r *ReadBuffer) Peek(n int) ([]byte, error) {
r.BufferSize = n
b := make([]byte, n)
if _, err := io.ReadAtLeast(r, b, n); err != nil {
return nil, err
}
r.Reset()
return b, nil
}
func (r *ReadBuffer) Reset() {
r.BufferSize = BufferDrainAndClear
r.pos = 0
}