-
Notifications
You must be signed in to change notification settings - Fork 2
/
proxyreader.go
128 lines (105 loc) · 1.88 KB
/
proxyreader.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
package file
import (
"io"
)
type ProxyReader interface {
io.ReadCloser
Len() int
BytesRead() int
Rewind() bool
}
type ProxyReaderAt struct {
io.ReaderAt
off int64
len int64
onRead func(i int64)
read int
closed bool
eof bool
}
type ProxyRead struct {
io.Reader
len int64
onRead func(i int64)
read int
closed bool
eof bool
}
func (x *ProxyReaderAt) Rewind() bool {
x.onRead(int64(-x.read))
x.read = 0
return true
}
func (x *ProxyRead) Rewind() bool {
return x.read == 0
}
func (x *ProxyReaderAt) Len() int {
return int(x.len)
}
func (x *ProxyRead) Len() int {
return int(x.len)
}
func (x *ProxyReaderAt) BytesRead() int {
return x.read
}
func (x *ProxyRead) BytesRead() int {
return x.read
}
func (x *ProxyReaderAt) Seek(offset int64, whence int) (int64, error) {
x.onRead(-int64(x.read - int(offset))) // rewind progress
x.read = int(offset)
return offset, nil
}
func (x *ProxyReaderAt) Read(p []byte) (int, error) {
if x.closed {
x.onRead(-int64(x.read)) // rewind progress
x.read = 0
x.closed = false
}
if x.read == x.Len() {
return 0, io.EOF
}
var n int
var err error
if len(p) > x.Len()-x.read {
n, err = x.ReadAt(p[:min(x.Len()-x.read, len(p))], x.off+int64(x.read))
} else {
n, err = x.ReadAt(p, x.off+int64(x.read))
}
if err == io.EOF {
x.eof = true
}
if err != nil {
return n, err
}
x.read += n
if x.onRead != nil {
x.onRead(int64(n))
}
return n, nil
}
func (x *ProxyRead) Read(p []byte) (int, error) {
if x.read == x.Len() || x.closed {
return 0, io.EOF
}
n, err := x.Reader.Read(p[:min(x.Len()-x.read, len(p))])
if err == io.EOF {
x.eof = true
}
if err != nil {
return n, err
}
x.read += n
if x.onRead != nil {
x.onRead(int64(n))
}
return n, err
}
func (x *ProxyReaderAt) Close() error {
x.closed = true
return nil
}
func (x *ProxyRead) Close() error {
x.closed = true
return nil
}