Skip to content
This repository has been archived by the owner on Feb 11, 2021. It is now read-only.

Commit

Permalink
DrawTextFormatBar: nonsensical numbers could cause a panic
Browse files Browse the repository at this point in the history
If one of the numbers provided to draw the progress bar was nonsensical,
like the total download size being 0, the library would cause a panic.

This adds a check for a unexpected current progress, and will display an
empty bar if it's outside acceptable bounds.
  • Loading branch information
Derek Gonyeo committed Oct 7, 2015
1 parent d7ae39d commit a9d1979
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions draw.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ func DrawTextFormatBarForW(width int64, w io.Writer) DrawTextFormatFunc {

return func(progress, total int64) string {
current := int64((float64(progress) / float64(total)) * float64(width))
if current < 0 || current > width {
return fmt.Sprintf("[%s]", strings.Repeat(" ", int(width)))
}
return fmt.Sprintf(
"[%s%s]",
strings.Repeat("=", int(current)),
Expand Down
18 changes: 18 additions & 0 deletions draw_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,24 @@ func TestDrawTextFormatBar(t *testing.T) {
if actual != expected {
t.Fatalf("bad: %s", actual)
}

actual = f(0, 0)
expected = "[ ]"
if actual != expected {
t.Fatalf("bad: %s", actual)
}

actual = f(-10, 10)
expected = "[ ]"
if actual != expected {
t.Fatalf("bad: %s", actual)
}

actual = f(20, 10)
expected = "[ ]"
if actual != expected {
t.Fatalf("bad: %s", actual)
}
}

func TestDrawTextFormatBytes(t *testing.T) {
Expand Down

0 comments on commit a9d1979

Please sign in to comment.