Skip to content

Commit

Permalink
Add each_line enumerator to IO class
Browse files Browse the repository at this point in the history
  • Loading branch information
ikatz-drizly committed Jan 25, 2020
1 parent 599bfd4 commit 59eb99b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/piperator/io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ def gets(separator = $INPUT_RECORD_SEPARATOR, _limit = nil)
read_with { @buffer.gets(separator) }
end

# Returns an enumerator of lines in the stream, without reading the entire stream into memory
#
# @return [Enumerator]
def each_line
Enumerator.new { |y| loop { y << gets&.gsub(/#{$INPUT_RECORD_SEPARATOR}$/, '') } }.lazy.take_while(&:itself).each
end

# Flush internal buffer until the last unread byte
def flush
if @buffer.pos == @buffer_read_pos
Expand Down
8 changes: 8 additions & 0 deletions spec/piperator/io_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@
end
end

describe '#each_line' do
subject { Piperator::IO.new(["foo\n", "bar\n", "baz\nbmp"].each) }

it 'return enumerated lines' do
expect(subject.each_line.to_a).to eq(["foo", "bar", "baz", "bmp"])
end
end

describe '#flush' do
subject { Piperator::IO.new(['a' * 16 * KILOBYTE].each) }
let(:flush_threshold) { Piperator::IO::FLUSH_THRESHOLD }
Expand Down

0 comments on commit 59eb99b

Please sign in to comment.