Repository navigation
Expand file tree
/
Copy pathproxywriter.go
More file actions
69 lines (58 loc) · 1.54 KB
/
Copy pathproxywriter.go
File metadata and controls
69 lines (58 loc) · 1.54 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
package mpb
import (
"io"
"time"
)
type writeCloser struct {
io.Writer
}
func (w writeCloser) Close() error {
if closer, ok := w.Writer.(io.Closer); ok {
return closer.Close()
}
return nil
}
type proxyWriter struct {
writeCloser
bar *Bar
}
func (x proxyWriter) Write(p []byte) (int, error) {
n, err := x.writeCloser.Write(p)
x.bar.IncrBy(n)
return n, err
}
type proxyWriteReaderFrom struct {
proxyWriter
dst io.ReaderFrom
}
func (x proxyWriteReaderFrom) ReadFrom(r io.Reader) (int64, error) {
return x.dst.ReadFrom(proxyReader{readCloser{r}, x.bar})
}
// ewmaProxyWriteReaderFrom implements its own io.ReaderFrom which will shadow any
// io.ReaderFrom implementation of the underlying writeCloser's io.Writer. This is
// necessary to correctly track ewma counters.
type ewmaProxyWriteReaderFrom struct {
writeCloser
bar *Bar
}
// If io.Copy(ewmaProxyWriteReaderFrom, src) is used then this Write method will
// not be used at all. Just keeping it for manual Write cases.
func (x ewmaProxyWriteReaderFrom) Write(p []byte) (int, error) {
start := time.Now()
n, err := x.writeCloser.Write(p)
x.bar.EwmaIncrBy(n, time.Since(start))
return n, err
}
func (x ewmaProxyWriteReaderFrom) ReadFrom(r io.Reader) (int64, error) {
return copyBuffer(x.bar, x.writeCloser, r, nil)
}
func newProxyWriter(b *Bar, w io.Writer) io.WriteCloser {
if len(b.ewmaDecorators) != 0 {
return ewmaProxyWriteReaderFrom{writeCloser{w}, b}
}
pw := proxyWriter{writeCloser{w}, b}
if dst, ok := w.(io.ReaderFrom); ok {
return proxyWriteReaderFrom{pw, dst}
}
return pw
}