Skip to content

Commit 9868bf4

Browse files
committed
Add support for Stream#each for enumerating chunks.
1 parent c24b059 commit 9868bf4

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/protocol/http/body/stream.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,22 @@ def readpartial(length, buffer = nil)
129129
read_partial(length, buffer) or raise EOFError, "End of file reached!"
130130
end
131131

132+
# Iterate over each chunk of data in the stream.
133+
#
134+
# @yields {|chunk| ...} Each chunk of data.
135+
def each(&block)
136+
return to_enum unless block_given?
137+
138+
if @buffer
139+
yield @buffer
140+
@buffer = nil
141+
end
142+
143+
while chunk = read_next
144+
yield chunk
145+
end
146+
end
147+
132148
# Read data from the stream without blocking if possible.
133149
def read_nonblock(length, buffer = nil, exception: nil)
134150
@buffer ||= read_next

test/protocol/http/body/stream.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,34 @@
159159
end
160160
end
161161

162+
with "#each" do
163+
it "can iterate over input" do
164+
chunks = []
165+
166+
stream.each do |chunk|
167+
chunks << chunk
168+
end
169+
170+
expect(chunks).to be == ["Hello", "World"]
171+
end
172+
173+
it "can iterate over input with buffer" do
174+
expect(stream.read(2)).to be == "He"
175+
176+
chunks = []
177+
178+
stream.each do |chunk|
179+
chunks << chunk
180+
end
181+
182+
expect(chunks).to be == ["llo", "World"]
183+
end
184+
185+
it "can return an enumerator" do
186+
expect(stream.each.to_a).to be == ["Hello", "World"]
187+
end
188+
end
189+
162190
with "#read_until" do
163191
it "can read until a pattern is encountered" do
164192
expect(stream.read_until("o")).to be == "Hello"

0 commit comments

Comments
 (0)