mirror of https://github.com/v2ray/v2ray-core
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.
67 lines
1002 B
67 lines
1002 B
9 years ago
|
package io
|
||
9 years ago
|
|
||
|
import (
|
||
|
"io"
|
||
9 years ago
|
"sync"
|
||
9 years ago
|
|
||
|
"github.com/v2ray/v2ray-core/common/alloc"
|
||
|
)
|
||
|
|
||
|
type ChanReader struct {
|
||
9 years ago
|
sync.Mutex
|
||
|
stream Reader
|
||
9 years ago
|
current *alloc.Buffer
|
||
|
eof bool
|
||
|
}
|
||
|
|
||
9 years ago
|
func NewChanReader(stream Reader) *ChanReader {
|
||
9 years ago
|
this := &ChanReader{
|
||
|
stream: stream,
|
||
|
}
|
||
9 years ago
|
this.Fill()
|
||
9 years ago
|
return this
|
||
|
}
|
||
|
|
||
9 years ago
|
// @Private
|
||
|
func (this *ChanReader) Fill() {
|
||
9 years ago
|
b, err := this.stream.Read()
|
||
9 years ago
|
this.current = b
|
||
9 years ago
|
if err != nil {
|
||
9 years ago
|
this.eof = true
|
||
|
this.current = nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (this *ChanReader) Read(b []byte) (int, error) {
|
||
9 years ago
|
if this.eof {
|
||
|
return 0, io.EOF
|
||
|
}
|
||
|
|
||
|
this.Lock()
|
||
|
defer this.Unlock()
|
||
9 years ago
|
if this.current == nil {
|
||
9 years ago
|
this.Fill()
|
||
9 years ago
|
if this.eof {
|
||
|
return 0, io.EOF
|
||
|
}
|
||
|
}
|
||
|
nBytes := copy(b, this.current.Value)
|
||
|
if nBytes == this.current.Len() {
|
||
|
this.current.Release()
|
||
|
this.current = nil
|
||
|
} else {
|
||
|
this.current.SliceFrom(nBytes)
|
||
|
}
|
||
|
return nBytes, nil
|
||
|
}
|
||
9 years ago
|
|
||
|
func (this *ChanReader) Release() {
|
||
|
this.Lock()
|
||
|
defer this.Unlock()
|
||
|
|
||
|
this.eof = true
|
||
|
this.current.Release()
|
||
|
this.current = nil
|
||
|
this.stream = nil
|
||
|
}
|