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
14 changes: 8 additions & 6 deletions lib/csv/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,13 @@ def prepare_strip
end
@strip = @strip.encode(@encoding)
@escaped_strip = Regexp.escape(@strip)
# One match for both ends. A delete_prefix! loop copies the
# remainder on every character (csv#396).
@line_strip = Regexp.new(
"\\A".encode(@encoding) + @escaped_strip +
"+|".encode(@encoding) + @escaped_strip +
"+\\z".encode(@encoding)
)
if @quote_character
@strip_value = Regexp.new(@escaped_strip +
"+".encode(@encoding))
Expand Down Expand Up @@ -1238,12 +1245,7 @@ def strip_value(value)

case @strip
when String
while value.delete_prefix!(@strip)
# do nothing
end
while value.delete_suffix!(@strip)
# do nothing
end
value.gsub!(@line_strip, "")
else
value.strip!
end
Expand Down
32 changes: 32 additions & 0 deletions test/csv/parse/test_strip.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,38 @@ def test_string
strip: " "))
end

def test_string_strip_long_padding
pad = " " * 20
assert_equal(["value"],
CSV.parse_line("#{pad}value#{pad}",
strip: " ",
quote_char: nil))
assert_equal(["a b"],
CSV.parse_line("#{pad}a b#{pad}",
strip: " ",
quote_char: nil))
assert_equal(["a", "b"],
CSV.parse_line("#{pad}a,b#{pad}",
strip: " ",
quote_char: nil))
ideographic_space = "\u3000"
padding = ideographic_space * 3
assert_equal(["a#{ideographic_space}b"],
CSV.parse_line("#{padding}a#{ideographic_space}b#{padding}",
strip: ideographic_space,
quote_char: nil))

# Time the strip itself. A full parse is dominated by the
# one-byte scanner used when CSV_PARSER_SCANNER_TEST is set.
parser = CSV.new("", strip: " ", quote_char: nil).send(:parser)
value = "#{" " * 400_000}value#{" " * 400_000}"
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
parser.send(:strip_value, value)
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
assert_equal("value", value)
assert_operator(elapsed, :<, 0.25)
end

def test_no_quote
assert_equal([" a ", " b "],
CSV.parse_line(%Q{" a ", b },
Expand Down