2017-02-15 16:51:01 -05:00
|
|
|
package buf
|
2016-02-26 17:45:33 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2016-12-11 20:14:48 -05:00
|
|
|
// BufferedReader is a reader with internal cache.
|
2016-02-26 17:45:33 -05:00
|
|
|
type BufferedReader struct {
|
2016-12-27 15:41:44 -05:00
|
|
|
reader io.Reader
|
2017-02-15 16:51:01 -05:00
|
|
|
buffer *Buffer
|
2016-12-27 15:41:44 -05:00
|
|
|
buffered bool
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
|
|
|
|
2017-02-20 04:33:35 -05:00
|
|
|
// NewBufferedReader creates a new BufferedReader based on an io.Reader.
|
2017-02-15 16:51:01 -05:00
|
|
|
func NewBufferedReader(rawReader io.Reader) *BufferedReader {
|
2016-02-26 17:45:33 -05:00
|
|
|
return &BufferedReader{
|
2016-12-27 15:41:44 -05:00
|
|
|
reader: rawReader,
|
2017-02-15 16:51:01 -05:00
|
|
|
buffer: NewLocal(1024),
|
2016-12-27 15:41:44 -05:00
|
|
|
buffered: true,
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-27 15:41:44 -05:00
|
|
|
// IsBuffered returns true if the internal cache is effective.
|
|
|
|
func (v *BufferedReader) IsBuffered() bool {
|
|
|
|
return v.buffered
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
|
|
|
|
2016-12-27 15:41:44 -05:00
|
|
|
// 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
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
|
|
|
|
2016-12-11 20:14:48 -05:00
|
|
|
// Read implements io.Reader.Read().
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *BufferedReader) Read(b []byte) (int, error) {
|
2016-12-27 15:41:44 -05:00
|
|
|
if !v.buffered || v.buffer == nil {
|
2016-11-27 15:39:09 -05:00
|
|
|
if !v.buffer.IsEmpty() {
|
|
|
|
return v.buffer.Read(b)
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
2016-11-27 15:39:09 -05:00
|
|
|
return v.reader.Read(b)
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|
2016-11-27 15:39:09 -05:00
|
|
|
if v.buffer.IsEmpty() {
|
2017-04-18 06:41:36 -04:00
|
|
|
if err := v.buffer.Reset(ReadFrom(v.reader)); err != nil {
|
2016-02-26 17:45:33 -05:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
if v.buffer.IsEmpty() {
|
2016-02-26 17:45:33 -05:00
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
return v.buffer.Read(b)
|
2016-02-26 17:45:33 -05:00
|
|
|
}
|