Class: FFI::Enum
Overview
Represents a C enum.
For a C enum:
enum fruits {
apple,
banana,
orange,
pineapple
};
are defined this vocabulary:
-
a symbol is a word from the enumeration (ie. apple, by example);
-
a value is the value of a symbol in the enumeration (by example, apple has value 0 and banana 1).
Direct Known Subclasses
Instance Attribute Summary collapse
-
#native_type ⇒ Object
readonly
Returns the value of attribute native_type.
-
#tag ⇒ Object
readonly
Returns the value of attribute tag.
Instance Method Summary collapse
-
#[](query) ⇒ Object
(also: #find)
Get a symbol or a value from the enum.
-
#from_native(val, ctx) ⇒ Object
Symbol name if it exists for
val
. -
#initialize(*args) ⇒ Enum
constructor
A new instance of Enum.
-
#symbol_map ⇒ Hash
(also: #to_h, #to_hash)
Get the symbol map.
-
#symbols ⇒ Array
Enum symbol names.
-
#to_native(val, ctx) ⇒ Integer
Value of a enum symbol.
Constructor Details
#initialize(info, tag = nil) ⇒ Enum #initialize(native_type, info, tag = nil) ⇒ Enum
Returns a new instance of Enum.
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/ffi/enum.rb', line 96 def initialize(*args) @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT info, @tag = *args @kv_map = Hash.new unless info.nil? last_cst = nil value = 0 info.each do |i| case i when Symbol raise ArgumentError, "duplicate enum key" if @kv_map.has_key?(i) @kv_map[i] = value last_cst = i value += 1 when Integer @kv_map[last_cst] = i value = i+1 end end end @vk_map = @kv_map.invert end |
Instance Attribute Details
#native_type ⇒ Object (readonly)
Returns the value of attribute native_type.
87 88 89 |
# File 'lib/ffi/enum.rb', line 87 def native_type @native_type end |
#tag ⇒ Object (readonly)
Returns the value of attribute tag.
86 87 88 |
# File 'lib/ffi/enum.rb', line 86 def tag @tag end |
Instance Method Details
#[](query) ⇒ Integer #[](query) ⇒ Symbol Also known as: find
Get a symbol or a value from the enum.
133 134 135 136 137 138 139 140 |
# File 'lib/ffi/enum.rb', line 133 def [](query) case query when Symbol @kv_map[query] when Integer @vk_map[query] end end |
#from_native(val, ctx) ⇒ Object
Returns symbol name if it exists for val
.
167 168 169 |
# File 'lib/ffi/enum.rb', line 167 def from_native(val, ctx) @vk_map[val] || val end |
#symbol_map ⇒ Hash Also known as: to_h, to_hash
Get the symbol map.
145 146 147 |
# File 'lib/ffi/enum.rb', line 145 def symbol_map @kv_map end |
#symbols ⇒ Array
Returns enum symbol names.
120 121 122 |
# File 'lib/ffi/enum.rb', line 120 def symbols @kv_map.keys end |
#to_native(val, ctx) ⇒ Integer
Returns value of a enum symbol.
155 156 157 158 159 160 161 162 163 |
# File 'lib/ffi/enum.rb', line 155 def to_native(val, ctx) @kv_map[val] || if val.is_a?(Integer) val elsif val.respond_to?(:to_int) val.to_int else raise ArgumentError, "invalid enum value, #{val.inspect}" end end |