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

enum[R]

@return [Hash]

Public Class Methods

new(enum, endian=nil, width=nil, default=nil) click to toggle source

@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

Calls superclass method
# 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

format_inspect() click to toggle source
# File lib/packetgen/types/enum.rb, line 75
def format_inspect
  format_str % [to_human, to_i]
end
from_human(value)

To handle human API: set value from a String

Alias for: value=
to_human() click to toggle source

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
value=(value) click to toggle source

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
Also aliased as: from_human