Skip to content

Commit

Permalink
DefaultConverter & Fix bounds error on long trailing whitespace (#16)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
hownowstephen authored Mar 30, 2023
1 parent e9756d8 commit d1eee75
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
2 changes: 1 addition & 1 deletion textplain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion wrap_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package textplain_test

import (
"strings"
"testing"

"github.com/mailproto/textplain"
Expand All @@ -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)
}

0 comments on commit d1eee75

Please sign in to comment.