Class: PacketGen::Types::TLV
- Defined in:
- lib/packetgen/types/tlv.rb
Overview
Class to handle Type-Length-Value attributes
TLV fields handles three subfields:
-
a tag/type field (defaults: Int8 type),
-
a length field (defaults: Int8 type),
-
a value field (defaults: String type).
#initialize supports options to change tag and length type. By example, to declare a TLV using Int16:
define_field :tlv, PacketGen::Types::TLV, builder: ->(obj) { PacketGen::Types::TLV.new(t: PacketGen::Types::Int16, l: PacketGen::Types::Int16) }
Subclasses
A subclass may defined a constant hash TYPES. This hash defines human readable types versus their integer values. Hash keys are integer values, and hash values are types as strings.
If TYPES is defined, a subclass may:
-
print human readable type using #human_type,
-
set type as String with #type=.
Direct Known Subclasses
Instance Attribute Summary collapse
Instance Method Summary collapse
-
#human_type ⇒ String
Return human readable type, if TYPES is defined.
-
#initialize(options = {}) ⇒ TLV
constructor
A new instance of TLV.
- #old_type= ⇒ Integer
- #to_human ⇒ String
Methods inherited from Fields
#[], #[]=, #body=, define_bit_fields_on, define_field, define_field_after, define_field_before, #fields, #force_binary, inherited, #inspect, #read, #sz, #to_h, #to_s
Constructor Details
#initialize(options = {}) ⇒ TLV
Returns a new instance of TLV.
44 45 46 47 48 49 50 51 52 |
# File 'lib/packetgen/types/tlv.rb', line 44 def initialize(={}) super self[:type] = [:t].new(type) if [:t] self[:length] = [:l].new(length) if [:l] self[:value] = String.new('', length_from: self[:length]) self.type = [:type] if [:type] self.value = [:value] if [:value] self.length = [:length] if [:length] end |
Instance Attribute Details
#length ⇒ Integer
30 |
# File 'lib/packetgen/types/tlv.rb', line 30 define_field :length, Int8 |
#type ⇒ Integer
27 |
# File 'lib/packetgen/types/tlv.rb', line 27 define_field :type, Int8 |
#value ⇒ String
33 34 |
# File 'lib/packetgen/types/tlv.rb', line 33 define_field :value, String, builder: ->(tlv) { String.new('', length_from: tlv[:length]) } |
Instance Method Details
#human_type ⇒ String
Return human readable type, if TYPES is defined
87 88 89 90 91 92 93 94 95 |
# File 'lib/packetgen/types/tlv.rb', line 87 def human_type if has_human_types? htype = self.class::TYPES[type] htype = type if htype.nil? htype.to_s else type.to_s end end |
#old_type= ⇒ Integer
55 |
# File 'lib/packetgen/types/tlv.rb', line 55 define_field :type, Int8 |
#to_human ⇒ String
98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/packetgen/types/tlv.rb', line 98 def to_human name = self.class.to_s.gsub(/.*::/, '') @typestr ||= if has_human_types? types = self.class::TYPES.values "%-#{types.max { |a,b| a.length <=> b.length }.size}s" else "%s" end @lenstr ||= "%-#{(2**(self[:length].width*8) - 1).to_s.size}u" "#{name} type:#@typestr length:#@lenstr value:#{value.inspect}" % [human_type, length] end |