-
Notifications
You must be signed in to change notification settings - Fork 54
QuickStart
Dion Mendel edited this page Jun 25, 2023
·
8 revisions
Stop writing code like this.
def read_fancy_format(io)
comment, len, rest = io.read.unpack("Z*Ca*")
data = rest.unpack("N#{len}")
{:comment => comment, :len => len, :data => *data}
end
Instead, write code like this.
class MyFancyFormat < BinData::Record
stringz :comment
uint8 :len
array :data, type: :int32be, initial_length: :len
end
Start by subclassing BinData::Record
.
class MyFancyFormat < BinData::Record
end
Add fields for each attribute of the file format.
class MyFancyFormat < BinData::Record
stringz :comment
end
Most fields will be primitive types (numbers and strings).
class MyFancyFormat < BinData::Record
stringz :comment
uint8 :len
end
You will also use compound types such as arrays, nested records or choices, as well as dependent fields.
class MyFancyFormat < BinData::Record
stringz :comment
uint8 :len
array :data, type: :int32be, initial_length: :len
end
Once you're created your new subclass, there are common operations to perform.
class MyFancyFormat < BinData::Record
stringz :comment
uint8 :len
array :data, type: :int32be, initial_length: :len
end
obj = MyFancyFormat.new
obj.comment = "this is my comment"
obj.data = [5, 10, 15]
puts obj.to_binary_s