Codebase list golang-github-vbauerster-mpb / dca13eb
decorator struct Vladimir Bauer 9 years ago
1 changed file(s) with 27 addition(s) and 11 deletion(s). Raw diff Collapse all Expand all
2424 Width = 70
2525 )
2626
27 // DecoratorFunc is a function that can be prepended and appended to the progress bar
28 type DecoratorFunc func(s *Statistics) string
29
30 type decoratorFuncType uint
31
32 const (
33 decoratorAppend decoratorFuncType = iota
34 decoratorPrepend
35 )
36
37 type decorator struct {
38 kind decoratorFuncType
39 f DecoratorFunc
40 }
41
2742 // Bar represents a progress bar
2843 type Bar struct {
2944 // total of the total for the progress bar
5368
5469 redrawRequestCh chan *redrawRequest
5570
56 decoratorFuncCh chan DecoratorFunc
71 decoratorCh chan *decorator
5772
5873 timePerItemEstimate time.Duration
5974 }
60
61 // DecoratorFunc is a function that can be prepended and appended to the progress bar
62 type DecoratorFunc func(s *Statistics) string
6375
6476 type Statistics struct {
6577 Total, Completed int
8395 Empty: Empty,
8496 currentIncrCh: make(chan int),
8597 redrawRequestCh: make(chan *redrawRequest),
86 decoratorFuncCh: make(chan DecoratorFunc),
98 decoratorCh: make(chan *decorator),
8799 }
88100 go b.server()
89101 return b
94106 }
95107
96108 func (b *Bar) AppendFunc(f DecoratorFunc) *Bar {
97 b.decoratorFuncCh <- f
109 b.decoratorCh <- &decorator{decoratorAppend, f}
98110 return b
99111 }
100112
116128 func (b *Bar) server() {
117129 var current int
118130 blockStartTime := time.Now()
119 buf := make([]byte, b.Width)
131 buf := make([]byte, b.Width, b.Width+9)
120132 var appendFuncs []DecoratorFunc
121 // var prependFuncs []DecoratorFunc
133 var prependFuncs []DecoratorFunc
122134 for {
123135 select {
124136 case i := <-b.currentIncrCh:
129141 b.updateTimePerItemEstimate(i, blockStartTime)
130142 current = n
131143 blockStartTime = time.Now()
132 case f := <-b.decoratorFuncCh:
133 appendFuncs = append(appendFuncs, f)
144 case d := <-b.decoratorCh:
145 switch d.kind {
146 case decoratorAppend:
147 appendFuncs = append(appendFuncs, d.f)
148 case decoratorPrepend:
149 prependFuncs = append(prependFuncs, d.f)
150 }
134151 case r := <-b.redrawRequestCh:
135152 r.bufch <- b.draw(buf, current, appendFuncs)
136153 }
138155 }
139156
140157 func (b *Bar) draw(buf []byte, current int, appendFuncs []DecoratorFunc) []byte {
141 // eta := time.Duration(b.total-current) * b.timePerItemEstimate
142158 completedWidth := current * b.Width / b.total
143159
144160 for i := 0; i < completedWidth; i++ {