Async::IO SourceAsyncIOGeneric

class Generic

Represents an asynchronous IO within a reactor.

Nested

Definitions

def read(length = nil, buffer = nil)

Read length bytes of data from the underlying I/O. If length is unspecified, read everything.

Implementation

def read(length = nil, buffer = nil)
	if buffer
		buffer.clear
	else
		buffer = String.new
	end
	
	if length
		return String.new(encoding: Encoding::BINARY) if length <= 0
		
		# Fast path:
		if buffer = self.sysread(length, buffer)
			
			# Slow path:
			while buffer.bytesize < length
				# Slow path:
				if chunk = self.sysread(length - buffer.bytesize)
					buffer << chunk
				else
					break
				end
			end
			
			return buffer
		else
			return nil
		end
	else
		buffer = self.sysread(BLOCK_SIZE, buffer)
		
		while chunk = self.sysread(BLOCK_SIZE)
			buffer << chunk
		end
		
		return buffer
	end
end