-
Notifications
You must be signed in to change notification settings - Fork 78
/
io.go
147 lines (131 loc) · 2.43 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package common
import (
"bufio"
"io"
"net"
"github.com/xxf098/lite-proxy/log"
)
type RewindReader struct {
rawReader io.Reader
buf []byte
bufReadIdx int
rewound bool
buffering bool
bufferSize int
}
func (r *RewindReader) Read(p []byte) (int, error) {
if r.rewound {
if len(r.buf) > r.bufReadIdx {
n := copy(p, r.buf[r.bufReadIdx:])
r.bufReadIdx += n
return n, nil
}
r.rewound = 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.D("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("no buffer")
}
r.rewound = 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 disabled")
}
r.buffering = false
r.buf = nil
r.bufReadIdx = 0
r.bufferSize = 0
} else {
if r.buffering {
panic("reader is 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 BufferdConn struct {
net.Conn
Br *bufio.Reader
}
func (c *BufferdConn) Read(b []byte) (int, error) {
return c.Br.Read(b)
}
func CopyBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}