lib/async/http/body.rb in async-http-0.17.1 vs lib/async/http/body.rb in async-http-0.18.0

- old
+ new

@@ -28,14 +28,21 @@ @finished = false @stopped = false end + # Read all chunks until the stream is closed. + def close + BufferedBody.for(self) + end + + # Have all chunks been read? def finished? @finished end + # Enumerate all chunks until finished. def each return to_enum unless block_given? return if @finished @@ -49,55 +56,69 @@ raise ensure @finished = true end + # Read the next available chunk. def read return if @finished unless chunk = @queue.dequeue @finished = true end return chunk end + # Read all remaining chunks into a single binary string. def join buffer = Async::IO::BinaryString.new self.each do |chunk| buffer << chunk end return buffer end + # Write a single chunk to the body. Signal completion by calling `#finish`. def write(chunk) if @stopped raise @stopped end # TODO should this yield if the queue is full? @queue.enqueue(chunk) end + # Signal that output has finished. def finish @queue.enqueue(nil) end end class BufferedBody - def initialize(body) - @chunks = [] - @index = 0 + def self.for(body) + chunks = [] body.each do |chunk| - @chunks << chunk + chunks << chunk end + + self.new(chunks) end + def initialize(chunks) + @chunks = chunks + @index = 0 + end + + def close + self + end + def each(&block) while @index < @chunks.count yield @chunks[@index] @index += 1 end @@ -133,25 +154,27 @@ def read self.body ? self.body.join : nil end def finish - return if self.body.nil? or self.body.finished? + return if self.body.nil? - unless self.body.is_a? BufferedBody - self.body = BufferedBody.new(self.body) - end + self.body = self.body.close end end end class ChunkedBody def initialize(protocol) @protocol = protocol @finished = false end + def close + BufferedBody.for(self) + end + def finished? @finished end def read @@ -197,9 +220,13 @@ class FixedBody def initialize(length, stream) @length = length @remaining = length @stream = stream + end + + def close + BufferedBody.for(self) end def finished? @remaining == 0 end