Skip to content

class IO::Sized
inherits IO

An IO that wraps another IO, setting a limit for the number of bytes that can be read.

io = IO::Memory.new "abcde"
sized = IO::Sized.new(io, read_size: 3)

sized.gets_to_end # => "abc"
sized.gets_to_end # => ""
io.gets_to_end    # => "de"

Class methods

.new(io : IO, read_size : Int, sync_close = false)

Creates a new IO::Sized which wraps io, and can read a maximum of read_size bytes. If sync_close is set, calling #close calls #close on the underlying IO.

View source

Methods

#close

Closes this IO.

IO defines this is a no-op method, but including types may override.

View source

#closed? : Bool

Returns true if this IO is closed.

IO defines returns false, but including types may override.

View source

#peek

Peeks into this IO, if possible.

It returns: - nil if this IO isn't peekable - an empty slice if it is, but EOF was reached - a non-empty slice if some data can be peeked

The returned bytes are only valid data until a next call to any method that reads from this IO is invoked.

By default this method returns nil, but IO implementations that provide buffering or wrap other IOs should override this method.

View source

#read(slice : Bytes)

Reads at most slice.size bytes from this IO into slice. Returns the number of bytes read, which is 0 if and only if there is no more data to read (so checking for 0 is the way to detect end of file).

io = IO::Memory.new "hello"
slice = Bytes.new(4)
io.read(slice) # => 4
slice          # => Bytes[104, 101, 108, 108]
io.read(slice) # => 1
slice          # => Bytes[111, 101, 108, 108]
io.read(slice) # => 0
View source

#read_byte

Reads a single byte from this IO. Returns nil if there is no more data to read.

io = IO::Memory.new "a"
io.read_byte # => 97
io.read_byte # => nil
View source

#read_remaining : UInt64

The number of remaining bytes to be read.

View source

#read_remaining=(read_remaining : UInt64)

The number of remaining bytes to be read.

View source

#skip(bytes_count) : Nil

View source

#sync_close=(sync_close : Bool)

If #sync_close? is true, closing this IO will close the underlying IO.

View source

#sync_close? : Bool

If #sync_close? is true, closing this IO will close the underlying IO.

View source

#write(slice : Bytes) : NoReturn

Writes the contents of slice into this IO.

io = IO::Memory.new
slice = Bytes.new(4) { |i| ('a'.ord + i).to_u8 }
io.write(slice)
io.to_s # => "abcd"
View source