Class: PacketGen::Types::Enum Abstract
Overview
This class is 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('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 Int#read will not raise when reading an outbound value. This to enable decoding (or forging) of bad packets.
Instance Attribute Summary collapse
- #enum ⇒ Hash readonly
Attributes inherited from Int
#default, #endian, #value, #width
Instance Method Summary collapse
- #format_inspect ⇒ Object
-
#initialize(enum, endian = nil, width = nil, default = nil) ⇒ Enum
constructor
A new instance of Enum.
-
#to_human ⇒ String
Get human readable value (enum name).
-
#value=(value) ⇒ Integer
(also: #from_human)
Setter for value attribute.
Methods inherited from Int
#nbits, #read, #sz, #to_f, #to_i, #to_s
Methods included from Fieldable
#read, #sz, #to_s, #type_name
Constructor Details
#initialize(enum, endian = nil, width = nil, default = nil) ⇒ Enum
Returns a new instance of Enum.
42 43 44 45 46 |
# File 'lib/packetgen/types/enum.rb', line 42 def initialize(enum, endian=nil, width=nil, default=nil) default ||= enum[enum.keys.first] super(nil, endian, width, default) @enum = enum end |
Instance Attribute Details
#enum ⇒ Hash (readonly)
35 36 37 |
# File 'lib/packetgen/types/enum.rb', line 35 def enum @enum end |
Instance Method Details
#format_inspect ⇒ Object
76 77 78 |
# File 'lib/packetgen/types/enum.rb', line 76 def format_inspect format_str % [to_human, to_i] end |
#to_human ⇒ String
Get human readable value (enum name)
72 73 74 |
# File 'lib/packetgen/types/enum.rb', line 72 def to_human @enum.key(to_i) || "<unknown:#{@value}>" end |
#value=(value) ⇒ Integer Also known as: from_human
Setter for value attribute
53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/packetgen/types/enum.rb', line 53 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 |