File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -129,6 +129,22 @@ def readpartial(length, buffer = nil)
129
129
read_partial ( length , buffer ) or raise EOFError , "End of file reached!"
130
130
end
131
131
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
+
132
148
# Read data from the stream without blocking if possible.
133
149
def read_nonblock ( length , buffer = nil , exception : nil )
134
150
@buffer ||= read_next
Original file line number Diff line number Diff line change 159
159
end
160
160
end
161
161
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
+
162
190
with "#read_until" do
163
191
it "can read until a pattern is encountered" do
164
192
expect ( stream . read_until ( "o" ) ) . to be == "Hello"
You can’t perform that action at this time.
0 commit comments