diff --git a/lib/csv/parser.rb b/lib/csv/parser.rb index f14be3af..bf3b211c 100644 --- a/lib/csv/parser.rb +++ b/lib/csv/parser.rb @@ -130,6 +130,15 @@ def each_line(row_separator) yield(buffer) buffer = nil next if line.empty? + # The remainder was already taken from this chunk. Leaving + # the scanner at its start drops those bytes on the next + # read, so a later re-parse of the row cannot see them. + unless line.end_with?(row_separator) + position += line.bytesize + @scanner.pos = position + buffer = line + next + end else buffer << line line = buffer diff --git a/test/csv/parse/test_row_separator.rb b/test/csv/parse/test_row_separator.rb index 5fd8e751..005f5455 100644 --- a/test/csv/parse/test_row_separator.rb +++ b/test/csv/parse/test_row_separator.rb @@ -13,4 +13,40 @@ def test_multiple_characters CSV.parse("a\r\nb\r\n", row_sep: "\r\n")) end end + + def test_two_character_separator_across_chunk_boundary + row_sep = "\r\n" + chunk = 8 + head = "x" * (chunk - 1) + quoted = "y" * (chunk - 2) + opened = head + row_sep + "\"" + quoted + row_sep + "admin,true" + row_sep + closed = opened + "\"" + row_sep + plain = head + row_sep + "b,\"c\"" + row_sep + with_chunk_size(chunk.to_s) do + error = assert_raise(CSV::MalformedCSVError) do + CSV.parse(opened, row_sep: row_sep) + end + assert_match(/Unclosed quoted field/, error.message) + assert_equal([[head], + [quoted + row_sep + "admin,true" + row_sep]], + CSV.parse(closed, row_sep: row_sep)) + assert_equal([[head], ["b", "c"]], + CSV.parse(plain, row_sep: row_sep)) + end + + file = Tempfile.new(["row-sep", ".csv"]) + begin + file.binmode + file.write(("x" * 8191) + row_sep + "\"" + ("y" * 8190) + row_sep + + "admin,true" + row_sep + "\"" + row_sep) + file.close + rows = [] + CSV.foreach(file.path, row_sep: row_sep) {|row| rows << row } + assert_equal(2, rows.size) + assert_equal(8191, rows[0][0].bytesize) + assert_equal(8204, rows[1][0].bytesize) + ensure + file.close! + end + end end