-
Notifications
You must be signed in to change notification settings - Fork 0
/
readv_reader.go
153 lines (129 loc) · 2.44 KB
/
readv_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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// +build !wasm
package buf
import (
"io"
"runtime"
"syscall"
"v2ray.com/core/common/platform"
)
type allocStrategy struct {
current uint32
}
func (s *allocStrategy) Current() uint32 {
return s.current
}
func (s *allocStrategy) Adjust(n uint32) {
if n >= s.current {
s.current *= 4
} else {
s.current = n
}
if s.current > 32 {
s.current = 32
}
if s.current == 0 {
s.current = 1
}
}
func (s *allocStrategy) Alloc() []*Buffer {
bs := make([]*Buffer, s.current)
for i := range bs {
bs[i] = New()
}
return bs
}
type multiReader interface {
Init([]*Buffer)
Read(fd uintptr) int32
Clear()
}
type ReadVReader struct {
io.Reader
rawConn syscall.RawConn
mr multiReader
alloc allocStrategy
}
func NewReadVReader(reader io.Reader, rawConn syscall.RawConn) *ReadVReader {
return &ReadVReader{
Reader: reader,
rawConn: rawConn,
alloc: allocStrategy{
current: 1,
},
mr: newMultiReader(),
}
}
func (r *ReadVReader) readMulti() (MultiBuffer, error) {
bs := r.alloc.Alloc()
r.mr.Init(bs)
var nBytes int32
err := r.rawConn.Read(func(fd uintptr) bool {
n := r.mr.Read(fd)
if n < 0 {
return false
}
nBytes = n
return true
})
r.mr.Clear()
if err != nil {
mb := MultiBuffer(bs)
mb.Release()
return nil, err
}
if nBytes == 0 {
mb := MultiBuffer(bs)
mb.Release()
return nil, io.EOF
}
nBuf := 0
for nBuf < len(bs) {
if nBytes <= 0 {
break
}
end := int32(nBytes)
if end > Size {
end = Size
}
bs[nBuf].end = end
nBytes -= end
nBuf++
}
for i := nBuf; i < len(bs); i++ {
bs[i].Release()
bs[i] = nil
}
return MultiBuffer(bs[:nBuf]), nil
}
// ReadMultiBuffer implements Reader.
func (r *ReadVReader) ReadMultiBuffer() (MultiBuffer, error) {
if r.alloc.Current() == 1 {
b, err := readOne(r.Reader)
if err != nil {
return nil, err
}
if b.IsFull() {
r.alloc.Adjust(1)
}
return NewMultiBufferValue(b), nil
}
mb, err := r.readMulti()
if err != nil {
return nil, err
}
r.alloc.Adjust(uint32(len(mb)))
return mb, nil
}
var useReadv = false
func init() {
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
value := platform.NewEnvFlag("v2ray.buf.readv").GetValue(func() string { return defaultFlagValue })
switch value {
case defaultFlagValue, "auto":
if (runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "s390x") && (runtime.GOOS == "linux" || runtime.GOOS == "darwin") {
useReadv = true
}
case "enable":
useReadv = true
}
}