diff --git a/lib/csv/byte_scanner.rb b/lib/csv/byte_scanner.rb new file mode 100644 index 00000000..4a2e2e51 --- /dev/null +++ b/lib/csv/byte_scanner.rb @@ -0,0 +1,398 @@ +# frozen_string_literal: true + +class CSV + class Parser + # The patterns CSV::Parser scans with, answered by comparing bytes in + # Ruby instead of running a regular expression. + # + # Every pattern is built from ASCII separators, and the parser uses them + # only on Strings in an encoding where an ASCII byte is always an ASCII + # character (see Parser#byte_scannable?). So where a run of bytes stops + # is where the equivalent regular expression's match stops. + # + # Every kind of pattern is an instance of this one class, with the same + # instance variables, so the call sites that use them stay monomorphic + # for YJIT. ByteScanner#skip and #scan answer the commonest kinds + # themselves and call into the pattern only for the rest, because + # without YJIT each Ruby method call is a large part of a scan. + class BytePattern + BYTEINDEX_AVAILABLE = "".respond_to?(:byteindex) + + # ByteScanner#scan reads these to answer the commonest kinds itself. + attr_reader :kind + attr_reader :bytes + + class << self + # A String, as StringScanner#scan(String) matches it. + def literal(literal) + bytes = literal.bytes.freeze + if bytes.size == 1 + new(:byte, bytes[0], nil) + else + new(:literal, bytes, nil) + end + end + + # Literals in alternation (/a|b|c/): the first that matches, in + # order. + def alternation(literals) + new(:alternation, + nil, + literals.collect {|literal| literal.bytes.freeze}.freeze) + end + + # One or more bytes not in a set (/[^...]+/). + def run_except(characters) + # An ASCII-only binary String is compatible with any + # ASCII-compatible String, so byteindex searches the bytes. + bytes = characters.bytes.uniq + stops = Array.new(256, false) + bytes.each {|byte| stops[byte] = true} + items = bytes.collect {|byte| byte.chr.b.freeze}.freeze + if items.size == 1 + new(:byte_until, items[0], nil) + else + new(:run_except, stops.freeze, items) + end + end + + # One or more bytes in a set (/[...]+/, /c+/). + def run_in(characters) + bytes = characters.bytes.uniq + if bytes.size == 1 + new(:byte_run, bytes[0], nil) + else + members = Array.new(256, false) + bytes.each {|byte| members[byte] = true} + new(:run_in, members.freeze, nil) + end + end + end + + def initialize(kind, bytes, items) + @kind = kind + @bytes = bytes + @items = items + @n_items = items ? items.size : 0 + end + + # The stop bytes of a :run_except pattern, as one-byte Strings. + attr_reader :items + + # The number of bytes at the end of +string+ that a :byte_run or + # :run_in pattern matches, as /[...]+\z/ would, or 0. + def trailing_length(string) + size = string.bytesize + i = size + if @kind == :byte_run + byte = @bytes + i -= 1 while i > 0 and string.getbyte(i - 1) == byte + else + members = @bytes + i -= 1 while i > 0 and members[string.getbyte(i - 1)] + end + size - i + end + + # The number of bytes the pattern matches at +pos+ in +string+, or nil, + # for every kind but :run_except, which ByteScanner answers. + # Like the regular expressions it replaces, it matches nothing at the + # end of the String: String#getbyte answers nil there. + def match_length(string, pos) + kind = @kind + if kind == :byte + match_byte(string, pos) + elsif kind == :byte_run + match_byte_run(string, pos) + elsif kind == :byte_until + match_byte_until(string, pos) + elsif kind == :run_in + match_run_in(string, pos) + elsif kind == :literal + match_literal(string, pos) + else + match_alternation(string, pos) + end + end + + private + + def match_byte(string, pos) + string.getbyte(pos) == @bytes ? 1 : nil + end + + def match_byte_run(string, pos) + byte = @bytes + return nil unless string.getbyte(pos) == byte + i = pos + 1 + i += 1 while string.getbyte(i) == byte + i - pos + end + + # With one stop byte the search ends where the match ends, so the + # String is read once however many values it has. + def match_byte_until(string, pos) + stop = string.byteindex(@bytes, pos) + length = (stop || string.bytesize) - pos + length > 0 ? length : nil + end + + def match_run_in(string, pos) + members = @bytes + i = pos + while (byte = string.getbyte(i)) and members[byte] + i += 1 + end + length = i - pos + length > 0 ? length : nil + end + + def match_literal(string, pos) + bytes = @bytes + size = bytes.size + return nil if size.zero? + i = 0 + while i < size + return nil unless string.getbyte(pos + i) == bytes[i] + i += 1 + end + size + end + + def match_alternation(string, pos) + j = 0 + while j < @n_items + bytes = @items[j] + size = bytes.size + i = 0 + i += 1 while i < size and string.getbyte(pos + i) == bytes[i] + return size if i == size + j += 1 + end + nil + end + end + + # The part of StringScanner that CSV::Parser uses, in Ruby. #scan and + # #check take a BytePattern. + class ByteScanner + attr_reader :string + attr_reader :pos + + def initialize(string) + @string = string + @size = string.bytesize + @pos = 0 + @run_pattern = nil + @run_stops = nil + @run_positions = nil + @run_last = 0 + @run_short = true + end + + def pos=(position) + size = @size + position += size if position < 0 + raise RangeError, "index out of range" if position < 0 or position > size + # The kept run_except positions hold only while the scan moves on. + @run_pattern = nil if position < @pos + @pos = position + end + + def skip(pattern) + string = @string + pos = @pos + kind = pattern.kind + if kind == :byte + return nil unless string.getbyte(pos) == pattern.bytes + length = 1 + elsif kind == :byte_run + byte = pattern.bytes + return nil unless string.getbyte(pos) == byte + i = pos + 1 + i += 1 while string.getbyte(i) == byte + length = i - pos + elsif kind == :byte_until + stop = string.byteindex(pattern.bytes, pos) + length = (stop || @size) - pos + return nil unless length > 0 + elsif kind == :run_except + length = run_except_length(pattern, pos) + return nil unless length + else + length = pattern.match_length(string, pos) + return nil unless length + end + @pos = pos + length + length + end + + def scan(pattern) + string = @string + pos = @pos + kind = pattern.kind + if kind == :run_except + # Most values are short: look at their first bytes before the + # kept positions, which cost a search for each value. + # After a long value the search goes first. + if @run_short + table = pattern.bytes + i = pos + limit = pos + 8 + while i < limit and (byte = string.getbyte(i)) + break if table[byte] + i += 1 + end + if i < limit + return nil if i == pos + @pos = i + return string.byteslice(pos, i - pos) + end + end + positions = @run_positions + positions = run_start(pattern) unless pattern.equal?(@run_pattern) + nearest = positions[0] + if nearest < pos + stops = @run_stops + size = @size + last = @run_last + while nearest < pos + stop = stops[0] + position = string.byteindex(stop, pos) || size + k = 0 + while k < last and (next_position = positions[k + 1]) < position + positions[k] = next_position + stops[k] = stops[k + 1] + k += 1 + end + positions[k] = position + stops[k] = stop + nearest = positions[0] + end + end + length = nearest - pos + @run_short = length < 8 + return nil unless length > 0 + elsif kind == :byte_until + stop = string.byteindex(pattern.bytes, pos) + length = (stop || @size) - pos + return nil unless length > 0 + else + length = pattern.match_length(string, pos) + return nil unless length + end + @pos = pos + length + string.byteslice(pos, length) + end + + def check(pattern) + if pattern.kind == :run_except + length = run_except_length(pattern, @pos) + else + length = pattern.match_length(@string, @pos) + end + length and @string.byteslice(@pos, length) + end + + # Appends to +values+ each value that +pattern+, a :run_except + # pattern, scans up to the byte +separator+, or nil for an empty + # value, and moves past the separator. Stops before the first value + # that ends some other way: at a quote, a new line or the end of the + # String. Returns the number of values appended. + def scan_separated(pattern, separator, values) + string = @string + table = pattern.bytes + pos = @pos + short = @run_short + n = 0 + while true + i = pos + if short + limit = pos + 8 + while i < limit and (byte = string.getbyte(i)) + break if table[byte] + i += 1 + end + end + if i == pos + 8 or not short + i = pos + (run_except_length(pattern, pos) || 0) + byte = string.getbyte(i) + short = i - pos < 8 + end + break unless byte == separator + values << (i == pos ? nil : string.byteslice(pos, i - pos)) + pos = i + 1 + n += 1 + end + @run_short = short + @pos = pos + n + end + + def eos? + @pos >= @size + end + + def rest + @string.byteslice(@pos, @size - @pos) + end + + def inspect + "#<#{self.class} #{@pos}/#{@string.bytesize}>" + end + + private + + # A :run_except pattern's stop bytes are found with String#byteindex, + # a byte search with no regular expression. The stops are kept in + # order of their next position, so when the scan passes the nearest + # one, only that one is searched again and moved back to its place, + # usually with one comparison. The String is searched once per stop + # byte however many values it has, and a stop byte that never appears + # costs one search, not one per value. The positions are kept for the + # last pattern scanned, while the scan does not move back. + def run_except_length(pattern, pos) + positions = @run_positions + positions = run_start(pattern) unless pattern.equal?(@run_pattern) + nearest = positions[0] + nearest = run_advance(pos) if nearest < pos + length = nearest - pos + length > 0 ? length : nil + end + + def run_start(pattern) + items = pattern.items + @run_pattern = pattern + @run_stops = items.dup + @run_last = items.size - 1 + @run_positions = Array.new(items.size, -1) + end + + # Its own method so that ZJIT profiles the search loop when it runs, + # not only on the first scans, which often find the nearest stop still + # ahead. + def run_advance(pos) + string = @string + size = @size + positions = @run_positions + stops = @run_stops + last = @run_last + nearest = positions[0] + while nearest < pos + stop = stops[0] + position = string.byteindex(stop, pos) || size + i = 0 + while i < last and (next_position = positions[i + 1]) < position + positions[i] = next_position + stops[i] = stops[i + 1] + i += 1 + end + positions[i] = position + stops[i] = stop + nearest = positions[0] + end + nearest + end + end + end +end diff --git a/lib/csv/parser.rb b/lib/csv/parser.rb index f14be3af..7eaa219e 100644 --- a/lib/csv/parser.rb +++ b/lib/csv/parser.rb @@ -2,6 +2,7 @@ require "strscan" +require_relative "byte_scanner" require_relative "input_record_separator" require_relative "row" require_relative "table" @@ -49,14 +50,7 @@ class UnexpectedError < StandardError # on the methods. For more information, please visit: # https://docs.ruby-lang.org/en/master/StringScanner.html # - class Scanner < StringScanner - alias_method :scan_all, :scan - - def initialize(*args) - super - @keeps = [] - end - + module ScannerKeeps def each_line(row_separator) position = pos rest.each_line(row_separator) do |line| @@ -84,6 +78,40 @@ def keep_drop end end + class Scanner < StringScanner + include ScannerKeeps + alias_method :scan_all, :scan + alias_method :skip_all, :skip + + def initialize(*args) + super + @keeps = [] + end + end + + # CSV::Parser::Scanner on ByteScanner, which scans with BytePattern in + # Ruby instead of StringScanner and regular expressions. + class ByteKeepScanner < ByteScanner + include ScannerKeeps + alias_method :scan_all, :scan + alias_method :skip_all, :skip + + def initialize(*args) + super + @keeps = [] + end + + # The lines only move the position on, so it is set as it is. + def each_line(row_separator) + position = @pos + rest.each_line(row_separator) do |line| + position += line.bytesize + @pos = position + yield(line) + end + end + end + # # CSV::InputsScanner receives IO inputs, encoding and the chunk_size. # It also controls the life cycle of the object with its methods +keep_start+, @@ -97,8 +125,10 @@ def keep_drop # If there is no more data (eos? = true), it returns "". # class InputsScanner - def initialize(inputs, encoding, row_separator, chunk_size: 8192) + def initialize(inputs, encoding, row_separator, chunk_size: 8192, + scanner_class: StringScanner) @inputs = inputs.dup + @scanner_class = scanner_class @encoding = encoding @row_separator = row_separator @chunk_size = chunk_size @@ -180,6 +210,24 @@ def scan_all(pattern) value end + def skip(pattern) + length = @scanner.skip(pattern) + return length if @last_scanner + + read_chunk if length and @scanner.eos? + length + end + + def skip_all(pattern) + length = @scanner.skip(pattern) + return length if @last_scanner + return nil if length.nil? + while @scanner.eos? and read_chunk and (sub_length = @scanner.skip(pattern)) + length += sub_length + end + length + end + def eos? @last_scanner and @scanner.eos? end @@ -223,7 +271,7 @@ def keep_back @inputs.unshift(StringIO.new(keep)) @last_scanner = false end - @scanner = StringScanner.new(buffer) + @scanner = @scanner_class.new(buffer) else if @scanner != scanner message = "scanners are different but no buffer: " @@ -315,7 +363,7 @@ def read_chunk string = input.read raise InvalidEncoding unless string.valid_encoding? # trace(__method__, :stringio, string) - @scanner = StringScanner.new(string) + @scanner = @scanner_class.new(string) @inputs.shift @last_scanner = @inputs.empty? true @@ -324,7 +372,7 @@ def read_chunk if chunk raise InvalidEncoding unless chunk.valid_encoding? # trace(__method__, :chunk, chunk) - @scanner = StringScanner.new(chunk) + @scanner = @scanner_class.new(chunk) if Parser.eof?(input) @inputs.shift @last_scanner = @inputs.empty? @@ -332,7 +380,7 @@ def read_chunk true else # trace(__method__, :no_chunk) - @scanner = StringScanner.new("".encode(@encoding)) + @scanner = @scanner_class.new("".encode(@encoding)) @inputs.shift @last_scanner = @inputs.empty? if @last_scanner @@ -463,8 +511,12 @@ def prepare prepare_strip prepare_separators validate_strip_and_col_sep_options - prepare_quoted - prepare_unquoted + @byte_scanning = byte_scannable? + if @byte_scanning + prepare_byte_scanning + else + prepare_patterns + end prepare_line prepare_header prepare_parser @@ -506,7 +558,7 @@ def prepare_quote_character raise ArgumentError, message end @escaped_quote_character = Regexp.escape(@quote_character) - @escaped_quote = Regexp.new(@escaped_quote_character) + @quote_character_bytesize = @quote_character.bytesize end end @@ -516,7 +568,6 @@ def prepare_backslash @backslash_character = "\\".encode(@encoding) @escaped_backslash_character = Regexp.escape(@backslash_character) - @escaped_backslash = Regexp.new(@escaped_backslash_character) if @quote_character.nil? @backslash_quote_character = nil else @@ -558,19 +609,22 @@ def prepare_strip end @strip = @strip.encode(@encoding) @escaped_strip = Regexp.escape(@strip) - if @quote_character - @strip_value = Regexp.new(@escaped_strip + - "+".encode(@encoding)) - @rstrip_value = Regexp.new(@escaped_strip + - "+\\z".encode(@encoding)) - end elsif @strip - strip_values = " \t\f\v" - @escaped_strip = strip_values.encode(@encoding) - if @quote_character - @strip_value = Regexp.new("[#{strip_values}]+".encode(@encoding)) - @rstrip_value = Regexp.new("[#{strip_values}]+\\z".encode(@encoding)) - end + @escaped_strip = STRIP_VALUES.encode(@encoding) + end + end + + STRIP_VALUES = " \t\f\v" + + def prepare_strip_patterns + return unless @quote_character + + if @strip.is_a?(String) + @strip_value = Regexp.new(@escaped_strip + "+".encode(@encoding)) + @rstrip_value = Regexp.new(@escaped_strip + "+\\z".encode(@encoding)) + elsif @strip + @strip_value = Regexp.new("[#{STRIP_VALUES}]+".encode(@encoding)) + @rstrip_value = Regexp.new("[#{STRIP_VALUES}]+\\z".encode(@encoding)) end end @@ -595,6 +649,11 @@ def prepare_separators @escaped_column_separator = Regexp.escape(@column_separator) @escaped_first_column_separator = Regexp.escape(@column_separator[0]) + @cr = "\r".encode(@encoding) + @lf = "\n".encode(@encoding) + end + + def prepare_separator_patterns if @column_separator.size > 1 @column_end = Regexp.new(@escaped_column_separator) @column_ends = @column_separator.each_char.collect do |char| @@ -622,8 +681,6 @@ def prepare_separators @row_ends = nil end - @cr = "\r".encode(@encoding) - @lf = "\n".encode(@encoding) @line_end = Regexp.new("\r\n|\n|\r".encode(@encoding)) @not_line_end = Regexp.new("[^\r\n]+".encode(@encoding)) end @@ -642,7 +699,8 @@ def validate_strip_and_col_sep_options "col_sep (#{@escaped_column_separator}) options are incompatible." end else - if Regexp.new("\\A[#{@escaped_strip}]|[#{@escaped_strip}]\\z").match?(@column_separator) + if @escaped_strip.include?(@column_separator[0]) or + @escaped_strip.include?(@column_separator[-1]) raise ArgumentError, "The provided strip (true) and " \ "col_sep (#{@escaped_column_separator}) options are incompatible." @@ -650,8 +708,21 @@ def validate_strip_and_col_sep_options end end + # Regexp patterns, for the StringScanner path. prepare_byte_scanning + # builds BytePatterns instead. + def prepare_patterns + prepare_strip_patterns + prepare_separator_patterns + prepare_quoted + prepare_unquoted + end + def prepare_quoted + if @backslash_quote + @escaped_backslash = Regexp.new(@escaped_backslash_character) + end if @quote_character + @escaped_quote = Regexp.new(@escaped_quote_character) @quotes = Regexp.new(@escaped_quote_character + "+".encode(@encoding)) no_quoted_values = @escaped_quote_character.dup @@ -760,6 +831,122 @@ def prepare_line @scanner = nil end + BYTE_SCANNABLE_ENCODINGS = [ + Encoding::UTF_8, + Encoding::US_ASCII, + Encoding::ASCII_8BIT, + ].freeze + BYTE_SCANNER_DISABLED = (ENV["CSV_PARSER_BYTE_SCANNER"] == "no") + + # Whether every pattern can be answered by BytePattern: the patterns + # are made of ASCII characters only, and in these encodings an ASCII + # byte is always an ASCII character. + def byte_scannable? + return false if BYTE_SCANNER_DISABLED + return false unless BytePattern::BYTEINDEX_AVAILABLE + return false unless BYTE_SCANNABLE_ENCODINGS.include?(@encoding) + # Without a quote character, strip: true splits with + # / \t\f\v*SEP \t\f\v*/, not a character class, so it rarely splits. + # The StringScanner path keeps that behavior. + return false if @quote_character.nil? and @strip == true + [ + @column_separator, + @row_separator, + @quote_character, + (@strip if @strip.is_a?(String)), + ].all? {|value| value.nil? or value.ascii_only?} + end + + # Builds the BytePatterns that stand for the Regexp patterns of + # prepare_patterns, so that no Regexp runs over the input. + def prepare_byte_scanning + @separated_value_end = nil + @column_end = BytePattern.literal(@column_separator) + if @column_separator.size > 1 + @column_ends = @column_separator.each_char.collect do |char| + BytePattern.literal(char) + end + @first_column_separators = BytePattern.run_in(@column_separator[0]) + end + @row_end = BytePattern.literal(@row_separator) + if @row_separator.size > 1 + @row_ends = @row_separator.each_char.collect do |char| + BytePattern.literal(char) + end + end + @line_end = BytePattern.alternation(["\r\n", "\n", "\r"]) + @not_line_end = BytePattern.run_except("\r\n") + + if @quote_character + @escaped_quote = BytePattern.literal(@quote_character) + @quotes = BytePattern.run_in(@quote_character) + no_quoted_values = @quote_character.dup + no_quoted_values << @backslash_character if @backslash_quote + @quoted_value = BytePattern.run_except(no_quoted_values) + + no_unquoted_values = @row_separator + @column_separator[0] + no_unquoted_values << @quote_character unless @liberal_parsing + @unquoted_value = BytePattern.run_except(no_unquoted_values) + + if @strip.is_a?(String) + @strip_value = BytePattern.run_in(@strip) + elsif @strip + @strip_value = BytePattern.run_in(STRIP_VALUES) + end + @rstrip_value = @strip_value + + # Plain values that end with a one-byte column separator need + # nothing of parse_column_value, so the robust loop takes a run + # of them in one call. + if @column_separator.bytesize == 1 and + not @liberal_parsing and + not @strip and + @unquoted_value.kind == :run_except + @separated_value_end = @column_separator.getbyte(0) + end + end + if @backslash_quote + @escaped_backslash = BytePattern.literal(@backslash_character) + end + + # String#split(" ") splits on runs of whitespace, and splitting + # around stripped separators needs a Regexp: split_line does both. + if @strip or @column_separator == " " + @split_column_separator = nil + if @strip.is_a?(String) + @split_strip = BytePattern.run_in(@strip) + elsif @strip + @split_strip = BytePattern.run_in(STRIP_VALUES) + end + else + @split_column_separator = @column_separator + end + end + + def split_line(line) + return [] if line.empty? + + separator = @column_separator + separator_size = separator.bytesize + strip = @split_strip + row = [] + pos = 0 + while true + stop = line.byteindex(separator, pos) + value = line.byteslice(pos, (stop || line.bytesize) - pos) + if strip + leading = strip.match_length(value, 0) + value = value.byteslice(leading, value.bytesize - leading) if leading + trailing = strip.trailing_length(value) + value = value.byteslice(0, value.bytesize - trailing) if trailing > 0 + end + row << value + break unless stop + pos = stop + separator_size + end + row + end + def last_line if @scanner @last_line ||= @scanner.keep_end @@ -880,7 +1067,8 @@ def build_scanner InputsScanner.new(inputs, @encoding, @row_separator, - chunk_size: chunk_size) + chunk_size: chunk_size, + scanner_class: inputs_scanner_class) end else def build_scanner @@ -899,17 +1087,22 @@ def build_scanner raise InvalidEncodingError.new(@encoding, @lineno + index + 1) end end - Scanner.new(string) + (@byte_scanning ? ByteKeepScanner : Scanner).new(string) else inputs = @samples.collect do |sample| StringIO.new(sample) end inputs << @input - InputsScanner.new(inputs, @encoding, @row_separator) + InputsScanner.new(inputs, @encoding, @row_separator, + scanner_class: inputs_scanner_class) end end end + def inputs_scanner_class + @byte_scanning ? ByteScanner : StringScanner + end + def skip_needless_lines return unless @skip_lines @@ -957,7 +1150,7 @@ def parse_no_quote(&block) row = [] else line = strip_value(line) - row = line.split(@split_column_separator, -1) + row = @split_column_separator ? line.split(@split_column_separator, -1) : split_line(line) n_columns = row.size i = 0 while i < n_columns @@ -997,7 +1190,7 @@ def parse_quotable_loose(&block) @parse_method = :parse_quotable_robust return parse_quotable_robust(&block) else - row = line.split(@split_column_separator, -1) + row = @split_column_separator ? line.split(@split_column_separator, -1) : split_line(line) quoted_fields = [] n_columns = row.size i = 0 @@ -1039,15 +1232,21 @@ def parse_quotable_loose(&block) def parse_quotable_robust(&block) row = [] quoted_fields = [] + separator = @separated_value_end + separator = nil unless @scanner.is_a?(ByteKeepScanner) skip_needless_lines start_row while true @quoted_column_value = false @unquoted_column_value = false - @scanner.scan_all(@strip_value) if @strip_value + if separator + n = @scanner.scan_separated(@unquoted_value, separator, row) + quoted_fields.fill(false, quoted_fields.size, n) if n > 0 + end + @scanner.skip_all(@strip_value) if @strip_value value = parse_column_value if value - @scanner.scan_all(@strip_value) if @strip_value + @scanner.skip_all(@strip_value) if @strip_value end if parse_column_end row << value @@ -1109,7 +1308,7 @@ def parse_column_value if @liberal_parsing quoted_value = parse_quoted_column_value if quoted_value - @scanner.scan_all(@strip_value) if @strip_value + @scanner.skip_all(@strip_value) if @strip_value unquoted_value = parse_unquoted_column_value if unquoted_value if @double_quote_outside_quote @@ -1144,7 +1343,7 @@ def parse_unquoted_column_value while true @scanner.keep_start is_column_end = @column_ends.all? do |column_end| - @scanner.scan(column_end) + @scanner.skip(column_end) end @scanner.keep_back break if is_column_end @@ -1158,27 +1357,41 @@ def parse_unquoted_column_value end value.gsub!(@backslash_quote_character, @quote_character) if @backslash_quote if @rstrip_value - value.gsub!(@rstrip_value, "") + if @byte_scanning + length = @rstrip_value.trailing_length(value) + value.bytesplice(value.bytesize - length, length, "") if length > 0 + else + value.gsub!(@rstrip_value, "") + end end value end def parse_quoted_column_value - quotes = @scanner.scan_all(@quotes) - return nil unless quotes + n_quotes = @scanner.skip_all(@quotes) + return nil unless n_quotes @quoted_column_value = true - n_quotes = quotes.size - if (n_quotes % 2).zero? - quotes[0, (n_quotes - 2) / 2] + n_quotes /= @quote_character_bytesize + if (n_quotes % 2) == 0 + @quote_character * ((n_quotes - 2) / 2) else - value = quotes[0, n_quotes / 2] + # value stays nil until there is text, so that a value with no + # escaped quotes is the scanned String itself. + value = @quote_character * (n_quotes / 2) if n_quotes > 1 while true quoted_value = @scanner.scan_all(@quoted_value) - value << quoted_value if quoted_value + if quoted_value + if value + value << quoted_value + else + value = quoted_value + end + end if @backslash_quote - if @scanner.scan(@escaped_backslash) - if @scanner.scan(@escaped_quote) + if @scanner.skip(@escaped_backslash) + value ||= @quote_character * 0 + if @scanner.skip(@escaped_quote) value << @quote_character else value << @backslash_character @@ -1187,30 +1400,36 @@ def parse_quoted_column_value end end - quotes = @scanner.scan_all(@quotes) - unless quotes + n_quotes = @scanner.skip_all(@quotes) + unless n_quotes ignore_broken_line message = "Unclosed quoted field" raise MalformedCSVError.new(message, @lineno) end - n_quotes = quotes.size + n_quotes /= @quote_character_bytesize if n_quotes == 1 break else - value << quotes[0, n_quotes / 2] + if value.nil? + value = @quote_character * (n_quotes / 2) + elsif n_quotes < 4 + value << @quote_character + else + value << @quote_character * (n_quotes / 2) + end break if (n_quotes % 2) == 1 end end - value + value || @quote_character * 0 end end def parse_column_end - return true if @scanner.scan(@column_end) + return true if @scanner.skip(@column_end) return false unless @column_ends @scanner.keep_start - if @column_ends.all? {|column_end| @scanner.scan(column_end)} + if @column_ends.all? {|column_end| @scanner.skip(column_end)} @scanner.keep_drop true else @@ -1220,10 +1439,10 @@ def parse_column_end end def parse_row_end - return true if @scanner.scan(@row_end) + return true if @scanner.skip(@row_end) return false unless @row_ends @scanner.keep_start - if @row_ends.all? {|row_end| @scanner.scan(row_end)} + if @row_ends.all? {|row_end| @scanner.skip(row_end)} @scanner.keep_drop true else @@ -1251,8 +1470,8 @@ def strip_value(value) end def ignore_broken_line - @scanner.scan_all(@not_line_end) - @scanner.scan_all(@line_end) + @scanner.skip_all(@not_line_end) + @scanner.skip_all(@line_end) @lineno += 1 end diff --git a/test/csv/parse/test_byte_scanner.rb b/test/csv/parse/test_byte_scanner.rb new file mode 100644 index 00000000..ae88bd9c --- /dev/null +++ b/test/csv/parse/test_byte_scanner.rb @@ -0,0 +1,121 @@ +require_relative "../helper" + +class TestCSVParseByteScanner < Test::Unit::TestCase + include CSVHelper + + BytePattern = CSV::Parser::BytePattern + ByteScanner = CSV::Parser::ByteScanner + + def setup + omit("String#byteindex is required") unless BytePattern::BYTEINDEX_AVAILABLE + end + + INPUTS = [ + "", + "abc", + "a,b,,c", + "\"a\"\"b\",c\r\nd", + "\r\n\n\r", + " x \t", + "日本語,\"語\"\n", + "a" * 40 + "," + "b" * 40, + ].freeze + + def assert_same_as_regexp(pattern, regexp) + INPUTS.each do |input| + input.bytesize.succ.times do |position| + next unless input.byteslice(0, position).valid_encoding? + expected = StringScanner.new(input) + expected.pos = position + actual = ByteScanner.new(input) + actual.pos = position + message = "#{regexp.inspect} at #{position} in #{input.inspect}" + assert_equal([expected.check(regexp), expected.skip(regexp)], + [actual.check(pattern), actual.skip(pattern)], + message) + expected.pos = position + actual.pos = position + assert_equal([expected.scan(regexp), expected.pos], + [actual.scan(pattern), actual.pos], + message) + end + end + end + + def test_literal_byte + assert_same_as_regexp(BytePattern.literal(","), /,/) + end + + def test_literal_bytes + assert_same_as_regexp(BytePattern.literal("\r\n"), /\r\n/) + end + + def test_alternation + assert_same_as_regexp(BytePattern.alternation(["\r\n", "\n", "\r"]), + /\r\n|\n|\r/) + end + + def test_run_in_byte + assert_same_as_regexp(BytePattern.run_in("\""), /"+/) + end + + def test_run_in_bytes + assert_same_as_regexp(BytePattern.run_in(" \t"), /[ \t]+/) + end + + def test_run_except_byte + assert_same_as_regexp(BytePattern.run_except("\""), /[^"]+/) + end + + def test_run_except_bytes + assert_same_as_regexp(BytePattern.run_except(",\"\r\n"), /[^,"\r\n]+/) + end + + def test_run_except_bytes_moving_back + pattern = BytePattern.run_except(",\n") + scanner = ByteScanner.new("ab,cd\nef") + assert_equal("ab", scanner.scan(pattern)) + scanner.pos = 3 + assert_equal("cd", scanner.scan(pattern)) + scanner.pos = 0 + assert_equal("ab", scanner.scan(pattern)) + scanner.pos = 6 + assert_equal("ef", scanner.scan(pattern)) + end + + def test_run_except_bytes_other_string + pattern = BytePattern.run_except(",\n") + assert_equal("abc", ByteScanner.new("abc,d").scan(pattern)) + assert_equal("x", ByteScanner.new("x\nyz").scan(pattern)) + end + + def test_scan_separated + pattern = BytePattern.run_except(",\"\r\n") + long = "b" * 20 + [ + ["a,b,,c\n", ["a", "b", nil], 5], + [",,", [nil, nil], 2], + ["#{long},x,#{long},\"q\"", [long, "x", long], 44], + ["x,#{long},,y", ["x", long, nil], 24], + ["abc", [], 0], + ].each do |input, expected_values, expected_pos| + scanner = ByteScanner.new(input) + values = [] + n = scanner.scan_separated(pattern, ",".ord, values) + assert_equal([expected_values, expected_values.size, expected_pos], + [values, n, scanner.pos], + input.inspect) + end + end + + def test_trailing_length + [[BytePattern.run_in(" "), / +\z/], + [BytePattern.run_in(" \t\f\v"), /[ \t\f\v]+\z/]].each do |pattern, regexp| + ["", "a", "a ", "a \t\v", " \f ", "日本 ", " a b"].each do |input| + expected = input[regexp]&.bytesize || 0 + assert_equal(expected, pattern.trailing_length(input), + "#{regexp.inspect} in #{input.inspect}") + end + end + end +end