You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/buf/buffered_reader.go

54 lines
1.1 KiB

package buf
import (
"io"
)
8 years ago
// 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.
7 years ago
func (r *BufferedReader) IsBuffered() bool {
return r.buffered
}
// SetBuffered is to enable or disable internal cache. If cache is disabled,
// Read() calls will be delegated to the underlying io.Reader directly.
7 years ago
func (r *BufferedReader) SetBuffered(cached bool) {
r.buffered = cached
}
8 years ago
// Read implements io.Reader.Read().
7 years ago
func (r *BufferedReader) Read(b []byte) (int, error) {
if !r.buffered || r.buffer == nil {
if !r.buffer.IsEmpty() {
return r.buffer.Read(b)
}
7 years ago
return r.reader.Read(b)
}
7 years ago
if r.buffer.IsEmpty() {
if err := r.buffer.Reset(ReadFrom(r.reader)); err != nil {
return 0, err
}
}
7 years ago
if r.buffer.IsEmpty() {
return 0, nil
}
7 years ago
return r.buffer.Read(b)
}