class Depix::Binary::Fields::Field

Base class for a padded field in a struct

Attributes

desc[RW]
length[RW]
name[RW]
pattern[RW]
req[RW]
req?[RW]
rtype[RW]

Public Class Methods

new(opts = {}) click to toggle source

Hash init

# File lib/depix/binary/fields.rb, line 16
def initialize(opts = {})
  opts.each_pair {|k, v| send(k.to_s + '=', v) }
end

Public Instance Methods

clean(v) click to toggle source

Return a cleaned value (like a null-terminated string truncated up to null)

# File lib/depix/binary/fields.rb, line 21
def clean(v)
  v
end
consume!(stack) click to toggle source

Return the actual values from the stack. The stack will begin on the element we need, so the default consumption is shift. Normally all fields shift the stack as they go, and if they contain nested substructs they will pop the stack as well

# File lib/depix/binary/fields.rb, line 33
def consume!(stack)
  clean(stack.shift)
end
explain() click to toggle source

Show a nice textual explanation of the field

# File lib/depix/binary/fields.rb, line 26
def explain
  [rtype ? ("(%s)" % rtype) : nil, desc, (req? ? "- required" : nil)].compact.join(' ')
end
pack(value) click to toggle source

Pack a value passed into a string

# File lib/depix/binary/fields.rb, line 48
def pack(value)
  raise "No pattern defined for #{self}" unless pattern
  if value.nil?
    [self.class.const_get(:BLANK)].pack(pattern)
  else
    [value].pack(pattern)
  end
end
validate!(value) click to toggle source

Check that the passed value: a) Matches the Ruby type expected b) Fits into the slot c) Does not overflow When the validation fails should raise

# File lib/depix/binary/fields.rb, line 42
def validate!(value)
  raise "#{name} value required, but got nil in #{name}".strip if value.nil? && req?
  raise "Value expected to be #{rtype} but was #{value.class}" if !value.nil? && rtype && !value.is_a?(rtype)
end

Private Instance Methods

blanking?(blob) click to toggle source
# File lib/depix/binary/fields.rb, line 58
def blanking?(blob)
  blob.nil? || blob.empty? || blob == (0xFF.chr * length)
end