Class: Protocol::HTTP1::Body::Fixed

Inherits:
HTTP::Body::Readable
  • Object
show all
Defined in:
lib/protocol/http1/body/fixed.rb

Overview

Represents a fixed length body.

Constant Summary collapse

BLOCK_SIZE =

The maximum amount of body data returned by a single read.

1024 * 64

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, length) ⇒ Fixed

Initialize the body with the given connection and length.



20
21
22
23
24
25
# File 'lib/protocol/http1/body/fixed.rb', line 20

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

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



28
29
30
# File 'lib/protocol/http1/body/fixed.rb', line 28

def length
  @length
end

#remainingObject (readonly)

Returns the value of attribute remaining.



31
32
33
# File 'lib/protocol/http1/body/fixed.rb', line 31

def remaining
  @remaining
end

#the length of the body.(lengthofthebody.) ⇒ Object (readonly)



28
# File 'lib/protocol/http1/body/fixed.rb', line 28

attr :length

#the remaining bytes to read.(remainingbytestoread.) ⇒ Object (readonly)



31
# File 'lib/protocol/http1/body/fixed.rb', line 31

attr :remaining

Instance Method Details

#as_jsonObject



84
85
86
87
88
89
# File 'lib/protocol/http1/body/fixed.rb', line 84

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

#close(error = nil) ⇒ Object

Close the connection.



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/protocol/http1/body/fixed.rb', line 41

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

#empty?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/protocol/http1/body/fixed.rb', line 34

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

#inspectObject



79
80
81
# File 'lib/protocol/http1/body/fixed.rb', line 79

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

#readObject

Read a chunk of data.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/protocol/http1/body/fixed.rb', line 57

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, BLOCK_SIZE].min)
			
			@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