diff --git a/bar_filler_bar.go b/bar_filler_bar.go index fd6ef0f..3860d2f 100644 --- a/bar_filler_bar.go +++ b/bar_filler_bar.go @@ -233,7 +233,7 @@ var tip component var refilling, filling, padding []byte var fillCount int - curWidth := int(internal.PercentageRound(stat.Total, stat.Current, uint(width))) + curWidth := int(internal.PercentageRound(stat.Total, stat.Current, int64(width))) if curWidth != 0 { if !stat.Completed || s.tipOnComplete { @@ -243,7 +243,7 @@ } switch refWidth := 0; { case stat.Refill != 0: - refWidth = int(internal.PercentageRound(stat.Total, stat.Refill, uint(width))) + refWidth = int(internal.PercentageRound(stat.Total, stat.Refill, int64(width))) curWidth -= refWidth refWidth += curWidth fallthrough diff --git a/internal/percentage.go b/internal/percentage.go index 4bc36f5..988227d 100644 --- a/internal/percentage.go +++ b/internal/percentage.go @@ -3,17 +3,20 @@ import "math" // Percentage is a helper function, to calculate percentage. -func Percentage(total, current int64, width uint) float64 { - if total <= 0 { +func Percentage(total, current, width uint) float64 { + if total == 0 { return 0 } if current >= total { return float64(width) } - return float64(int64(width)*current) / float64(total) + return float64(width*current) / float64(total) } // PercentageRound same as Percentage but with math.Round. -func PercentageRound(total, current int64, width uint) float64 { - return math.Round(Percentage(total, current, width)) +func PercentageRound(total, current, width int64) float64 { + if total < 0 || current < 0 || width < 0 { + return 0 + } + return math.Round(Percentage(uint(total), uint(current), uint(width))) } diff --git a/internal/percentage_test.go b/internal/percentage_test.go index 515ad60..b0e2838 100644 --- a/internal/percentage_test.go +++ b/internal/percentage_test.go @@ -4,7 +4,7 @@ func TestPercentage(t *testing.T) { // key is barWidth - testSuite := map[uint][]struct { + testSuite := map[int64][]struct { name string total int64 current int64