Skip to content

Commit

Permalink
text: fix infinite loop in Wrap
Browse files Browse the repository at this point in the history
If the last word is greater than the limit, we wouldn't
set the next line break at all, and it would be left at
0, causing an infinite loop in the final loop to apply
the line breaks.

To fix this, recognize that the last word must be on the
last line, so its length doesn't matter. Always set the
last word's next break to the end of the text.

Fixes #1.
Closes #2.
  • Loading branch information
kr committed Sep 5, 2015
1 parent e373e13 commit bb797dc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion wrap.go
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func WrapWords(words [][]byte, spc, lim, pen int) [][][]byte {
cost[i] = math.MaxInt32
}
for i := n - 1; i >= 0; i-- {
if length[i][n-1] <= lim {
if length[i][n-1] <= lim || i == n-1 {
cost[i] = 0
nbrk[i] = n
} else {
Expand Down
18 changes: 18 additions & 0 deletions wrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,21 @@ func TestWrapOneLine(t *testing.T) {
t.Fail()
}
}

func TestWrapBug1(t *testing.T) {
cases := []struct {
limit int
text string
want string
}{
{4, "aaaaa", "aaaaa"},
{4, "a aaaaa", "a\naaaaa"},
}

for _, test := range cases {
got := Wrap(test.text, test.limit)
if got != test.want {
t.Errorf("Wrap(%q, %d) = %q want %q", test.text, test.limit, got, test.want)
}
}
}

0 comments on commit bb797dc

Please sign in to comment.