-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffered_reader.go
53 lines (45 loc) · 1.13 KB
/
buffered_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
package buf
import (
"io"
)
// BufferedReader is a reader with internal cache.
type BufferedReader struct {
reader io.Reader
buffer *Buffer
buffered bool
}
// NewBufferedReader creates a new BufferedReader based on an io.Reader.
func NewBufferedReader(rawReader io.Reader) *BufferedReader {
return &BufferedReader{
reader: rawReader,
buffer: NewLocal(1024),
buffered: true,
}
}
// IsBuffered returns true if the internal cache is effective.
func (v *BufferedReader) IsBuffered() bool {
return v.buffered
}
// SetBuffered is to enable or disable internal cache. If cache is disabled,
// Read() calls will be delegated to the underlying io.Reader directly.
func (v *BufferedReader) SetBuffered(cached bool) {
v.buffered = cached
}
// Read implements io.Reader.Read().
func (v *BufferedReader) Read(b []byte) (int, error) {
if !v.buffered || v.buffer == nil {
if !v.buffer.IsEmpty() {
return v.buffer.Read(b)
}
return v.reader.Read(b)
}
if v.buffer.IsEmpty() {
if err := v.buffer.Reset(ReadFrom(v.reader)); err != nil {
return 0, err
}
}
if v.buffer.IsEmpty() {
return 0, nil
}
return v.buffer.Read(b)
}