class Protocol::HTTP1::Body::Fixed

Represents a fixed length body.

def as_json(...)

@returns [Hash] JSON representation for tracing and debugging.
def as_json(...)
	super.merge(
		remaining: @remaining,
		state: @connection ? "open" : "closed"
	)
end

def close(error = nil)

@parameter error [Exception | Nil] the error that caused the connection to be closed, if any.

Close the connection.
def close(error = nil)
	if connection = @connection
		@connection = nil
		
		unless @remaining == 0
			connection.close_read
		end
	end
	
	super
end

def empty?

@returns [Boolean] true if the body is empty.
def empty?
	@connection.nil? or @remaining == 0
end

def initialize(connection, length)

@parameter length [Integer] the length of the body.
@parameter connection [Protocol::HTTP1::Connection] the connection to read the body from.

Initialize the body with the given connection and length.
def initialize(connection, length)
	@connection = connection
	
	@length = length
	@remaining = length
end

def inspect

@returns [String] a human-readable representation of the body.
def inspect
	"#<#{self.class} #{@length} bytes, #{@remaining} remaining, #{empty? ? 'finished' : 'reading'}>"
end

def read

@raises [EOFError] if the connection is closed before the expected length is read.
@returns [String | Nil] the next chunk of data.

Read a chunk of data.
def read
	if @remaining > 0
		if @connection
			# `readpartial` will raise `EOFError` if the connection is finished, or `IOError` if the connection is closed.
			chunk = @connection.readpartial(@remaining)
			
			@remaining -= chunk.bytesize
			
			if @remaining == 0
				@connection.receive_end_stream!
				@connection = nil
			end
			
			return chunk
		end
		
		# If the connection has been closed before we have read the expected length, raise an error:
		raise EOFError, "connection closed before expected length was read!"
	end
end