class PacketGen::Types::Enum
@abstract Base enum class to handle binary integers with limited
authorized values
An {Enum} type is used to handle an {Int} field with limited and named values.
Simple example¶ ↑
enum = Int8Enum.new(0, 'low' => 0, 'medium' => 1, 'high' => 2})
In this example, enum
is a 8-bit field which may take one among three values: low
, medium
or high
:
enum.value = 'high' enum.value # => 2 enum.value = 1 enum.value # => 1 enum.to_human # => "medium"
Setting an unknown value will raise an exception:
enum.value = 4 # => raise! enum.value = 'unknown' # => raise!
But {#read} will not raise when reading an outbound value. This to enable decoding (or forging) of bad packets. @since 2.1.3 @author Sylvain Daubert
Attributes
@return [Hash]
Public Class Methods
@param [Hash] enum enumerated values. Default value is taken from
first element unless given.
@param [:little,:big,nil] endian @param [Integer,nil] width @param [Integer,nil] default default value
# File lib/packetgen/types/enum.rb, line 41 def initialize(enum, endian=nil, width=nil, default=nil) default ||= enum[enum.keys.first] super(nil, endian, width, default) @enum = enum end
Public Instance Methods
# File lib/packetgen/types/enum.rb, line 75 def format_inspect format_str % [to_human, to_i] end
Get human readable value (enum name) @return [String]
# File lib/packetgen/types/enum.rb, line 71 def to_human @enum.key(to_i) || "<unknown:#{@value}>" end
Setter for value attribute @param [#to_i, String
,nil] value value as an Integer or as a String
from enumration
@return [Integer] @raise [ArgumentError] String
value is unknown
# File lib/packetgen/types/enum.rb, line 52 def value=(value) ival = case value when NilClass nil when ::String raise ArgumentError, "#{value.inspect} not in enumeration" unless @enum.key? value @enum[value] else value.to_i end @value = ival end