Skip to content

Commit

Permalink
Add support for Stream#each for enumerating chunks.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Nov 12, 2024
1 parent c24b059 commit 9868bf4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/protocol/http/body/stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ def readpartial(length, buffer = nil)
read_partial(length, buffer) or raise EOFError, "End of file reached!"
end

# Iterate over each chunk of data in the stream.
#
# @yields {|chunk| ...} Each chunk of data.
def each(&block)
return to_enum unless block_given?

if @buffer
yield @buffer
@buffer = nil
end

while chunk = read_next
yield chunk
end
end

# Read data from the stream without blocking if possible.
def read_nonblock(length, buffer = nil, exception: nil)
@buffer ||= read_next
Expand Down
28 changes: 28 additions & 0 deletions test/protocol/http/body/stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,34 @@
end
end

with "#each" do
it "can iterate over input" do
chunks = []

stream.each do |chunk|
chunks << chunk
end

expect(chunks).to be == ["Hello", "World"]
end

it "can iterate over input with buffer" do
expect(stream.read(2)).to be == "He"

chunks = []

stream.each do |chunk|
chunks << chunk
end

expect(chunks).to be == ["llo", "World"]
end

it "can return an enumerator" do
expect(stream.each.to_a).to be == ["Hello", "World"]
end
end

with "#read_until" do
it "can read until a pattern is encountered" do
expect(stream.read_until("o")).to be == "Hello"
Expand Down

0 comments on commit 9868bf4

Please sign in to comment.