class Falcon::Adapters::Input

def read(length = nil, buffer = nil)

@returns a buffer containing the data
@parameter buffer [String] the buffer which will receive the data
@parameter length [Integer] the amount of data to read

`read` behaves like `IO#read`. Its signature is `read(length = nil, buffer = nil)`. If given, length must be a non-negative `Integer` (>= 0) or `nil`, and buffer must be a `String` and may not be nil. If `length` is given and not `nil`, then this method reads at most `length` bytes from the input stream. If `length` is not given or `nil`, then this method reads all data. When the end is reached, this method returns `nil` if `length` is given and not `nil`, or an empty `String` if `length` is not given or is `nil`. If `buffer` is given, then the read data will be placed into the `buffer` instead of a newly created `String` object.

Read data from the input stream.
def read(length = nil, buffer = nil)
	buffer ||= Async::IO::Buffer.new
	buffer.clear
	
	until buffer.bytesize == length
		@buffer = read_next if @buffer.nil?
		break if @buffer.nil?
		
		remaining_length = length - buffer.bytesize if length
		
		if remaining_length && remaining_length < @buffer.bytesize
			# We know that we are not going to reuse the original buffer.
			# But byteslice will generate a hidden copy. So let's freeze it first:
			@buffer.freeze
			
			buffer << @buffer.byteslice(0, remaining_length)
			@buffer = @buffer.byteslice(remaining_length, @buffer.bytesize)
		else
			buffer << @buffer
			@buffer = nil
		end
	end
	
	return nil if buffer.empty? && length && length > 0
	
	return buffer
end