Skip to content

Commit

Permalink
Merge pull request #1 from ernesto-jimenez/allow-custom-line-ending
Browse files Browse the repository at this point in the history
Configurable line ends
  • Loading branch information
ianlopshire authored Oct 11, 2019
2 parents 3f7c898 + bb6c095 commit 6ae718e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
11 changes: 9 additions & 2 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,15 @@ func (e *MarshalInvalidTypeError) Error() string {
// stream.
type Encoder struct {
w *bufio.Writer

LineEnd []byte
}

// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
bufio.NewWriter(w),
w: bufio.NewWriter(w),
LineEnd: []byte("\n"),
}
}

Expand Down Expand Up @@ -95,14 +98,18 @@ func (e *Encoder) Encode(i interface{}) (err error) {
}

func (e *Encoder) writeLines(v reflect.Value) error {
lineEnd := e.LineEnd
if len(lineEnd) == 0 {
lineEnd = []byte("\n")
}
for i := 0; i < v.Len(); i++ {
err := e.writeLine(v.Index(i))
if err != nil {
return err
}

if i != v.Len()-1 {
_, err := e.w.Write([]byte("\n"))
_, err := e.w.Write(lineEnd)
if err != nil {
return err
}
Expand Down
36 changes: 35 additions & 1 deletion encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package fixedwidth
import (
"bytes"
"fmt"
"github.com/pkg/errors"
"io"
"log"
"reflect"
"testing"

"github.com/pkg/errors"
)

func ExampleMarshal() {
Expand Down Expand Up @@ -126,3 +128,35 @@ func TestNewValueEncoder(t *testing.T) {
})
}
}

func TestEncoderWithMultipleLines(t *testing.T) {
input := []interface{}{
EncodableString{"foo", nil},
EncodableString{"bar", nil},
}

for _, tt := range []struct {
name string
expected string
newEncoder func(io.Writer) *Encoder
}{
{"default", "foo\nbar", func(w io.Writer) *Encoder { return NewEncoder(w) }},
{"default", "foo\r\nbar", func(w io.Writer) *Encoder {
enc := NewEncoder(w)
enc.LineEnd = []byte("\r\n")
return enc
}},
} {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
enc := tt.newEncoder(&buf)
err := enc.Encode(input)
if err != nil {
t.Fatal(err)
}
if buf.String() != tt.expected {
t.Fatalf("unexpected output\nexpected: %q\nreceived: %q", tt.expected, buf.String())
}
})
}
}

0 comments on commit 6ae718e

Please sign in to comment.