Derive Macro rustler_codegen::NifUntaggedEnum
source · [−]#[derive(NifUntaggedEnum)]
{
// Attributes available to this derive:
#[rustler]
}
Expand description
Implementation of the NifUntaggedEnum
macro that lets the user annotate an enum that will
generate elixir values when decoded. This can be used for rust enums that contain data and
will generate a value based on the kind of data encoded. For example from the test code:
ⓘ
#[derive(NifUntaggedEnum)]
enum UntaggedEnum {
Foo(u32),
Bar(String),
Baz(AddStruct),
}
pub fn untagged_enum_echo<'a>(env: Env<'a>, args: &[Term<'a>]) -> NifResult<Term<'a>> {
let untagged_enum: UntaggedEnum = args[0].decode()?;
Ok(untagged_enum.encode(env))
}
This can be used from elixir in the following manner.
test "untagged enum transcoder" do
assert 123 == RustlerTest.untagged_enum_echo(123)
assert "Hello" == RustlerTest.untagged_enum_echo("Hello")
assert %AddStruct{lhs: 45, rhs: 123} = RustlerTest.untagged_enum_echo(%AddStruct{lhs: 45, rhs: 123})
assert :invalid_variant == RustlerTest.untagged_enum_echo([1,2,3,4])
end
Note that the type of elixir return is dependent on the data in the enum and the actual enum type is lost in the translation because Elixir has no such concept.