Skip to content

Commit

Permalink
Avoid force encodings on frozen strings (#653)
Browse files Browse the repository at this point in the history
  • Loading branch information
bvicenzo authored Aug 18, 2021
1 parent f99e287 commit 2df5e46
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
10 changes: 6 additions & 4 deletions lib/http/response/body.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ def initialize(stream, encoding: Encoding::BINARY)
# (see HTTP::Client#readpartial)
def readpartial(*args)
stream!
@stream.readpartial(*args)&.force_encoding(@encoding)
chunk = @stream.readpartial(*args)

String.new(chunk, :encoding => @encoding) if chunk
end

# Iterate over the body, allowing it to be enumerable
Expand All @@ -45,11 +47,11 @@ def to_s

begin
@streaming = false
@contents = String.new("").force_encoding(@encoding)
@contents = String.new("", :encoding => @encoding)

while (chunk = @stream.readpartial)
@contents << chunk.force_encoding(@encoding)
chunk.clear # deallocate string
@contents << String.new(chunk, :encoding => @encoding)
chunk = nil # deallocate string
end
rescue
@contents = nil
Expand Down
10 changes: 5 additions & 5 deletions spec/lib/http/response/body_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

RSpec.describe HTTP::Response::Body do
let(:connection) { double(:sequence_id => 0) }
let(:chunks) { [String.new("Hello, "), String.new("World!")] }
let(:chunks) { ["Hello, ", "World!"] }

before do
allow(connection).to receive(:readpartial) { chunks.shift }
Expand All @@ -16,7 +16,7 @@
end

context "when body empty" do
let(:chunks) { [String.new("")] }
let(:chunks) { [""] }

it "returns responds to empty? with true" do
expect(subject).to be_empty
Expand Down Expand Up @@ -45,12 +45,12 @@
it "returns content in specified encoding" do
body = described_class.new(connection)
expect(connection).to receive(:readpartial).
and_return(String.new("content").force_encoding(Encoding::UTF_8))
and_return(String.new("content", :encoding => Encoding::UTF_8))
expect(body.readpartial.encoding).to eq Encoding::BINARY

body = described_class.new(connection, :encoding => Encoding::UTF_8)
expect(connection).to receive(:readpartial).
and_return(String.new("content").force_encoding(Encoding::BINARY))
and_return(String.new("content", :encoding => Encoding::BINARY))
expect(body.readpartial.encoding).to eq Encoding::UTF_8
end
end
Expand All @@ -59,7 +59,7 @@
let(:chunks) do
body = Zlib::Deflate.deflate("Hi, HTTP here ☺")
len = body.length
[String.new(body[0, len / 2]), String.new(body[(len / 2)..-1])]
[body[0, len / 2], body[(len / 2)..-1]]
end
subject(:body) do
inflater = HTTP::Response::Inflater.new(connection)
Expand Down

0 comments on commit 2df5e46

Please sign in to comment.