Protocol::HTTP1SourceProtocolHTTP1BodyFixed

class Fixed

Represents a fixed length body.

Definitions

def initialize(connection, length)

Initialize the body with the given connection and length.

Signature

parameter connection Protocol::HTTP1::Connection

the connection to read the body from.

parameter length Integer

the length of the body.

Implementation

def initialize(connection, length)
	@connection = connection
	
	@length = length
	@remaining = length
end

attr :length

Signature

attribute Integer

the length of the body.

attr :remaining

Signature

attribute Integer

the remaining bytes to read.

def empty?

Signature

returns Boolean

true if the body is empty.

Implementation

def empty?
	@connection.nil? or @remaining == 0
end

def close(error = nil)

Close the connection.

Signature

parameter error Exception | Nil

the error that caused the connection to be closed, if any.

Implementation

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

def read

Read a chunk of data.

Signature

returns String | Nil

the next chunk of data.

raises EOFError

if the connection is closed before the expected length is read.

Implementation

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

def inspect

Signature

returns String

a human-readable representation of the body.

Implementation

def inspect
	"#<#{self.class} #{@length} bytes, #{@remaining} remaining, #{empty? ? 'finished' : 'reading'}>"
end

def as_json(...)

Signature

returns Hash

JSON representation for tracing and debugging.

Implementation

def as_json(...)
	super.merge(
		remaining: @remaining,
		state: @connection ? "open" : "closed"
	)
end