1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-19 10:56:06 -05:00
v2fly/common/buf/buffered_reader.go

55 lines
1.1 KiB
Go
Raw Normal View History

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
}
2016-12-11 20:14:48 -05:00
// NewReader 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-02-15 16:51:01 -05:00
err := v.buffer.AppendSupplier(ReadFrom(v.reader))
2016-02-26 17:45:33 -05:00
if err != nil {
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
}