Attribute Macro enumber::into

source ·
#[into]
Expand description

Convert an enumber compliant enum whose variants have data into a proper enum with appropriate associated traits.

As an example, you might have the following enum definition:

#[enumber::into]
#[repr(usize)]
enum Errors {
    Success = 0,
    #[value(0x10)] NotDefined(String),
    InvalidArg(String, String) = 0x20,
    OpNotSupported = 0x30,
}

Enumber turns this into a normal enum and also implements From. This makes it easy to convert the enum into its corresponding numeric value, which is particularly useful when converting from rich Rust-style errors to C-style error codes:

type ErrorCode = usize;

fn some_ffi() -> ErrorCode {
    Errors::OpNotSupported.into()
}

Unlike the convert macro, this macro does not generate an implementation of From in the opposite direction (i.e., from a numeric value to a variant), nor does it generate an implementation of FromStr for the simple reason that it is not possible to convert an error code to a variant that has data without having default values, which is not always reasonable.

This macro also doesn’t support ranges or a default, because we are only converting from variants to values and only a single value per variant makes sense. As such, the following does not work:

#[enumber::into]
#[repr(u8)]
enum Age {
    Child(String) = 0..=12,
    Teenager(String) = 13..=19,
    Adult(String) = 20..=65,
    Pensioner(String) = 66..=255,
}

And, into does not implement Display as there isn’t a single reasonable way to implement Display for variants with data.