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.
v2ray-core/common/io/chan_reader.go

63 lines
863 B

package io
import (
"io"
"sync"
"v2ray.com/core/common/alloc"
)
type ChanReader struct {
sync.Mutex
stream Reader
current *alloc.Buffer
eof bool
}
func NewChanReader(stream Reader) *ChanReader {
return &ChanReader{
stream: stream,
}
}
// Private: Visible for testing.
8 years ago
func (v *ChanReader) Fill() {
b, err := v.stream.Read()
v.current = b
if err != nil {
8 years ago
v.eof = true
v.current = nil
}
}
8 years ago
func (v *ChanReader) Read(b []byte) (int, error) {
if v.eof {
return 0, io.EOF
}
8 years ago
v.Lock()
defer v.Unlock()
if v.current == nil {
v.Fill()
if v.eof {
return 0, io.EOF
}
}
8 years ago
nBytes, err := v.current.Read(b)
if v.current.IsEmpty() {
v.current.Release()
v.current = nil
}
return nBytes, err
}
8 years ago
func (v *ChanReader) Release() {
v.Lock()
defer v.Unlock()
8 years ago
v.eof = true
v.current.Release()
v.current = nil
v.stream = nil
}