-
Notifications
You must be signed in to change notification settings - Fork 3
/
progress.go
89 lines (73 loc) · 1.27 KB
/
progress.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
package progress
import (
"errors"
"io"
)
var ErrCompleted = io.EOF
type Sizable interface {
Size() int64
}
type Monitorable interface {
Current() int64
Error() error
}
type Progressable interface {
Monitorable
Sizable
}
type Progressor interface {
Progress() Progress
}
type Progress struct {
current int64
size int64
err error
}
func (p Progress) Current() int64 {
return int64(p.current)
}
func (p Progress) Size() int64 {
return int64(p.size)
}
func (p Progress) Error() error {
return p.err
}
func (p Progress) Progress() Progress {
return p
}
func (p Progress) Complete() bool {
return IsCompleted(&p)
}
func (p Progress) Ratio() float64 {
if p.current == 0 || p.size < 0 {
return 0
}
if p.current >= p.size {
return 1
}
return float64(p.current) / float64(p.size)
}
func (p Progress) Percent() float64 {
if p.current == 0 || p.size < 0 {
return 0
}
if p.current >= p.size {
return 100
}
return 100 / (float64(p.size) / float64(p.current))
}
func IsCompleted(p Progressable) bool {
if IsErrCompleted(p.Error()) {
return true
}
if p.Size() < 0 {
return false
}
return p.Current() >= p.Size()
}
func IsErrCompleted(err error) bool {
if errors.Is(err, io.EOF) || errors.Is(err, ErrCompleted) {
return true
}
return false
}