class Protocol::HTTP::Body::Buffered

A body which buffers all it’s contents.

def self.read(body)

@returns [Buffered] the buffered body.
@parameter body [Readable] the body to read.

Read the entire body into a buffered representation.
def self.read(body)
	chunks = []
	
	body.each do |chunk|
		chunks << chunk
	end
	
	self.new(chunks)
end

def self.wrap(object)

@returns [Readable | nil] the wrapped body or nil if nil was given.
@parameter body [String | Array(String) | Readable | nil] the body to wrap.

For compatibility, also accepts anything that behaves like an `Array(String)`.

Tries to wrap an object in a {Buffered} instance.
def self.wrap(object)
	if object.is_a?(Readable)
		return object
	elsif object.is_a?(Array)
		return self.new(object)
	elsif object.is_a?(String)
		return self.new([object])
	elsif object
		return self.read(object)
	end
end

def buffered

@returns [Buffered] the buffered body.

A rewindable body wraps some other body. Convert it to a buffered body. The buffered body will share the same chunks as the rewindable body.
def buffered
	self.class.new(@chunks)
end

def clear

def clear
	@chunks = []
	@length = 0
	@index = 0
end

def close(error = nil)

Ensure that future reads return nil, but allow for rewinding.
def close(error = nil)
	@index = @chunks.length
	
	return nil
end

def close_write(error)

def close_write(error)
	# Nothing to do.
end

def discard

def discard
	# It's safe to call close here because there is no underlying stream to close:
	self.close
end

def empty?

def empty?
	@index >= @chunks.length
end

def finish

def finish
	self
end

def initialize(chunks = [], length = nil)

def initialize(chunks = [], length = nil)
	@chunks = chunks
	@length = length
	
	@index = 0
end

def inspect

def inspect
	if @chunks
		"\#<#{self.class} #{@chunks.size} chunks, #{self.length} bytes>"
	end
end

def length

def length
	@length ||= @chunks.inject(0) {|sum, chunk| sum + chunk.bytesize}
end

def read

def read
	return nil unless @chunks
	
	if chunk = @chunks[@index]
		@index += 1
		
		return chunk.dup
	end
end

def ready?

A buffered response is always ready.
def ready?
	true
end

def rewind

def rewind
	return false unless @chunks
	
	@index = 0
	
	return true
end

def rewindable?

def rewindable?
	@chunks != nil
end

def write(chunk)

def write(chunk)
	@chunks << chunk
end