class FFI::Enum

Represents a C enum.

For a C enum:

enum fruits {
  apple,
  banana,
  orange,
  pineapple
};

are defined this vocabulary:

Attributes

native_type[R]
tag[R]

Public Class Methods

new(*args) click to toggle source

@overload initialize(info, tag=nil)

@param [nil, Enumerable] info
@param [nil, Symbol] tag enum tag

@overload initialize(native_type, info, tag=nil)

@param [FFI::Type] native_type Native type for new Enum
@param [nil, Enumerable] info symbols and values for new Enum
@param [nil, Symbol] tag name of new Enum
# File lib/ffi/enum.rb, line 97
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

Public Instance Methods

[](query) click to toggle source

Get a symbol or a value from the enum. @overload [](query)

Get enum value from symbol.
@param [Symbol] query
@return [Integer]

@overload [](query)

Get enum symbol from value.
@param [Integer] query
@return [Symbol]
# File lib/ffi/enum.rb, line 134
def [](query)
  case query
  when Symbol
    @kv_map[query]
  when Integer
    @vk_map[query]
  end
end
Also aliased as: find
find(query)
Alias for: []
from_native(val, ctx) click to toggle source

@param val @return symbol name if it exists for val.

# File lib/ffi/enum.rb, line 168
def from_native(val, ctx)
  @vk_map[val] || val
end
symbol_map() click to toggle source

Get the symbol map. @return [Hash]

# File lib/ffi/enum.rb, line 146
def symbol_map
  @kv_map
end
Also aliased as: to_h, to_hash
symbols() click to toggle source

@return [Array] enum symbol names

# File lib/ffi/enum.rb, line 121
def symbols
  @kv_map.keys
end
to_h()
Alias for: symbol_map
to_hash()
Alias for: symbol_map
to_native(val, ctx) click to toggle source

@param [Symbol, Integer, to_int] val @param ctx unused @return [Integer] value of a enum symbol

# File lib/ffi/enum.rb, line 156
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