forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchan_reader.go
48 lines (42 loc) · 802 Bytes
/
chan_reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package http
import (
"io"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
)
type ChanReader struct {
stream v2io.Reader
current *alloc.Buffer
eof bool
}
func NewChanReader(stream v2io.Reader) *ChanReader {
this := &ChanReader{
stream: stream,
}
this.fill()
return this
}
func (this *ChanReader) fill() {
b, err := this.stream.Read()
this.current = b
if err != nil {
this.eof = true
this.current = nil
}
}
func (this *ChanReader) Read(b []byte) (int, error) {
if this.current == nil {
this.fill()
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
}