Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/csv/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions test/csv/parse/test_row_separator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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