abstract class IO

Overview

The IO class is the basis for all input and output in Crystal.

This class is inherited by types like File, Socket and IO::Memory and provides many useful methods for reading from and writing to an IO, like print, puts, gets and printf.

The only requirement for a type including the IO module is to define these two methods:

For example, this is a simple IO on top of a Bytes:

class SimpleSliceIO < IO
  def initialize(@slice : Bytes)
  end

  def read(slice : Bytes)
    slice.size.times { |i| slice[i] = @slice[i] }
    @slice += slice.size
    slice.size
  end

  def write(slice : Bytes) : Nil
    slice.size.times { |i| @slice[i] = slice[i] }
    @slice += slice.size
  end
end

slice = Slice.new(9) { |i| ('a'.ord + i).to_u8 }
String.new(slice) # => "abcdefghi"

io = SimpleSliceIO.new(slice)
io.gets(3) # => "abc"
io.print "xyz"
String.new(slice) # => "abcxyzghi"

Encoding

An IO can be set an encoding with the #set_encoding method. When this is set, all string operations (gets, gets_to_end, read_char, <<, print, puts printf) will write in the given encoding, and read from the given encoding. Byte operations (read, write, read_byte, write_byte, getb_to_end) never do encoding/decoding operations.

If an encoding is not set, the default one is UTF-8.

Mixing string and byte operations might not give correct results and should be avoided, as string operations might need to read extra bytes in order to get characters in the given encoding.

Defined in:

lib/libremiliacr/src/remilib/console/ansi.cr
lib/libremiliacr/src/remilib/extensions.cr
lib/remiaudio/src/remiaudio/common.cr
haematite/ioext.cr

Instance Method Summary

Instance Method Detail

def readFixedLengthStr(count) : String #

def readFourCC : String #

Attempts to read a "four CC" string from the IO, as used in RIFF formats. If four bytes cannot be read, this returns nil.


def readInt16 : Int16 #

Convenience method to read a signed 16-bit little-endian integer.

This is the same as calling read_bytes(Int16, IO::ByteFormat::LittleEndian), just shorter.


def readInt32 : Int32 #

Convenience method to read a signed 32-bit little-endian integer.

This is the same as calling read_bytes(Int32, IO::ByteFormat::LittleEndian), just shorter.


def readInt8 : Int8 #

Convenience method to read a signed 8-bit byte. If the byte cannot be read, this will raise an IO::EOFError.

This is the same as calling io.read_byte.try &.to_i8! || raise IO::EOFError.new, just shorter.


def readIntVarLength : Int64 #

def readUInt16 : UInt16 #

Convenience method to read a signed 16-bit little-endian integer.

This is the same as calling read_bytes(UInt16, IO::ByteFormat::LittleEndian), just shorter.