Codebase list golang-github-vbauerster-mpb / 5598898
CalcPercentage Vladimir Bauer 9 years ago
2 changed file(s) with 5 addition(s) and 21 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "fmt"
44 "io"
5 "math"
65 "sync"
76 "time"
87 "unicode/utf8"
378377 // bar width without leftEnd and rightEnd runes
379378 barWidth := width - 2
380379
381 completedWidth := percentage(total, current, barWidth)
380 completedWidth := decor.CalcPercentage(total, current, barWidth)
382381
383382 buf := make([]byte, 0, width)
384383 buf = append(buf, fmtBytes[rLeft]...)
385384
386385 if rf != nil {
387 till := percentage(total, rf.till, barWidth)
386 till := decor.CalcPercentage(total, rf.till, barWidth)
388387 rbytes := make([]byte, utf8.RuneLen(rf.char))
389388 utf8.EncodeRune(rbytes, rf.char)
390389 // append refill rune
438437 return fmtBytes
439438 }
440439
441 func percentage(total, current, ratio int) int {
442 if total == 0 || current > total {
443 return 0
444 }
445 num := float64(ratio) * float64(current) / float64(total)
446 ceil := math.Ceil(num)
447 diff := ceil - num
448 // num = 2.34 will return 2
449 // num = 2.44 will return 3
450 if math.Max(diff, 0.6) == diff {
451 return int(num)
452 }
453 return int(ceil)
454 }
455
456440 func getSpinner() func() byte {
457441 chars := []byte(`-\|/`)
458442 repeat := len(chars) - 1
130130 }
131131 format += "%ds"
132132 return func(s *Statistics, myWidth chan<- int, maxWidth <-chan int) string {
133 str := fmt.Sprintf("%d %%", percentage(s.Total, s.Current, 100))
133 str := fmt.Sprintf("%d %%", CalcPercentage(s.Total, s.Current, 100))
134134 if (conf & DwidthSync) != 0 {
135135 myWidth <- utf8.RuneCountInString(str)
136136 max := <-maxWidth
143143 }
144144 }
145145
146 func percentage(total, current, ratio int) int {
146 func CalcPercentage(total, current, width int) int {
147147 if total == 0 || current > total {
148148 return 0
149149 }
150 num := float64(ratio) * float64(current) / float64(total)
150 num := float64(width) * float64(current) / float64(total)
151151 ceil := math.Ceil(num)
152152 diff := ceil - num
153153 // num = 2.34 will return 2