From 8d362d72af2d10b1da2e2999775ab6e34c66af62 Mon Sep 17 00:00:00 2001 From: Stephen Paul Weber Date: Mon, 24 Aug 2020 17:06:03 -0400 Subject: [PATCH] Satisfy IO#readpartial API IO#readpartial allows for a second "outbuf" param which some streaming usages expect, so support it here to allow using response bodies anywhere IO can be. --- lib/http/connection.rb | 14 ++++++++------ spec/lib/http/connection_spec.rb | 8 ++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/http/connection.rb b/lib/http/connection.rb index 3e53c80f..ea37c6a1 100644 --- a/lib/http/connection.rb +++ b/lib/http/connection.rb @@ -83,17 +83,19 @@ def send_request(req) # # @return [String] data chunk # @return [nil] when no more data left - def readpartial(size = BUFFER_SIZE) + def readpartial(size = BUFFER_SIZE, outbuf = nil) return unless @pending_response chunk = @parser.read(size) - return chunk if chunk - finished = (read_more(size) == :eof) || @parser.finished? - chunk = @parser.read(size) - finish_response if finished + unless chunk + finished = (read_more(size) == :eof) || @parser.finished? + chunk = @parser.read(size) + finish_response if finished + end - chunk || "".b + chunk ||= "".b + outbuf ? outbuf.replace(chunk) : chunk end # Reads data from socket up until headers are loaded diff --git a/spec/lib/http/connection_spec.rb b/spec/lib/http/connection_spec.rb index d7c9c546..e743ad8e 100644 --- a/spec/lib/http/connection_spec.rb +++ b/spec/lib/http/connection_spec.rb @@ -62,5 +62,13 @@ end expect(buffer).to eq "1234567890" end + + it "fill outbuf when present" do + connection.read_headers! + outbuf = String.new + buffer = String.new + buffer << outbuf while connection.readpartial(2, outbuf) + expect(buffer).to eq "1234567890" + end end end