1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 17:27:50 -04:00
v2fly/common/bufio/reader.go

69 lines
992 B
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-09 05:35:27 -05:00
"v2ray.com/core/common/buf"
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-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-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
v.reader = nil
2016-02-26 17:45:33 -05:00
}
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-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-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
}