Class: BinStruct::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 attribute with limited and named values.
Setting an unknown name will raise an exception:
enum.value = 'unknown' # => raise!
But Int#read and #value= will not raise when reading/setting an out-of-bound integer. This to enable decoding (or forging) of bad packets.
enum.read("\x05".b).value # => 5
enum.value = 4 # => 4
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.
45 46 47 48 49 50 51 52 |
# File 'lib/bin_struct/enum.rb', line 45 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
37 38 39 |
# File 'lib/bin_struct/enum.rb', line 37 def enum @enum end |
Instance Method Details
#format_inspect ⇒ ::String
Format Enum type when inspecting Struct
84 85 86 |
# File 'lib/bin_struct/enum.rb', line 84 def format_inspect format_str % [to_human, to_i] end |
#to_human ⇒ ::String
Get human readable value (enum name)
78 79 80 |
# File 'lib/bin_struct/enum.rb', line 78 def to_human @enum.key(to_i) || "<unknown:#{@value}>" end |
#value=(value) ⇒ Integer Also known as: from_human
Setter for value attribute
59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/bin_struct/enum.rb', line 59 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 |