From d1eee75c3a567b81512f246d33fbf6f15a65b47a Mon Sep 17 00:00:00 2001 From: Stephen Young Date: Thu, 30 Mar 2023 14:50:12 -0400 Subject: [PATCH] DefaultConverter & Fix bounds error on long trailing whitespace (#16) Even longer trailing whitespace results in a different out-of-bounds issue due to slice bounds issues. The wrapper could do with a rewrite, but in the meantime, this ensures we don't ever try and grab an invalid slice --- textplain.go | 2 +- wrap.go | 5 ++++- wrap_test.go | 6 +++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/textplain.go b/textplain.go index 2ceaa27..cbadaea 100644 --- a/textplain.go +++ b/textplain.go @@ -14,7 +14,7 @@ var ( ErrBodyNotFound = errors.New("could not find a `body` element in your html document") ) -var defaultConverter = NewRegexpConverter() +var defaultConverter = NewTreeConverter() // Convert is a convenience method so the library can be used without initializing a converter // because this library relies heavily on regexp objects, it may act as a bottlneck to concurrency diff --git a/wrap.go b/wrap.go index 351703c..10c69db 100644 --- a/wrap.go +++ b/wrap.go @@ -17,11 +17,14 @@ func WordWrap(txt string, lineLength int) string { var final []string for _, line := range strings.Split(txt, "\n") { var startIndex, endIndex int - for (len(line) - endIndex) > lineLength { + for (len(line)-endIndex) > lineLength && startIndex < len(line) { endIndex += lineLength if endIndex >= len(line) { endIndex = len(line) - 1 + } else if endIndex < startIndex { + endIndex = startIndex } + newIndex := strings.LastIndex(line[startIndex:endIndex+1], " ") if newIndex <= 0 { continue diff --git a/wrap_test.go b/wrap_test.go index 41aaec3..4693ba3 100644 --- a/wrap_test.go +++ b/wrap_test.go @@ -1,6 +1,7 @@ package textplain_test import ( + "strings" "testing" "github.com/mailproto/textplain" @@ -19,9 +20,12 @@ func TestWrappingInvalidLength(t *testing.T) { assert.Equal(t, body, wrapped) } -func TestWrappingEdgeCase(t *testing.T) { +func TestWrappingTrailingWhitespace(t *testing.T) { body := "1 23 45\n67\n1234567890 1 " wrapped := textplain.WordWrap(body, 13) assert.Equal(t, "1 23 45\n67\n1234567890 1 \n", wrapped) + + wrapped = textplain.WordWrap("1234567890"+strings.Repeat(" ", 20), 10) + assert.Equal(t, "1234567890\n", wrapped) }