diff --git a/stringwrap.go b/stringwrap.go index bedf92e..ab9c8d8 100644 --- a/stringwrap.go +++ b/stringwrap.go @@ -89,7 +89,11 @@ type WrappedStringSeq struct { // lastWrappedLine pulls the last wrapped line that has been parsed func (s *WrappedStringSeq) lastWrappedLine() *WrappedString { - return &s.WrappedLines[len(s.WrappedLines)-1] + n := len(s.WrappedLines) + if n == 0 { + return nil + } + return &s.WrappedLines[n-1] } // appendWrappedSeq adds a new WrappedString to the existing slice @@ -489,7 +493,7 @@ func stringWrap( // remove the last new line from the wrapped buffer // if the last line is not a hard break. lastWrappedLine := wrappedStringSeq.lastWrappedLine() - if !lastWrappedLine.IsHardBreak { + if lastWrappedLine != nil && !lastWrappedLine.IsHardBreak { stateMachine.buffer.Truncate(stateMachine.buffer.Len() - 1) lastWrappedLine.LastSegmentInOrig = true } diff --git a/stringwrap_test.go b/stringwrap_test.go index 0231184..e400575 100644 --- a/stringwrap_test.go +++ b/stringwrap_test.go @@ -129,13 +129,24 @@ func TestStringWrap(t *testing.T) { trimWhitespace: true, splitWord: true, }, + { + input: "", + wrapped: "", + limit: 5, + trimWhitespace: true, + splitWord: true, + }, } for idx, tt := range tests { t.Run(fmt.Sprintf("Wrapped String Test %d", idx+1), func(t *testing.T) { wrapped, seq, err := wrapString(tt) + expectedLines := 0 + if wrapped != "" { + expectedLines = len(strings.Split(wrapped, "\n")) + } assert.Nil(t, err) - assert.Equal(t, len(seq.WrappedLines), len(strings.Split(wrapped, "\n"))) + assert.Equal(t, expectedLines, len(seq.WrappedLines)) assert.Equal(t, tt.wrapped, wrapped) }) }