forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
116 lines (101 loc) · 2.04 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package buf
import (
"io"
"v2ray.com/core/common/errors"
)
// BytesToBufferReader is a Reader that adjusts its reading speed automatically.
type BytesToBufferReader struct {
reader io.Reader
buffer *Buffer
}
// Read implements Reader.Read().
func (r *BytesToBufferReader) Read() (MultiBuffer, error) {
if err := r.buffer.Reset(ReadFrom(r.reader)); err != nil {
return nil, err
}
mb := NewMultiBuffer()
for !r.buffer.IsEmpty() {
b := New()
b.AppendSupplier(ReadFrom(r.buffer))
mb.Append(b)
}
return mb, nil
}
type readerAdpater struct {
MultiBufferReader
}
func (r *readerAdpater) Read() (MultiBuffer, error) {
return r.ReadMultiBuffer()
}
type bufferToBytesReader struct {
stream Reader
current MultiBuffer
err error
}
// fill fills in the internal buffer.
func (r *bufferToBytesReader) fill() {
b, err := r.stream.Read()
if err != nil {
r.err = err
return
}
r.current = b
}
func (r *bufferToBytesReader) Read(b []byte) (int, error) {
if r.err != nil {
return 0, r.err
}
if r.current == nil {
r.fill()
if r.err != nil {
return 0, r.err
}
}
nBytes, err := r.current.Read(b)
if r.current.IsEmpty() {
r.current.Release()
r.current = nil
}
return nBytes, err
}
func (r *bufferToBytesReader) ReadMultiBuffer() (MultiBuffer, error) {
if r.err != nil {
return nil, r.err
}
if r.current == nil {
r.fill()
if r.err != nil {
return nil, r.err
}
}
b := r.current
r.current = nil
return b, nil
}
func (r *bufferToBytesReader) writeToInternal(writer io.Writer) (int64, error) {
if r.err != nil {
return 0, r.err
}
mbWriter := NewWriter(writer)
totalBytes := int64(0)
for {
if r.current == nil {
r.fill()
if r.err != nil {
return totalBytes, r.err
}
}
totalBytes += int64(r.current.Len())
if err := mbWriter.Write(r.current); err != nil {
return totalBytes, err
}
r.current = nil
}
}
func (r *bufferToBytesReader) WriteTo(writer io.Writer) (int64, error) {
nBytes, err := r.writeToInternal(writer)
if errors.Cause(err) == io.EOF {
return nBytes, nil
}
return nBytes, err
}