Skip to content

Commit

Permalink
eof? can and does block, so let's avoid it.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jan 26, 2024
1 parent 07323c9 commit ad93116
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
8 changes: 7 additions & 1 deletion lib/protocol/http1/body/remainder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ class Remainder < HTTP::Body::Readable
# block_size may be removed in the future. It is better managed by stream.
def initialize(stream)
@stream = stream
@empty = false
end

def empty?
@stream.eof? or @stream.closed?
@empty or @stream.closed?
end

def close(error = nil)
# We can't really do anything in this case except close the connection.
@stream.close
@empty = true

super
end
Expand All @@ -31,6 +33,8 @@ def close(error = nil)
def read
@stream.readpartial(BLOCK_SIZE)
rescue EOFError, IOError
@empty = true

# I noticed that in some cases you will get EOFError, and in other cases IOError!?
return nil
end
Expand All @@ -45,6 +49,8 @@ def call(stream)

def join
@stream.read
ensure
@empty = true
end

def inspect
Expand Down
14 changes: 6 additions & 8 deletions test/protocol/http1/body/remainder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@

with "#read" do
it "retrieves chunks of content" do
expect(body).not.to be(:empty?)

expect(body.read).to be == "Hello World"
expect(body.read).to be == nil
end

it "updates number of bytes retrieved" do
body.read

expect(body).to be(:empty?)
end
end
Expand All @@ -57,12 +56,11 @@

with "#join" do
it "returns all content" do
expect(body).not.to be(:empty?)

expect(body.join).to be == "Hello World"
expect(body.join).to be == ""
end

it "updates number of bytes retrieved" do
body.read

expect(body).to be(:empty?)
end
end
Expand Down

0 comments on commit ad93116

Please sign in to comment.