mirror of https://github.com/v2ray/v2ray-core
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.
55 lines
1.1 KiB
55 lines
1.1 KiB
8 years ago
|
package buf
|
||
9 years ago
|
|
||
|
import (
|
||
|
"io"
|
||
|
)
|
||
|
|
||
8 years ago
|
// BufferedReader is a reader with internal cache.
|
||
9 years ago
|
type BufferedReader struct {
|
||
8 years ago
|
reader io.Reader
|
||
8 years ago
|
buffer *Buffer
|
||
8 years ago
|
buffered bool
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
// NewReader creates a new BufferedReader based on an io.Reader.
|
||
8 years ago
|
func NewBufferedReader(rawReader io.Reader) *BufferedReader {
|
||
9 years ago
|
return &BufferedReader{
|
||
8 years ago
|
reader: rawReader,
|
||
8 years ago
|
buffer: NewLocal(1024),
|
||
8 years ago
|
buffered: true,
|
||
9 years ago
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
// IsBuffered returns true if the internal cache is effective.
|
||
|
func (v *BufferedReader) IsBuffered() bool {
|
||
|
return v.buffered
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
// 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
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
// Read implements io.Reader.Read().
|
||
8 years ago
|
func (v *BufferedReader) Read(b []byte) (int, error) {
|
||
8 years ago
|
if !v.buffered || v.buffer == nil {
|
||
8 years ago
|
if !v.buffer.IsEmpty() {
|
||
|
return v.buffer.Read(b)
|
||
9 years ago
|
}
|
||
8 years ago
|
return v.reader.Read(b)
|
||
9 years ago
|
}
|
||
8 years ago
|
if v.buffer.IsEmpty() {
|
||
8 years ago
|
err := v.buffer.AppendSupplier(ReadFrom(v.reader))
|
||
9 years ago
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
if v.buffer.IsEmpty() {
|
||
9 years ago
|
return 0, nil
|
||
|
}
|
||
|
|
||
8 years ago
|
return v.buffer.Read(b)
|
||
9 years ago
|
}
|