v2ray-core/common/buf/buffered_reader.go

55 lines
1.1 KiB
Go
Raw Normal View History

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