class HTTPX::Response::Body
def ==(other)
def ==(other) to_s == other.to_s end
def bytesize
def bytesize @length end
def close
def close return if @state == :idle @buffer.close @buffer.unlink if @buffer.respond_to?(:unlink) @buffer = nil @length = 0 @state = :idle end
def copy_to(dest)
def copy_to(dest) return unless @buffer if dest.respond_to?(:path) && @buffer.respond_to?(:path) FileUtils.mv(@buffer.path, dest.path) else @buffer.rewind ::IO.copy_stream(@buffer, dest) end end
def each
def each return enum_for(__method__) unless block_given? begin unless @state == :idle rewind while (chunk = @buffer.read(@window_size)) yield(chunk.force_encoding(@encoding)) end end ensure close end end
def empty?
def empty? @length.zero? end
def initialize(response, threshold_size:, window_size: 1 << 14)
def initialize(response, threshold_size:, window_size: 1 << 14) @response = response @headers = response.headers @threshold_size = threshold_size @window_size = window_size @encoding = response.content_type.charset || Encoding::BINARY @length = 0 @buffer = nil @state = :idle end
def inspect
def inspect "#<HTTPX::Response::Body:#{object_id} " \ "@state=#{@state} " \ "@length=#{@length}>" end
def read(*args)
def read(*args) return unless @buffer @buffer.read(*args) end
def rewind
def rewind return if @state == :idle @buffer.rewind end
def to_s
def to_s rewind if @buffer content = @buffer.read begin return content.force_encoding(@encoding) rescue ArgumentError # ex: unknown encoding name - utf return content end end "".b ensure close end
def transition
def transition case @state when :idle if @length > @threshold_size @state = :buffer @buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR) else @state = :memory @buffer = StringIO.new("".b, File::RDWR) end when :memory if @length > @threshold_size aux = @buffer @buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR) aux.rewind ::IO.copy_stream(aux, @buffer) # (this looks like a bug from Ruby < 2.3 @buffer.pos = aux.pos ################## ######################################## aux.close @state = :buffer end end return unless %i[memory buffer].include?(@state) end
def write(chunk)
def write(chunk) @length += chunk.bytesize transition @buffer.write(chunk) end