File: body_reader.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (45 lines) | stat: -rw-r--r-- 957 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

require "stringio"

module HTTPX
  module Transcoder
    class BodyReader
      def initialize(body)
        @body = if body.respond_to?(:read)
          body.rewind if body.respond_to?(:rewind)
          body
        elsif body.respond_to?(:each)
          body.enum_for(:each)
        else
          StringIO.new(body.to_s)
        end
      end

      def bytesize
        return @body.bytesize if @body.respond_to?(:bytesize)

        Float::INFINITY
      end

      def read(length = nil, outbuf = nil)
        return @body.read(length, outbuf) if @body.respond_to?(:read)

        begin
          chunk = @body.next
          if outbuf
            outbuf.replace(chunk)
          else
            outbuf = chunk
          end
          outbuf unless length && outbuf.empty?
        rescue StopIteration
        end
      end

      def close
        @body.close if @body.respond_to?(:close)
      end
    end
  end
end