Module: Rstruct::Packable

Included in:
ContainerType, PackedType
Defined in:
lib/rstruct/base_types/packed_type.rb

Instance Method Summary collapse

Instance Method Details

#pack_value(val, obj = nil) ⇒ Object

Called when composing raw data. While you can override this in subclasses, in general it is probably better to use the ‘on_pack’ method to define a proc to handle packing for special cases.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rstruct/base_types/packed_type.rb', line 48

def pack_value(val, obj=nil)
  begin
    if @pack_cb
      @pack_cb.call(val, obj)
    else
      varray = val.is_a?(Array) ? val : [val]
      varray.pack(self.format)
    end
  rescue => e
    raise(PackError, "Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}")
  end
end

#read(raw, predecessors = nil) ⇒ Object

Called when parsing. While you can override this in subclasses, in general it is probably better to use the ‘on_unpack’ method to define a proc to handle unpacking for special cases.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rstruct/base_types/packed_type.rb', line 28

def read(raw, predecessors=nil)
  if raw.respond_to?(:read)
    raw = raw.read(self.sizeof())
  end
  if raw.size < self.sizeof()
    raise(ReadError, "Expected #{self.sizeof} bytes, but only got #{raw.size} bytes")
  end

  vals = 
    if @unpack_cb
      @unpack_cb.call(raw, predecessors)
    else
      raw.unpack(self.format)
    end
  return(self.claim_value(vals, predecessors))
end