-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathproxyreader.go
More file actions
70 lines (59 loc) · 1.53 KB
/
Copy pathproxyreader.go
File metadata and controls
70 lines (59 loc) · 1.53 KB
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
package mpb
import (
"io"
"time"
)
type readCloser struct {
io.Reader
}
func (r readCloser) Close() error {
if closer, ok := r.Reader.(io.Closer); ok {
return closer.Close()
}
return nil
}
type proxyReader struct {
readCloser
bar *Bar
}
func (x proxyReader) Read(p []byte) (int, error) {
n, err := x.readCloser.Read(p)
x.bar.IncrBy(n)
return n, err
}
type proxyReadWriterTo struct {
proxyReader
src io.WriterTo
}
func (x proxyReadWriterTo) WriteTo(w io.Writer) (int64, error) {
return x.src.WriteTo(proxyWriter{writeCloser{w}, x.bar})
}
// ewmaProxyReadWriterTo implements its own io.WriterTo which will shadow any
// io.WriterTo implementation of the underlying readCloser's io.Reader. This is
// necessary to correctly track ewma counters.
type ewmaProxyReadWriterTo struct {
readCloser
bar *Bar
}
// If io.Copy(dst, ewmaProxyReadWriterTo) is used then this Read method will
// not be used at all. Just keeping it for manual Read cases.
func (x ewmaProxyReadWriterTo) Read(p []byte) (int, error) {
start := time.Now()
n, err := x.readCloser.Read(p)
x.bar.EwmaIncrBy(n, time.Since(start))
return n, err
}
//nolint:staticcheck // QF1008
func (x ewmaProxyReadWriterTo) WriteTo(w io.Writer) (int64, error) {
return copyBuffer(x.bar, w, x.readCloser.Reader, nil)
}
func newProxyReader(b *Bar, r io.Reader) io.ReadCloser {
if len(b.ewmaDecorators) != 0 {
return ewmaProxyReadWriterTo{readCloser{r}, b}
}
pr := proxyReader{readCloser{r}, b}
if src, ok := r.(io.WriterTo); ok {
return proxyReadWriterTo{pr, src}
}
return pr
}