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)


343
344
345
# File 'lib/bindata/struct.rb', line 343

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

#bytes_to_align(obj, rel_offset) ⇒ Object



338
339
340
341
# File 'lib/bindata/struct.rb', line 338

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

#do_read(io) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/bindata/struct.rb', line 295

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



308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/bindata/struct.rb', line 308

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



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/bindata/struct.rb', line 321

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