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)


441
442
443
# File 'lib/bindata/struct.rb', line 441

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

#bytes_to_align(obj, rel_offset) ⇒ Object



436
437
438
439
# File 'lib/bindata/struct.rb', line 436

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

#do_read(io) ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/bindata/struct.rb', line 393

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



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/bindata/struct.rb', line 406

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



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/bindata/struct.rb', line 419

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