module Rstruct::Packable
Public Instance Methods
pack_value(val, obj=nil)
click to toggle source
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.
# 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)
click to toggle source
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.
# 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
Private Instance Methods
on_pack(&block)
click to toggle source
sets up a callback for packing a value to raw data for this type
# File lib/rstruct/base_types/packed_type.rb, line 14 def on_pack(&block) @pack_cb = block end
on_unpack(&block)
click to toggle source
sets up a callback for unpacking data from a string for this type
# File lib/rstruct/base_types/packed_type.rb, line 20 def on_unpack(&block) @unpack_cb = block end