forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
130 lines (116 loc) · 2.33 KB
/
io.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
package common
import (
"io"
"net"
"github.com/p4gefau1t/trojan-go/log"
)
type RewindReader struct {
rawReader io.Reader
buf []byte
bufReadIdx int
rewinded bool
buffering bool
bufferSize int
}
func (r *RewindReader) Read(p []byte) (int, error) {
if r.rewinded {
if len(r.buf) > r.bufReadIdx {
n := copy(p, r.buf[r.bufReadIdx:])
r.bufReadIdx += n
return n, nil
}
r.rewinded = false //all buffering content has been read
}
n, err := r.rawReader.Read(p)
if r.buffering {
r.buf = append(r.buf, p[:n]...)
if len(r.buf) > r.bufferSize*2 {
log.Debug("read too many bytes!")
}
}
return n, err
}
func (r *RewindReader) ReadByte() (byte, error) {
buf := [1]byte{}
_, err := r.Read(buf[:])
return buf[0], err
}
func (r *RewindReader) Discard(n int) (int, error) {
buf := [128]byte{}
if n < 128 {
return r.Read(buf[:n])
}
for discarded := 0; discarded+128 < n; discarded += 128 {
_, err := r.Read(buf[:])
if err != nil {
return discarded, err
}
}
if rest := n % 128; rest != 0 {
return r.Read(buf[:rest])
}
return n, nil
}
func (r *RewindReader) Rewind() {
if r.bufferSize == 0 {
panic("has no buffer")
}
r.rewinded = true
r.bufReadIdx = 0
}
func (r *RewindReader) StopBuffering() {
r.buffering = false
}
func (r *RewindReader) SetBufferSize(size int) {
if size == 0 { //disable buffering
if !r.buffering {
panic("reader is already disabled")
}
r.buffering = false
r.buf = nil
r.bufReadIdx = 0
r.bufferSize = 0
} else {
if r.buffering {
panic("reader is already buffering")
}
r.buffering = true
r.bufReadIdx = 0
r.bufferSize = size
r.buf = make([]byte, 0, size)
}
}
type RewindConn struct {
net.Conn
*RewindReader
}
func (c *RewindConn) Read(p []byte) (int, error) {
return c.RewindReader.Read(p)
}
func NewRewindConn(conn net.Conn) *RewindConn {
return &RewindConn{
Conn: conn,
RewindReader: &RewindReader{
rawReader: conn,
},
}
}
type StickyWriter struct {
rawWriter io.Writer
writeBuffer []byte
MaxBuffered int
}
func (w *StickyWriter) Write(p []byte) (int, error) {
if w.MaxBuffered > 0 {
w.MaxBuffered--
w.writeBuffer = append(w.writeBuffer, p...)
if w.MaxBuffered != 0 {
return len(p), nil
}
w.MaxBuffered = 0
_, err := w.rawWriter.Write(w.writeBuffer)
w.writeBuffer = nil
return len(p), err
}
return w.rawWriter.Write(p)
}