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.

Direct Known Subclasses

Defined in:

shatter/data.cr

Instance Method Summary

Instance Method Detail

def read_angle : Float64 #

[View source]
def read_bool : Bool #

[View source]
def read_f32 : Float32 #

[View source]
def read_f64 : Float64 #

[View source]
def read_i16 : Int16 #

[View source]
def read_i32 : Int32 #

[View source]
def read_i64 : Int64 #

[View source]
def read_i8 : Int8 #

[View source]
def read_n_bytes(size : Int) : Bytes #

[View source]
def read_u16 : UInt16 #

[View source]
def read_u32 : UInt32 #

[View source]
def read_u64 : UInt64 #

[View source]
def read_u8 : UInt8 #

[View source]
def read_uuid : UUID #

[View source]
def read_var_int : UInt32 #

[View source]
def read_var_long : UInt64 #

[View source]
def read_var_string : String #

[View source]
def write_bool(i : Bool) : Nil #

[View source]
def write_f32(i : Float32) : Nil #

[View source]
def write_f64(i : Float64) : Nil #

[View source]
def write_i16(i : Int16) : Nil #

[View source]
def write_i32(i : Int32) : Nil #

[View source]
def write_i64(i : Int64) : Nil #

[View source]
def write_i8(i : Int8) : Nil #

[View source]
def write_u16(i : UInt16) : Nil #

[View source]
def write_u32(i : UInt32) : Nil #

[View source]
def write_u64(i : UInt64) : Nil #

[View source]
def write_u8(i : UInt8) : Nil #

[View source]
def write_var_int(value : Int32) : Nil #

[View source]
def write_var_int(value : UInt32) : Nil #

[View source]
def write_var_string(s : String) : Nil #

[View source]