class Buffered
A buffered stream implementation that wraps an underlying IO object to provide efficient buffered reading and writing.
Definitions
def self.open(path, mode = "r+", **options)
Open a file and wrap it in a buffered stream.
Signature
-
parameter
path
String
The file path to open.
-
parameter
mode
String
The file mode (e.g., "r+", "w", "a").
-
parameter
options
Hash
Additional options passed to the stream constructor.
-
returns
IO::Stream::Buffered
A buffered stream wrapping the opened file.
Implementation
def self.open(path, mode = "r+", **options)
stream = self.new(::File.open(path, mode), **options)
return stream unless block_given?
begin
yield stream
ensure
stream.close
end
end
def self.wrap(io, **options)
Wrap an existing IO object in a buffered stream.
Signature
-
parameter
io
IO
The IO object to wrap.
-
parameter
options
Hash
Additional options passed to the stream constructor.
-
returns
IO::Stream::Buffered
A buffered stream wrapping the IO object.
Implementation
def self.wrap(io, **options)
if io.respond_to?(:buffered=)
io.buffered = false
elsif io.respond_to?(:sync=)
io.sync = true
end
stream = self.new(io, **options)
return stream unless block_given?
begin
yield stream
ensure
stream.close
end
end
def initialize(io, ...)
Initialize a new buffered stream.
Signature
-
parameter
io
IO
The underlying IO object to wrap.
Implementation
def initialize(io, ...)
super(...)
@io = io
if io.respond_to?(:timeout)
@timeout = io.timeout
else
@timeout = nil
end
end
attr :io
Signature
-
attribute
IO
The wrapped IO object.
def to_io
Get the underlying IO object.
Signature
-
returns
IO
The underlying IO object.
Implementation
def to_io
@io.to_io
end
def closed?
Check if the stream is closed.
Signature
-
returns
Boolean
True if the stream is closed.
Implementation
def closed?
@io.closed?
end
def close_read
Close the read end of the stream.
Implementation
def close_read
@io.close_read
end
def close_write
Close the write end of the stream.
Implementation
def close_write
super
ensure
@io.close_write
end
def readable?
Check if the stream is readable.
Signature
-
returns
Boolean
True if the stream is readable.
Implementation
def readable?
super && @io.readable?
end
def sysread(size, buffer)
Reads data from the underlying stream as efficiently as possible.
Implementation
def sysread(size, buffer)
# Come on Ruby, why couldn't this just return `nil`? EOF is not exceptional. Every file has one.
while true
result = @io.read_nonblock(size, buffer, exception: false)
case result
when :wait_readable
@io.wait_readable(@io.timeout) or raise ::IO::TimeoutError, "read timeout"
when :wait_writable
@io.wait_writable(@io.timeout) or raise ::IO::TimeoutError, "write timeout"
else
return result
end
end
rescue Errno::EBADF
raise ::IOError, "stream closed"
end