Skip to content

Commit

Permalink
Support output buffer in read_partial/readpartial.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Aug 20, 2024
1 parent a472da1 commit f755edc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
22 changes: 16 additions & 6 deletions lib/protocol/http/body/stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,22 @@ def read(length = nil, buffer = nil)
# Will avoid reading from the underlying stream if there is buffered data available.
#
# @parameter length [Integer] The maximum number of bytes to read.
def read_partial(length = nil)
def read_partial(length = nil, buffer = nil)
if @buffer
buffer = @buffer
@buffer = nil
if buffer
buffer.replace(@buffer)
else
buffer = @buffer
@buffer = nil
end
else
buffer = read_next
chunk = read_next

if buffer and chunk
buffer.replace(chunk)
else
buffer = chunk
end
end

if buffer and length
Expand All @@ -111,8 +121,8 @@ def read_partial(length = nil)
end

# Similar to {read_partial} but raises an `EOFError` if the stream is at EOF.
def readpartial(length)
read_partial(length) or raise EOFError, "End of file reached!"
def readpartial(length, buffer = nil)
read_partial(length, buffer) or raise EOFError, "End of file reached!"
end

# Read data from the stream without blocking if possible.
Expand Down
10 changes: 10 additions & 0 deletions test/protocol/http/body/stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,14 @@
expect(stream).to be(:closed?)
end
end

with 'IO.copy_stream' do
let(:output) {StringIO.new}

it "can copy input to output" do
::IO.copy_stream(stream, output)

expect(output.string).to be == "HelloWorld"
end
end
end

0 comments on commit f755edc

Please sign in to comment.