11package main
22
33import (
4+ "io"
45 "math/rand"
56 "time"
67
@@ -15,40 +16,39 @@ func init() {
1516func main () {
1617 p := mpb .New (mpb .WithWidth (64 ))
1718
18- // initialize bar with dynamic total and initial total guess = 80
19- bar := p .AddBar (80 ,
20- // indicate that total is dynamic, could be omitted if total set to 0
21- mpb .BarDynamicTotal (),
22- // trigger total auto increment by 1, when 18 % remains till bar completion
23- mpb .BarAutoIncrTotal (18 , 1 ),
24- mpb .PrependDecorators (decor .CountersNoUnit ("%d / %d" )),
19+ bar := p .AddBar (0 , // by setting total to 0, we indicate that it's dynamic
20+ mpb .PrependDecorators (decor .Counters (decor .UnitKiB , "% .1f / % .1f" )),
2521 mpb .AppendDecorators (decor .Percentage ()),
2622 )
2723
28- totalUpd := make (chan int64 )
29- go func () {
30- for {
31- total , ok := <- totalUpd
32- bar .SetTotal (total , ! ok )
33- if ! ok {
34- break
35- }
24+ var written int64
25+ maxSleep := 100 * time .Millisecond
26+ read := makeStream (200 )
27+ for {
28+ n , err := read ()
29+ written += int64 (n )
30+ time .Sleep (time .Duration (rand .Intn (10 )+ 1 ) * maxSleep / 10 )
31+ bar .IncrBy (n )
32+ if err == io .EOF {
33+ break
3634 }
37- }()
38-
39- max := 100 * time .Millisecond
40- for i := 0 ; ! bar .Completed (); i ++ {
41- if i == 140 {
42- totalUpd <- 190
43- }
44- if i == 250 {
45- totalUpd <- 300
46- // final upd, so closing channel
47- close (totalUpd )
48- }
49- time .Sleep (time .Duration (rand .Intn (10 )+ 1 ) * max / 10 )
50- bar .Increment ()
35+ bar .SetTotal (written + 1024 , false )
5136 }
5237
38+ // final set total, final=true
39+ bar .SetTotal (written , true )
40+ // need to increment once, to shutdown the bar
41+ bar .IncrBy (0 )
42+
5343 p .Wait ()
5444}
45+
46+ func makeStream (limit int ) func () (int , error ) {
47+ return func () (int , error ) {
48+ if limit <= 0 {
49+ return 0 , io .EOF
50+ }
51+ limit --
52+ return rand .Intn (1024 ) + 1 , nil
53+ }
54+ }
0 commit comments