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