Attribute Macro ffi_enum

Source
#[ffi_enum]
Expand description

An attribute macro to generate FFI-compatible bitflags from an enum.

§Attributes

The macro accepts the following arguments:

AttributeDescription
flag_nameThe Identifier of Flag struct(optional, defaults to _CEnum suffix struct if not provided)

§Why this is necessary

In the context of FFI (Foreign Function Interface), the enum type is often represented as i32 or u32. Using Rust’s enum in a struct for FFI may cause undefined behavior if an invalid or unknown value is received.

This macro prevents it:

  • Represent the numeric value of the enum in a Flag structure that safely represents the value of FFI.
  • Provide a to_enum() method to return the flags to the enum, returning None for invalid values instead of causing undefined behavior.
  • Ensure safe and predictable FFI interactions.

§Example

#[commonlibsse_ng_derive_internal::ffi_enum] // auto generate `struct MyEnum_CEnum(i32)`
#[repr(i32)]
enum MyEnum {
    A = 1,
    B = 2,
    C = 4,
}

assert_eq!(MyEnum_CEnum::count(), 3);

// FFI -> Enum
let valid = MyEnum_CEnum::A;
assert_eq!(core::mem::size_of::<MyEnum_CEnum>(), core::mem::size_of::<i32>());
assert_eq!(valid.to_enum(), Some(MyEnum::A));

// Invalid flag: using a bit value that is not defined in the enum
let invalid = MyEnum_CEnum(999);
assert_eq!(invalid.to_enum(), None);

// Enum -> FFI
let flag = MyEnum_CEnum::from_enum(MyEnum::B);
assert_eq!(flag, MyEnum_CEnum::B);