Skip to content

Commit c94763a

Browse files
authored
Don't use enumerator in CSV (#363)
GitHub: Fix GH-361 CSV::Parser#parse can continue from the previous state. Reported by Cas Donoghue. Thanks!!!
1 parent b36c160 commit c94763a

2 files changed

Lines changed: 11 additions & 34 deletions

File tree

lib/csv.rb

Lines changed: 5 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2110,8 +2110,6 @@ def initialize(data,
21102110
strip: strip,
21112111
}
21122112
@parser = nil
2113-
@parser_enumerator = nil
2114-
@eof_error = nil
21152113

21162114
@writer_options = {
21172115
encoding: @encoding,
@@ -2430,24 +2428,13 @@ def to_io
24302428
end
24312429

24322430
def eof?
2433-
return false if @eof_error
2434-
begin
2435-
parser_enumerator.peek
2436-
false
2437-
rescue MalformedCSVError => error
2438-
@eof_error = error
2439-
false
2440-
rescue StopIteration
2441-
true
2442-
end
2431+
parser.eof?
24432432
end
24442433
alias_method :eof, :eof?
24452434

24462435
# Rewinds the underlying IO object and resets CSV's lineno() counter.
24472436
def rewind
24482437
@parser = nil
2449-
@parser_enumerator = nil
2450-
@eof_error = nil
24512438
@writer.rewind if @writer
24522439
@io.rewind
24532440
end
@@ -2687,13 +2674,7 @@ def header_convert(name = nil, &converter)
26872674
# p row
26882675
# end
26892676
def each(&block)
2690-
return to_enum(__method__) unless block_given?
2691-
begin
2692-
while true
2693-
yield(parser_enumerator.next)
2694-
end
2695-
rescue StopIteration
2696-
end
2677+
parser.parse(&block)
26972678
end
26982679

26992680
# :call-seq:
@@ -2801,15 +2782,10 @@ def header_row?
28012782
# # Raises IOError (not opened for reading)
28022783
# csv.shift
28032784
def shift
2804-
if @eof_error
2805-
eof_error, @eof_error = @eof_error, nil
2806-
raise eof_error
2807-
end
2808-
begin
2809-
parser_enumerator.next
2810-
rescue StopIteration
2811-
nil
2785+
parser.parse do |row|
2786+
return row
28122787
end
2788+
nil
28132789
end
28142790
alias_method :gets, :shift
28152791
alias_method :readline, :shift
@@ -2971,10 +2947,6 @@ def parser_options
29712947
fields_converter: parser_fields_converter)
29722948
end
29732949

2974-
def parser_enumerator
2975-
@parser_enumerator ||= parser.parse
2976-
end
2977-
29782950
def writer
29792951
@writer ||= Writer.new(@io, writer_options)
29802952
end

lib/csv/parser.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def scan_all(pattern)
181181
end
182182

183183
def eos?
184-
@scanner.eos?
184+
@last_scanner and @scanner.eos?
185185
end
186186

187187
def keep_start
@@ -444,6 +444,11 @@ def parse(&block)
444444
end
445445
end
446446

447+
def eof?
448+
return false if @scanner.nil?
449+
@scanner.eos?
450+
end
451+
447452
def use_headers?
448453
@use_headers
449454
end

0 commit comments

Comments
 (0)