class

BinaryParser

Inherits Reference / Object

BinaryParser for Crystal

class Parser < BinaryParser
  uint8 :value
end

io = IO::Memory.new(sizeof(UInt8))
io.write_bytes(42)
io.rewind
parser = Parser.new.load(io)

parser.value # 42

Class methods

from_io(io : IO, format : IO::ByteFormat)

Support for IO#read_bytes

Source

Instance methods

load(filename : String, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)

Load from file with filename

Source
load(io : IO, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)

Load from an IO object

Source
save(filename : String, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)

Save to file with filename

Source
to_io(io : IO, format : IO::ByteFormat)

Support for IO#write_bytes

Source
to_s(io : IO)

Convert to string

File.write("filename", parser)
Source
write(io : IO, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)

Write to an IO object

Source

Macros

array(name, opt)

Declare an array field

Argument:

  • name: Field name
  • opt: Options
    • :type: Element type, must respond to from_io
    • :count: Element size, can be a number for fixed size, or a symbol for variable size

Example:

# Fixed size
class Parser < BinaryParser
  array :arr, {type: UInt8, count: 10} # Array of 10 UInt8
end

# Variable size
class Parser < BinaryParser
  uint32 :size
  array :arr, {type: UInt8, count: :size}
end
Source
endian(type)

Define what endian to use. endian can be either :little or :big

This macro should be place at the top of class, and can only call zero or one time.

endian
Source
int16(name)

Declare a int16 field

int16 :value # name of field
Source
int32(name)

Declare a int32 field

int32 :value # name of field
Source
int64(name)

Declare a int64 field

int64 :value # name of field
Source
int8(name)

Declare a int8 field

int8 :value # name of field
Source
string(name, opt = {count: -1})

Declare a string field

Argument:

  • name: Field name
  • opt: Options
    • :count: Sting length, can be a number for fixed size, -1 for zero terminated, or a symbol for variable size

Example:

# Fixed size
class Parser < BinaryParser
  string :str, {count: 10} # Array of 10 UInt8
end

# Variable size
class Parser < BinaryParser
  uint32 :size
  string :str, {count: :size}
end
Source
type(name, klass)

Nested BinaryParser

Argument:

  • name: Field name
  • klass: Another BinaryParser

Example:

class InnerParser < BinaryParser
  uint8 :foo
end

class Parser < BinaryParser
  type :inner, InnerParser
end
Source
uint16(name)

Declare a uint16 field

uint16 :value # name of field
Source
uint32(name)

Declare a uint32 field

uint32 :value # name of field
Source
uint64(name)

Declare a uint64 field

uint64 :value # name of field
Source
uint8(name)

Declare a uint8 field

uint8 :value # name of field
Source

Nested types