forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
84 lines (73 loc) · 1.57 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
package mux
import (
"io"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/serial"
)
type Reader struct {
reader io.Reader
buffer *buf.Buffer
leftOver int
}
func NewReader(reader buf.Reader) *Reader {
return &Reader{
reader: buf.ToBytesReader(reader),
buffer: buf.NewLocal(1024),
leftOver: -1,
}
}
func (r *Reader) ReadMetadata() (*FrameMetadata, error) {
r.leftOver = -1
b := r.buffer
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, 2)); err != nil {
return nil, err
}
metaLen := serial.BytesToUint16(b.Bytes())
if metaLen > 512 {
return nil, newError("invalid metalen ", metaLen).AtWarning()
}
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, int(metaLen))); err != nil {
return nil, err
}
return ReadFrameFrom(b.Bytes())
}
func (r *Reader) readSize() error {
if err := r.buffer.Reset(buf.ReadFullFrom(r.reader, 2)); err != nil {
return err
}
r.leftOver = int(serial.BytesToUint16(r.buffer.Bytes()))
return nil
}
func (r *Reader) Read() (buf.MultiBuffer, error) {
if r.leftOver == 0 {
r.leftOver = -1
return nil, io.EOF
}
if r.leftOver == -1 {
if err := r.readSize(); err != nil {
return nil, err
}
}
mb := buf.NewMultiBuffer()
for r.leftOver > 0 {
readLen := buf.Size
if r.leftOver < readLen {
readLen = r.leftOver
}
b := buf.New()
if err := b.AppendSupplier(func(bb []byte) (int, error) {
return r.reader.Read(bb[:readLen])
}); err != nil {
mb.Release()
return nil, err
}
r.leftOver -= b.Len()
mb.Append(b)
if b.Len() < readLen {
break
}
}
return mb, nil
}