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
Instance methods
load(filename : String, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)
Load from file with filename
save(filename : String, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)
Save to file with filename
Macros
array(name, opt)
Declare an array field
Argument:
- name: Field name
- opt: Options
:type: Element type, must respond tofrom_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
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
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,-1for 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
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