-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsugar.go
72 lines (63 loc) · 1.55 KB
/
sugar.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
package progress
import (
"sync"
"time"
)
type ReaderWrapper struct {
Reader
lock *sync.RWMutex
startTime *time.Time
}
// Extend adds some nice utility methods to a Reader.
// Reader implementations can just embed this.
func Extend(t Reader) ReaderWrapper {
if already, wrapped := t.(ReaderWrapper); wrapped {
return already
}
now := time.Now()
return ReaderWrapper{Reader: t,
lock: new(sync.RWMutex),
startTime: &now,
}
}
// PerSecond returns the throughput since this tracker began.
func (s ReaderWrapper) PerSecond() float64 {
s.lock.Lock()
defer s.lock.Unlock()
fin, _ := s.Count()
return float64(fin) / time.Since(*s.startTime).Seconds()
}
// Remaining estimates the time remaining until completion.
func (s ReaderWrapper) Remaining() time.Duration {
perSecond := s.PerSecond()
fin, tot := s.Count()
if perSecond == 0 {
return time.Duration(0)
}
if !s.InProgress() {
return 0
}
seconds := float64(tot-fin) / perSecond
return time.Duration(seconds * float64(time.Second))
}
// Percentage returns the current progress as a percentage between 0 and 1.
func (s ReaderWrapper) Percentage() float64 {
fin, tot := s.Count()
return float64(fin) / float64(tot)
}
// InProgress will return false when the tracker is complete.
// It is debounced to try and return false for 200ms.
// After 200ms it will finally return true.
func (s ReaderWrapper) InProgress() bool {
ch, closed := s.DoneChan()
if closed {
return false
}
t := time.NewTimer(200 * time.Millisecond)
select {
case <-t.C:
return true
case <-ch:
return false
}
}