Skip to content

Commit 49b59af

Browse files
committed
Handling of reads at EOF, consistent with stdlib.
1 parent 968ba48 commit 49b59af

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

lib/io/stream/readable.rb

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,14 @@ def gets(separator = $/, limit = nil, chomp: false)
254254
end
255255

256256
# If we can't read any more data, we should return what we have:
257-
return consume_read_buffer unless fill_read_buffer
257+
# gets should return nil at EOF when no more data is available
258+
unless fill_read_buffer
259+
if @read_buffer.empty?
260+
return nil
261+
else
262+
return consume_read_buffer
263+
end
264+
end
258265
end
259266

260267
# If the index of the separator was beyond the limit:
@@ -358,12 +365,19 @@ def fill_read_buffer(size = @minimum_read_size)
358365
def consume_read_buffer(size = nil, buffer = nil)
359366
# If we are at done, and the read buffer is empty, we can't consume anything.
360367
if @done && @read_buffer.empty?
361-
# Clear the buffer even when returning nil
362368
if buffer
363369
buffer.clear
364370
buffer.force_encoding(Encoding::BINARY)
365371
end
366-
return nil
372+
373+
# When reading a specific size, return nil at EOF
374+
if size
375+
buffer = nil
376+
else
377+
buffer ||= String.new(encoding: Encoding::BINARY)
378+
end
379+
380+
return buffer
367381
end
368382

369383
result = nil

test/io/stream/buffered.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,7 @@ def before
714714
with "#close" do
715715
it "should close the stream" do
716716
server.close
717-
expect(client.read).to be_nil
717+
expect(client.read).to be == ""
718718

719719
expect(server.closed?).to be_truthy
720720
expect(client.closed?).to be_falsey

0 commit comments

Comments
 (0)