Derive Macro rustler::NifUntaggedEnum

source ·
#[derive(NifUntaggedEnum)]
{
    // Attributes available to this derive:
    #[rustler]
}
Expand description

Derives implementations for the Encoder and Decoder traits which convert between a Rust enum and a union of Elixir types.

This can be used for Rust enums that contain several constructors containing different types of data, each implementing the Encoder and Decoder traits. An enum value will be encoded based on the constructor used, and an Elixir value will be decoded based on the value.

For example from the test code:

#[derive(NifUntaggedEnum)]
enum UntaggedEnum {
    Foo(u32),
    Bar(String),
    Baz(AddStruct),
}

#[rustler::nif]
pub fn untagged_enum_echo(untagged_enum: UntaggedEnum) -> UntaggedEnum {
    untagged_enum
}

Adding boiler plate code to connect Rust code to elixir functions, this can be used from elixir in the following manner.

test "untagged enum transcoder" do
  assert 123 == untagged_enum_echo(123)
  assert "Hello" == untagged_enum_echo("Hello")
  assert %AddStruct{lhs: 45, rhs: 123} = untagged_enum_echo(%AddStruct{lhs: 45, rhs: 123})
  assert :invalid_variant == 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.