Class: BinStruct::Enum Abstract
Overview
Base enum class to handle binary integers with limited authorized values
An Enum type is used to handle an Int attribute with limited and named values.
Simple example
enum = Int8Enum.new('low' => 0, 'medium' => 1, 'high' => 2})
In this example, enum
is a 8-bit attribute 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{::String => Integer}
readonly
Enumerated values.
Attributes inherited from Int
#default, #endian, #value, #width
Instance Method Summary collapse
-
#format_inspect ⇒ ::String
Format Enum type when inspecting Struct.
-
#initialize(options = {}) ⇒ 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 Structable
#read, #sz, #to_s, #type_name
Constructor Details
#initialize(options = {}) ⇒ Enum
Returns a new instance of Enum.
42 43 44 45 46 47 48 49 |
# File 'lib/bin_struct/enum.rb', line 42 def initialize( = {}) enum = [:enum] raise TypeError, 'enum must be defined as a Hash' unless enum.is_a?(Hash) [:default] ||= enum[enum.keys.first] super @enum = enum end |
Instance Attribute Details
#enum ⇒ Hash{::String => Integer} (readonly)
Enumerated values
34 35 36 |
# File 'lib/bin_struct/enum.rb', line 34 def enum @enum end |
Instance Method Details
#format_inspect ⇒ ::String
Format Enum type when inspecting Struct
81 82 83 |
# File 'lib/bin_struct/enum.rb', line 81 def format_inspect format_str % [to_human, to_i] end |
#to_human ⇒ ::String
Get human readable value (enum name)
75 76 77 |
# File 'lib/bin_struct/enum.rb', line 75 def to_human @enum.key(to_i) || "<unknown:#{@value}>" end |
#value=(value) ⇒ Integer Also known as: from_human
Setter for value attribute
56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/bin_struct/enum.rb', line 56 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 |