Module: BinData::Struct::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)


361
362
363
# File 'lib/bindata/struct.rb', line 361

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

#bytes_to_align(obj, rel_offset) ⇒ Object



356
357
358
359
# File 'lib/bindata/struct.rb', line 356

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

#do_read(io) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/bindata/struct.rb', line 302

def do_read(io)
  offset = 0
  instantiate_all_objs
  @field_objs.each do |f|
    next unless include_obj?(f)

    if align_obj?(f)
      nbytes = bytes_to_align(f, offset.ceil)
      offset = offset.ceil + nbytes
      io.readbytes(nbytes)
    end

    f.do_read(io)
    nbytes = f.do_num_bytes
    offset = (nbytes.is_a?(Integer) ? offset.ceil : offset) + nbytes
  end
end

#do_write(io) ⇒ Object



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

def do_write(io)
  offset = 0
  instantiate_all_objs
  @field_objs.each do |f|
    next unless include_obj?(f)

    if align_obj?(f)
      nbytes = bytes_to_align(f, offset.ceil)
      offset = offset.ceil + nbytes
      io.writebytes("\x00" * nbytes)
    end

    f.do_write(io)
    nbytes = f.do_num_bytes
    offset = (nbytes.is_a?(Integer) ? offset.ceil : offset) + nbytes
  end
end

#sum_num_bytes_below_index(index) ⇒ Object



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/bindata/struct.rb', line 338

def sum_num_bytes_below_index(index)
  sum = 0
  @field_objs.each_with_index do |obj, i|
    next unless include_obj?(obj)

    if align_obj?(obj)
      sum = sum.ceil + bytes_to_align(obj, sum.ceil)
    end

    break if i >= index

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

  sum
end