summaryrefslogtreecommitdiff
path: root/vendor/github.com/vbauerster/mpb/v7/proxyreader.go
blob: a16f5ec8af4d21304cb75539633b41f41b1419d4 (plain)
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
package mpb

import (
	"io"
	"io/ioutil"
	"time"
)

type proxyReader struct {
	io.ReadCloser
	bar *Bar
}

func (x *proxyReader) Read(p []byte) (int, error) {
	n, err := x.ReadCloser.Read(p)
	x.bar.IncrBy(n)
	if err == io.EOF {
		go x.bar.SetTotal(-1, true)
	}
	return n, err
}

type proxyWriterTo struct {
	io.ReadCloser // *proxyReader
	wt            io.WriterTo
	bar           *Bar
}

func (x *proxyWriterTo) WriteTo(w io.Writer) (int64, error) {
	n, err := x.wt.WriteTo(w)
	x.bar.IncrInt64(n)
	if err == io.EOF {
		go x.bar.SetTotal(-1, true)
	}
	return n, err
}

type ewmaProxyReader struct {
	io.ReadCloser // *proxyReader
	bar           *Bar
}

func (x *ewmaProxyReader) Read(p []byte) (int, error) {
	start := time.Now()
	n, err := x.ReadCloser.Read(p)
	if n > 0 {
		x.bar.DecoratorEwmaUpdate(time.Since(start))
	}
	return n, err
}

type ewmaProxyWriterTo struct {
	io.ReadCloser             // *ewmaProxyReader
	wt            io.WriterTo // *proxyWriterTo
	bar           *Bar
}

func (x *ewmaProxyWriterTo) WriteTo(w io.Writer) (int64, error) {
	start := time.Now()
	n, err := x.wt.WriteTo(w)
	if n > 0 {
		x.bar.DecoratorEwmaUpdate(time.Since(start))
	}
	return n, err
}

func newProxyReader(r io.Reader, bar *Bar) io.ReadCloser {
	rc := toReadCloser(r)
	rc = &proxyReader{rc, bar}

	if wt, isWriterTo := r.(io.WriterTo); bar.hasEwmaDecorators {
		rc = &ewmaProxyReader{rc, bar}
		if isWriterTo {
			rc = &ewmaProxyWriterTo{rc, wt, bar}
		}
	} else if isWriterTo {
		rc = &proxyWriterTo{rc, wt, bar}
	}
	return rc
}

func toReadCloser(r io.Reader) io.ReadCloser {
	if rc, ok := r.(io.ReadCloser); ok {
		return rc
	}
	return ioutil.NopCloser(r)
}