Using module IO::ByteFormat to write properties of an object

I am working on a OLE2 shard and now I am working on the write part. What is the most efficient way of writing parts of an object to a series of bytes in liitle endian format?

It’s really easy to use IO::write_bytes (method API docs):

class IDSerializableArray(T)
  getter id : Int32
  getter data : Array(T)

  def initialize(@id : Int32, @data = Array(T).new)
    # note: `T` must have a `#to_io(IO, IO::ByteFormat)` method;
    #       if you want to use this code directly, you should add
    #       compile-time checking for that

  def serialize(io : IO, endianness : IO::ByteFormat)
    io.write_bytes id, endianness

    io.write_bytes data.size, endianness
    data.each do |element|
      io.write_bytes element, endianness

  # adding a deserialization method for good measure
  def self.deserialize(io : IO, endianness : IO::ByteFormat)
    # note: add error checking if you use this for real
    id = io.read_bytes Int32, endianness

    data_size = io.read_bytes Int32, endianness
    data = { io.read_bytes T, endianness }, data)

I included the endianness arguments for completeness, but if you only ever need little-endian then instead use IO::ByteFormat::LittleEndian.

1 Like