v2ray-core/common/io/chan_reader.go

63 lines
863 B
Go
Raw Normal View History

2016-05-25 22:36:52 +02:00
package io
2015-12-15 22:13:09 +01:00
import (
"io"
2016-05-25 22:36:52 +02:00
"sync"
2015-12-15 22:13:09 +01:00
2016-08-20 20:55:45 +02:00
"v2ray.com/core/common/alloc"
2015-12-15 22:13:09 +01:00
)
type ChanReader struct {
2016-05-25 22:36:52 +02:00
sync.Mutex
stream Reader
2015-12-15 22:13:09 +01:00
current *alloc.Buffer
eof bool
}
2016-05-25 22:36:52 +02:00
func NewChanReader(stream Reader) *ChanReader {
2016-11-10 23:41:28 +01:00
return &ChanReader{
2015-12-15 22:13:09 +01:00
stream: stream,
}
}
2016-08-24 11:17:42 +02:00
// Private: Visible for testing.
2016-11-27 21:39:09 +01:00
func (v *ChanReader) Fill() {
b, err := v.stream.Read()
v.current = b
2016-04-18 18:44:10 +02:00
if err != nil {
2016-11-27 21:39:09 +01:00
v.eof = true
v.current = nil
2015-12-15 22:13:09 +01:00
}
}
2016-11-27 21:39:09 +01:00
func (v *ChanReader) Read(b []byte) (int, error) {
if v.eof {
2016-05-25 22:36:52 +02:00
return 0, io.EOF
}
2016-11-27 21:39:09 +01:00
v.Lock()
defer v.Unlock()
if v.current == nil {
v.Fill()
if v.eof {
2015-12-15 22:13:09 +01:00
return 0, io.EOF
}
}
2016-11-27 21:39:09 +01:00
nBytes, err := v.current.Read(b)
if v.current.IsEmpty() {
v.current.Release()
v.current = nil
2015-12-15 22:13:09 +01:00
}
2016-07-17 12:18:26 +02:00
return nBytes, err
2015-12-15 22:13:09 +01:00
}
2016-05-25 22:36:52 +02:00
2016-11-27 21:39:09 +01:00
func (v *ChanReader) Release() {
v.Lock()
defer v.Unlock()
2016-05-25 22:36:52 +02:00
2016-11-27 21:39:09 +01:00
v.eof = true
v.current.Release()
v.current = nil
v.stream = nil
2016-05-25 22:36:52 +02:00
}