module Protocol::HTTP::Body::Stream::Reader

def read_partial(length = nil, buffer = nil)

@parameter length [Integer] The maximum number of bytes to read.

Will avoid reading from the underlying stream if there is buffered data available.

If the length is given, at most length bytes will be read. Otherwise, one chunk of data from the underlying stream will be read.

Read some bytes from the stream.
def read_partial(length = nil, buffer = nil)
	if @buffer
		if buffer
			buffer.replace(@buffer)
		else
			buffer = @buffer
		end
		@buffer = nil
	else
		if chunk = read_next
			if buffer
				buffer.replace(chunk)
			else
				buffer = chunk
			end
		else
			buffer&.clear
			buffer = nil
		end
	end
	
	if buffer and length
		if buffer.bytesize > length
			# This ensures the subsequent `slice!` works correctly.
			buffer.force_encoding(Encoding::BINARY)
			@buffer = buffer.byteslice(length, buffer.bytesize)
			buffer.slice!(length, buffer.bytesize)
		end
	end
	
	return buffer
end