/
progress.go
126 lines (109 loc) · 2.44 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright 2020 Alexey Krivonogov. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
package vm
import (
"io"
"math/rand"
)
const (
ProgressCopy = iota
ProgressDownload
ProgressCompress
ProgressDecompress
ProgStatusStart = 0
ProgStatusActive = 1
ProgStatusEnd = 2
)
type Progress struct {
ID uint32
Type int32
Status int32
Total int64
Current int64
Source string
Dest string
Ratio float64
Custom interface{}
handle ProgressFunc
}
type ProgressFunc func(*Progress) bool
type ProgressReader struct {
Progress
reader io.Reader
}
func NewProgress(rt *Runtime, total int64, ptype int64) *Progress {
return &Progress{
ID: rand.Uint32(),
Total: total,
Type: int32(ptype),
handle: rt.Owner.Settings.ProgressHandle,
}
}
func NewProgressReader(reader io.Reader, progress *Progress) *ProgressReader {
return &ProgressReader{
Progress: *progress,
reader: reader,
}
}
func (progress *ProgressReader) Read(data []byte) (n int, err error) {
n, err = progress.reader.Read(data)
if err == nil && n > 0 {
progress.Increment(int64(n))
}
return n, err
}
func (progress *Progress) Increment(inc int64) {
progress.Status = ProgStatusActive
progress.Current += int64(inc)
if progress.Current >= progress.Total {
progress.Ratio = 1
} else {
progress.Ratio = float64(progress.Current) / float64(progress.Total)
}
if progress.handle != nil {
progress.handle(progress)
}
}
func (progress *Progress) Complete() {
progress.Ratio = 1
progress.Status = ProgStatusEnd
progress.handle(progress)
return
}
func (progress *Progress) Start(source, dest string) {
progress.Source = source
progress.Dest = dest
progress.Status = ProgStatusStart
progress.handle(progress)
return
}
func ProgressStart(rt *Runtime, total int64, ptype int64, src, dest string) int64 {
if rt.Owner.Unique == nil {
return 0
}
prog := NewProgress(rt, total, ptype)
rt.Owner.Unique.Store(int64(prog.ID), prog)
prog.Start(src, dest)
return int64(prog.ID)
}
func ProgressInc(rt *Runtime, id, inc int64) {
if rt.Owner.Unique == nil {
return
}
if prog, loaded := rt.Owner.Unique.Load(id); loaded {
if v, ok := prog.(*Progress); ok {
v.Increment(inc)
}
}
}
func ProgressEnd(rt *Runtime, id int64) {
if rt.Owner.Unique == nil {
return
}
if prog, loaded := rt.Owner.Unique.LoadAndDelete(id); loaded {
if v, ok := prog.(*Progress); ok {
v.Complete()
}
}
}