Module: BinData::ByteAlignPlugin

Defined in:
lib/bindata/struct.rb

Overview

Align fields to a multiple of :byte_align

Instance Method Summary collapse

Instance Method Details

#align_obj?(obj) ⇒ Boolean

Returns:

  • (Boolean)


336
337
338
# File 'lib/bindata/struct.rb', line 336

def align_obj?(obj)
  obj.has_parameter?(:byte_align)
end

#bytes_to_align(obj, rel_offset) ⇒ Object



331
332
333
334
# File 'lib/bindata/struct.rb', line 331

def bytes_to_align(obj, rel_offset)
  align = obj.eval_parameter(:byte_align)
  (align - (rel_offset % align)) % align
end

#do_read(io) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/bindata/struct.rb', line 288

def do_read(io)
  initial_offset = io.offset
  instantiate_all_objs
  @field_objs.each do |f|
    if include_obj?(f)
      if align_obj?(f)
        io.seekbytes(bytes_to_align(f, io.offset - initial_offset))
      end
      f.do_read(io)
    end
  end
end

#do_write(io) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/bindata/struct.rb', line 301

def do_write(io)
  initial_offset = io.offset
  instantiate_all_objs
  @field_objs.each do |f|
    if include_obj?(f)
      if align_obj?(f)
        io.writebytes("\x00" * bytes_to_align(f, io.offset - initial_offset))
      end
      f.do_write(io)
    end
  end
end

#sum_num_bytes_below_index(index) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/bindata/struct.rb', line 314

def sum_num_bytes_below_index(index)
  sum = 0
  (0...@field_objs.length).each do |i|
    obj = @field_objs[i]
    if include_obj?(obj)
      sum = sum.ceil + bytes_to_align(obj, sum.ceil) if align_obj?(obj)

      break if i >= index

      nbytes = obj.do_num_bytes
      sum = (nbytes.is_a?(Integer) ? sum.ceil : sum) + nbytes
    end
  end

  sum
end