diff --git a/reader.go b/reader.go index 987a040..47801c3 100644 --- a/reader.go +++ b/reader.go @@ -27,7 +27,7 @@ func New(r io.Reader) io.Reader { func (r reader) Read(p []byte) (n int, err error) { n, err = r.r.Read(p) for i, b := range p { - if b == rByte { + if j := i + 1; b == rByte && ((j < len(p) && p[j] != nByte) || j == len(p)) { p[i] = nByte } } diff --git a/reader_test.go b/reader_test.go index 10d6a2f..c50f5e5 100644 --- a/reader_test.go +++ b/reader_test.go @@ -1,9 +1,11 @@ package macreader import ( + "testing" "bytes" "encoding/csv" "fmt" + "strings" ) func Example() { @@ -32,3 +34,63 @@ func Example() { // With macreader: [][]string{[]string{"a", "b", "c"}, []string{"1", "2", "3"}} } + + +func TestCR(t *testing.T) { + testFile := bytes.NewBufferString("a,b,c\r1,2,3\r").Bytes() + + r := csv.NewReader(New(bytes.NewReader(testFile))) + lines, err := r.ReadAll() + + if err != nil { + t.Errorf("An error occurred while reading the data: %v", err) + } + if len(lines) != 2 { + t.Errorf("Wrong number of lines. Expected 2, got %d", len(lines)) + } +} + +func TestLF(t *testing.T) { + testFile := bytes.NewBufferString("a,b,c\n1,2,3\n").Bytes() + + r := csv.NewReader(New(bytes.NewReader(testFile))) + lines, err := r.ReadAll() + + if err != nil { + t.Errorf("An error occurred while reading the data: %v", err) + } + if len(lines) != 2 { + t.Errorf("Wrong number of lines. Expected 2, got %d", len(lines)) + } +} + +func TestCRLF(t *testing.T) { + testFile := bytes.NewBufferString("a,b,c\r\n1,2,3\r\n").Bytes() + + r := csv.NewReader(New(bytes.NewReader(testFile))) + lines, err := r.ReadAll() + + if err != nil { + t.Errorf("An error occurred while reading the data: %v", err) + } + if len(lines) != 2 { + t.Errorf("Wrong number of lines. Expected 2, got %d", len(lines)) + } +} + +func TestCRInQuote(t *testing.T) { + testFile := bytes.NewBufferString("a,\"foo,\rbar\",c\r1,\"2\r\n2\",3\r").Bytes() + + r := csv.NewReader(New(bytes.NewReader(testFile))) + lines, err := r.ReadAll() + + if err != nil { + t.Errorf("An error occurred while reading the data: %v", err) + } + if len(lines) != 2 { + t.Errorf("Wrong number of lines. Expected 2, got %d", len(lines)) + } + if strings.Contains(lines[1][1], "\n\n") { + t.Error("The CRLF was converted to a LFLF") + } +}