-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransfer.go
103 lines (95 loc) · 1.93 KB
/
transfer.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
package grab
import (
"context"
"io"
"sync/atomic"
"time"
"github.com/cavaliercoder/grab/bps"
)
type transfer struct {
n int64 // must be 64bit aligned on 386
ctx context.Context
gauge bps.Gauge
lim RateLimiter
w io.Writer
r io.Reader
b []byte
}
func newTransfer(ctx context.Context, lim RateLimiter, dst io.Writer, src io.Reader, buf []byte) *transfer {
return &transfer{
ctx: ctx,
gauge: bps.NewSMA(6), // five second moving average sampling every second
lim: lim,
w: dst,
r: src,
b: buf,
}
}
// copy behaves similarly to io.CopyBuffer except that it checks for cancelation
// of the given context.Context, reports progress in a thread-safe manner and
// tracks the transfer rate.
func (c *transfer) copy() (written int64, err error) {
// maintain a bps gauge in another goroutine
ctx, cancel := context.WithCancel(c.ctx)
defer cancel()
go bps.Watch(ctx, c.gauge, c.N, time.Second)
// start the transfer
if c.b == nil {
c.b = make([]byte, 32*1024)
}
for {
select {
case <-c.ctx.Done():
err = c.ctx.Err()
return
default:
// keep working
}
nr, er := c.r.Read(c.b)
if nr > 0 {
nw, ew := c.w.Write(c.b[0:nr])
if nw > 0 {
written += int64(nw)
atomic.StoreInt64(&c.n, written)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
// wait for rate limiter
if c.lim != nil {
err = c.lim.WaitN(c.ctx, nr)
if err != nil {
return
}
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}
// N returns the number of bytes transferred.
func (c *transfer) N() (n int64) {
if c == nil {
return 0
}
n = atomic.LoadInt64(&c.n)
return
}
// BPS returns the current bytes per second transfer rate using a simple moving
// average.
func (c *transfer) BPS() (bps float64) {
if c == nil || c.gauge == nil {
return 0
}
return c.gauge.BPS()
}