1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-09 02:46:35 -05:00
v2fly/common/bufio/reader.go

80 lines
1.5 KiB
Go
Raw Normal View History

2016-12-09 07:17:34 -05:00
package bufio
2016-02-26 17:45:33 -05:00
import (
"io"
"sync"
2016-02-26 17:45:33 -05:00
2016-12-11 20:14:48 -05:00
"v2ray.com/core/common"
2016-12-09 05:35:27 -05:00
"v2ray.com/core/common/buf"
2016-02-26 17:45:33 -05:00
)
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 {
sync.Mutex
2016-02-26 17:45:33 -05:00
reader io.Reader
2016-12-09 05:35:27 -05:00
buffer *buf.Buffer
2016-02-26 17:45:33 -05:00
cached bool
}
2016-12-11 20:14:48 -05:00
// NewReader creates a new BufferedReader based on an io.Reader.
2016-12-09 07:17:34 -05:00
func NewReader(rawReader io.Reader) *BufferedReader {
2016-02-26 17:45:33 -05:00
return &BufferedReader{
reader: rawReader,
2016-12-09 06:08:25 -05:00
buffer: buf.New(),
2016-02-26 17:45:33 -05:00
cached: true,
}
}
2016-12-11 20:14:48 -05:00
// Release implements Releasable.Release().
2016-11-27 15:39:09 -05:00
func (v *BufferedReader) Release() {
v.Lock()
defer v.Unlock()
2016-11-27 15:39:09 -05:00
v.buffer.Release()
v.buffer = nil
2016-12-11 20:14:48 -05:00
if releasable, ok := v.reader.(common.Releasable); ok {
releasable.Release()
}
2016-11-27 15:39:09 -05:00
v.reader = nil
2016-02-26 17:45:33 -05:00
}
2016-12-11 20:14:48 -05:00
// Cached returns true if the internal cache is effective.
2016-11-27 15:39:09 -05:00
func (v *BufferedReader) Cached() bool {
return v.cached
2016-02-26 17:45:33 -05:00
}
2016-12-11 20:14:48 -05:00
// 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.
2016-11-27 15:39:09 -05:00
func (v *BufferedReader) SetCached(cached bool) {
v.cached = 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) {
v.Lock()
defer v.Unlock()
2016-11-27 15:39:09 -05:00
if v.reader == nil {
return 0, io.EOF
}
2016-11-27 15:39:09 -05:00
if !v.cached {
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() {
2016-12-09 06:08:25 -05:00
err := v.buffer.AppendSupplier(buf.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
}