Class: Depix::Binary::Fields::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/depix/binary/fields.rb

Overview

Base class for a padded field in a struct

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Field

Hash init



16
17
18
# File 'lib/depix/binary/fields.rb', line 16

def initialize(opts = {})
  opts.each_pair {|k, v| send(k.to_s + '=', v) }
end

Instance Attribute Details

#descObject

Field description



10
11
12
# File 'lib/depix/binary/fields.rb', line 10

def desc
  @desc
end

#lengthObject

Field length in bytes, including any possible padding



7
8
9
# File 'lib/depix/binary/fields.rb', line 7

def length
  @length
end

#nameObject

Field name



6
7
8
# File 'lib/depix/binary/fields.rb', line 6

def name
  @name
end

#patternObject

The unpack pattern that defines the field



8
9
10
# File 'lib/depix/binary/fields.rb', line 8

def pattern
  @pattern
end

#reqObject Also known as: req?

Is the field required?



9
10
11
# File 'lib/depix/binary/fields.rb', line 9

def req
  @req
end

#rtypeObject

To which Ruby type this has to be cast (and which type is accepted as value)



11
12
13
# File 'lib/depix/binary/fields.rb', line 11

def rtype
  @rtype
end

Instance Method Details

#clean(v) ⇒ Object

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



21
22
23
# File 'lib/depix/binary/fields.rb', line 21

def clean(v)
  v
end

#consume!(stack) ⇒ Object

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



33
34
35
# File 'lib/depix/binary/fields.rb', line 33

def consume!(stack)
  clean(stack.shift)
end

#explainObject

Show a nice textual explanation of the field



26
27
28
# File 'lib/depix/binary/fields.rb', line 26

def explain
  [rtype ? ("(%s)" % rtype) : nil, desc, (req? ? "- required" : nil)].compact.join(' ')
end

#pack(value) ⇒ Object

Pack a value passed into a string



48
49
50
51
52
53
54
55
# 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) ⇒ Object

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



42
43
44
45
# 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