CalcPercentage
Vladimir Bauer
9 years ago
| 2 | 2 |
import (
|
| 3 | 3 |
"fmt"
|
| 4 | 4 |
"io"
|
| 5 | |
"math"
|
| 6 | 5 |
"sync"
|
| 7 | 6 |
"time"
|
| 8 | 7 |
"unicode/utf8"
|
|
| 378 | 377 |
// bar width without leftEnd and rightEnd runes
|
| 379 | 378 |
barWidth := width - 2
|
| 380 | 379 |
|
| 381 | |
completedWidth := percentage(total, current, barWidth)
|
|
380 |
completedWidth := decor.CalcPercentage(total, current, barWidth)
|
| 382 | 381 |
|
| 383 | 382 |
buf := make([]byte, 0, width)
|
| 384 | 383 |
buf = append(buf, fmtBytes[rLeft]...)
|
| 385 | 384 |
|
| 386 | 385 |
if rf != nil {
|
| 387 | |
till := percentage(total, rf.till, barWidth)
|
|
386 |
till := decor.CalcPercentage(total, rf.till, barWidth)
|
| 388 | 387 |
rbytes := make([]byte, utf8.RuneLen(rf.char))
|
| 389 | 388 |
utf8.EncodeRune(rbytes, rf.char)
|
| 390 | 389 |
// append refill rune
|
|
| 438 | 437 |
return fmtBytes
|
| 439 | 438 |
}
|
| 440 | 439 |
|
| 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 | |
|
| 456 | 440 |
func getSpinner() func() byte {
|
| 457 | 441 |
chars := []byte(`-\|/`)
|
| 458 | 442 |
repeat := len(chars) - 1
|
| 130 | 130 |
}
|
| 131 | 131 |
format += "%ds"
|
| 132 | 132 |
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))
|
| 134 | 134 |
if (conf & DwidthSync) != 0 {
|
| 135 | 135 |
myWidth <- utf8.RuneCountInString(str)
|
| 136 | 136 |
max := <-maxWidth
|
|
| 143 | 143 |
}
|
| 144 | 144 |
}
|
| 145 | 145 |
|
| 146 | |
func percentage(total, current, ratio int) int {
|
|
146 |
func CalcPercentage(total, current, width int) int {
|
| 147 | 147 |
if total == 0 || current > total {
|
| 148 | 148 |
return 0
|
| 149 | 149 |
}
|
| 150 | |
num := float64(ratio) * float64(current) / float64(total)
|
|
150 |
num := float64(width) * float64(current) / float64(total)
|
| 151 | 151 |
ceil := math.Ceil(num)
|
| 152 | 152 |
diff := ceil - num
|
| 153 | 153 |
// num = 2.34 will return 2
|