/
body.rb
87 lines (70 loc) · 2.17 KB
/
body.rb
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# frozen_string_literal: true
require "forwardable"
require "http/client"
module HTTP
class Response
# A streamable response body, also easily converted into a string
class Body
extend Forwardable
include Enumerable
def_delegator :to_s, :empty?
# The connection object used to make the corresponding request.
#
# @return [HTTP::Connection]
attr_reader :connection
def initialize(stream, encoding: Encoding::BINARY)
@stream = stream
@connection = stream.is_a?(Inflater) ? stream.connection : stream
@streaming = nil
@contents = nil
@encoding = find_encoding(encoding)
end
# (see HTTP::Client#readpartial)
def readpartial(*args)
stream!
chunk = @stream.readpartial(*args)
String.new(chunk, encoding: @encoding) if chunk
end
# Iterate over the body, allowing it to be enumerable
def each
while (chunk = readpartial)
yield chunk
end
end
# @return [String] eagerly consume the entire body as a string
def to_s
return @contents if @contents
raise StateError, "body is being streamed" unless @streaming.nil?
begin
@streaming = false
@contents = String.new("", encoding: @encoding)
while (chunk = @stream.readpartial)
@contents << String.new(chunk, encoding: @encoding)
chunk = nil # deallocate string
end
rescue
@contents = nil
raise
end
@contents
end
alias to_str to_s
# Assert that the body is actively being streamed
def stream!
raise StateError, "body has already been consumed" if @streaming == false
@streaming = true
end
# Easier to interpret string inspect
def inspect
"#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>"
end
private
# Retrieve encoding by name. If encoding cannot be found, default to binary.
def find_encoding(encoding)
Encoding.find encoding
rescue ArgumentError
Encoding::BINARY
end
end
end
end