Skip to content

Commit

Permalink
Fix encoder panic when last value is empty
Browse files Browse the repository at this point in the history
Fix a panic in the encoder due to trying to write an empty value at
the end of a line that contains multi-byte characters.
  • Loading branch information
ianlopshire committed Aug 17, 2023
1 parent 03add0a commit 48332ed
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions buff.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ func lineBufferFromValue(value rawValue) *lineBuilder {

// WriteValue writes the given value to the lineBuilder at the give start index.
func (b *lineBuilder) WriteValue(start int, value rawValue) {
// If the value is empty there is nothing to write.
if len(value.data) == 0 {
return
}

// Fast path for ascii only operation.
if !b.hasMultiByteChar() && !value.hasMultiByteChar() {
copy(b.data[start:], value.data)
Expand Down
18 changes: 18 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,24 @@ func TestMarshal_backwardCompatibility(t *testing.T) {
})
}

func TestEncoder_regressions(t *testing.T) {
// Ensure the encoder doesn't panic when encoding an empty value at the end of a line
// that contains multi-byte characters.
// See: https://github.com/ianlopshire/go-fixedwidth/issues/58
t.Run("issue 58", func(t *testing.T) {
var v struct {
Foo string `fixed:"1,1"`
Bar string `fixed:"2,2,right"`
}
v.Foo = "Ç"

buf := new(bytes.Buffer)
e := NewEncoder(buf)
e.SetUseCodepointIndices(true)
_ = e.Encode(v)
})
}

func TestNewValueEncoder(t *testing.T) {
for _, tt := range []struct {
name string
Expand Down

0 comments on commit 48332ed

Please sign in to comment.