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/bufio/reader.go

68 lines
1.3 KiB

package bufio
import (
"io"
8 years ago
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
)
8 years ago
// BufferedReader is a reader with internal cache.
type BufferedReader struct {
reader io.Reader
buffer *buf.Buffer
cached bool
}
8 years ago
// NewReader creates a new BufferedReader based on an io.Reader.
func NewReader(rawReader io.Reader) *BufferedReader {
return &BufferedReader{
reader: rawReader,
8 years ago
buffer: buf.New(),
cached: true,
}
}
8 years ago
// Release implements Releasable.Release().
8 years ago
func (v *BufferedReader) Release() {
8 years ago
if v.buffer != nil {
v.buffer.Release()
v.buffer = nil
}
common.Release(v.reader)
}
8 years ago
// Cached returns true if the internal cache is effective.
8 years ago
func (v *BufferedReader) Cached() bool {
return v.cached
}
8 years ago
// SetCached is to enable or disable internal cache. If cache is disabled,
// Read() and Write() calls will be delegated to the underlying io.Reader directly.
8 years ago
func (v *BufferedReader) SetCached(cached bool) {
v.cached = cached
}
8 years ago
// Read implements io.Reader.Read().
8 years ago
func (v *BufferedReader) Read(b []byte) (int, error) {
if !v.cached || v.buffer == nil {
8 years ago
if !v.buffer.IsEmpty() {
return v.buffer.Read(b)
}
8 years ago
return v.reader.Read(b)
}
8 years ago
if v.buffer.IsEmpty() {
8 years ago
err := v.buffer.AppendSupplier(buf.ReadFrom(v.reader))
if err != nil {
return 0, err
}
}
8 years ago
if v.buffer.IsEmpty() {
return 0, nil
}
8 years ago
return v.buffer.Read(b)
}