Module: IOStruct

Extended by:
HashFmt, PackFmt
Defined in:
lib/iostruct.rb,
lib/iostruct/version.rb,
lib/iostruct/hash_fmt.rb,
lib/iostruct/pack_fmt.rb

Defined Under Namespace

Modules: ClassMethods, DecInspect, HashFmt, HexInspect, InspectBase, InstanceMethods, NestedInstanceMethods, PackFmt Classes: FieldInfo

Constant Summary collapse

VERSION =
"0.7.0"

Constants included from PackFmt

PackFmt::FMTSPEC

Constants included from HashFmt

HashFmt::KNOWN_FIELD_TYPES, HashFmt::KNOWN_FIELD_TYPES_REVERSED

Class Method Summary collapse

Methods included from HashFmt

get_type_size

Class Method Details

.auto_names(fields, _size) ⇒ Object

self.new



51
52
53
54
55
56
57
58
59
# File 'lib/iostruct.rb', line 51

def self.auto_names(fields, _size)
  names = []
  offset = 0
  fields.each do |f|
    names << sprintf("f%x", offset).to_sym
    offset += f.size
  end
  names
end

.get_name(klass) ⇒ Object



61
62
63
# File 'lib/iostruct.rb', line 61

def self.get_name(klass)
  (klass.respond_to?(:name) && klass.name) || 'struct'
end

.new(fmt = nil, *names, inspect: :hex, inspect_name_override: nil, struct_name: nil, **kwargs) ⇒ Object

rubocop:enable Lint/StructNewOverride



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/iostruct.rb', line 14

def self.new fmt = nil, *names, inspect: :hex, inspect_name_override: nil, struct_name: nil, **kwargs
  struct_name ||= inspect_name_override # XXX inspect_name_override is deprecated
  if fmt
    renames = kwargs
    finfos, size = parse_pack_format(fmt, names)
    names = auto_names(finfos, size) if names.empty?
    names.map! { |n| renames[n] || n } if renames.any?
  elsif kwargs[:fields]
    fmt, names, finfos, size = parse_hash_format(name: struct_name, **kwargs)
  else
    raise "IOStruct: no fmt and no :fields specified"
  end

  # if first argument to Struct.new() is a string - it creates a named struct in the Struct:: namespace
  # convert all just for the case
  names = names.map(&:to_sym)

  Struct.new( *names ) do
    const_set 'FIELDS', names.zip(finfos).to_h
    const_set 'FORMAT', fmt
    const_set 'SIZE', size
    extend ClassMethods
    include InstanceMethods
    include NestedInstanceMethods if finfos.any?(&:fmt)
    case inspect
    when :hex
      include HexInspect
    when :dec
      include DecInspect
    else
      # ruby default inspect
    end
    define_singleton_method(:to_s) { struct_name } if struct_name
    define_singleton_method(:name) { struct_name } if struct_name
  end
end