Module: IOStruct::NestedInstanceMethods

Defined in:
lib/iostruct.rb

Overview

initialize nested structures / arrays

Instance Method Summary collapse

Instance Method Details

#initialize(*args) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/iostruct.rb', line 117

def initialize *args
  super
  self.class::FIELDS.each do |k, v|
    next unless v.fmt
    next unless (value = self[k])

    self[k] =
      if v.fmt.is_a?(String)
        # Primitive array (e.g., "i3" for 3 ints)
        value.unpack(v.fmt)
      elsif v.count && v.count > 1
        # Nested struct array: split data and read each chunk
        item_size = v.fmt.size
        v.count.times.map { |i| v.fmt.read(value[i * item_size, item_size]) }
      else
        # Single nested struct
        v.fmt.read(value)
      end
  end
end

#packObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/iostruct.rb', line 138

def pack
  values = self.class::FIELDS.map do |k, v|
    value = self[k]
    next value unless v&.fmt && value

    # Reverse the unpacking done in initialize
    if v.fmt.is_a?(String)
      # Primitive array
      value.pack(v.fmt)
    elsif v.count && v.count > 1
      # Nested struct array: pack each and concatenate
      value.map(&:pack).join
    else
      # Single nested struct
      value.pack
    end
  end
  values.pack self.class.const_get('FORMAT')
end