-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprogress_writer.go
40 lines (35 loc) · 939 Bytes
/
progress_writer.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
package main
import (
"io"
"time"
)
// ProgressWriter wraps a io.Writer and an updater callback
// It calls updater callback only if there are more than 1024 bytes written
// And more than 500ms has elapsed since last call to callback
const significantWrite = 1024 * 10
const significantTime = 500
type ProgressWriter struct {
Callback func(int64)
Writer io.Writer
total int64
lastCall int64
lastTotal int64
}
func (pw *ProgressWriter) Write(p []byte) (n int, err error) {
n, err = pw.Writer.Write(p)
pw.total += int64(n)
var writeCondition, timeCondition bool
var now time.Time
writeCondition = (pw.total - pw.lastTotal) > significantWrite
if writeCondition {
now = time.Now()
timeCondition = pw.lastCall == 0 ||
(now.UnixMilli()-pw.lastCall) > significantTime
}
if writeCondition && timeCondition {
pw.lastCall = now.UnixMilli()
pw.lastTotal = pw.total
pw.Callback(pw.total)
}
return n, err
}