# coding: utf-8 # frozen_string_literal: true # This file is part of PacketGen # See https://github.com/sdaubert/packetgen for more informations # Copyright (C) 2016 Sylvain Daubert # This program is published under MIT license. module PacketGen module Types # This class is an abstract class to define type-length-value data. # # This class supersedes {TLV} class, which is not well defined on some corner # cases. # # ===Usage # To simply define a new TLV class, do: # MyTLV = PacketGen::Types::AbstractTLV.create # MyTLV.define_type_enum 'one' => 1, 'two' => 2 # This will define a new +MyTLV+ class, subclass of {Fields}. This class will # define 3 fields: # * +#type+, as a {Int8Enum} by default, # * +#length+, as a {Int8} by default, # * and +#value+, as a {String} by default. # +.define_type_enum+ is, here, necessary to define enum hash to be used # for +#type+ accessor, as this one is defined as an {Enum}. # # This class may then be used as older {TLV} class: # tlv = MyTLV.new(type: 1, value: 'abcd') # automagically set #length from value # tlv.type #=> 1 # tlv.human_type #=> 'one' # tlv.length #=> 4 # tlv.value #=> "abcd" # # ===Advanced usage # Each field's type may be changed at generating TLV class: # MyTLV = PacketGen::Types::AbstractTLV.create(type_class: PacketGen::Types::Int16, # length_class: PacketGen::Types::Int16, # value_class: PacketGen::Header::IP::Addr) # tlv = MyTLV.new(type: 1, value: '1.2.3.4') # tlv.type #=> 1 # tlv.length #=> 4 # tlv.value #=> '1.2.3.4' # tlv.to_s #=> "\x00\x01\x00\x04\x01\x02\x03\x04" # # Some aliases may also be defined. For example, to create a TLV type # whose +type+ field should be named +code+: # MyTLV = PacketGen::Types::AbstractTLV.create(type_class: PacketGen::Types::Int16, # length_class: PacketGen::Types::Int16, # aliases: { code: :type }) # tlv = MyTLV.new(code: 1, value: 'abcd') # tlv.code #=> 1 # tlv.type #=> 1 # tlv.length #=> 4 # tlv.value #=> 'abcd' # # @author Sylvain Daubert # @since 3.1.0 # @since 3.1.1 add +:aliases+ keyword to {#initialize} class AbstractTLV < Types::Fields class <