Derive Macro rustler_codegen::NifUnitEnum
source · #[derive(NifUnitEnum)]
{
// Attributes available to this derive:
#[rustler]
}
Expand description
Derives implementations for the Encoder
and Decoder
traits
which convert between an enum and a union of elixir atoms.
For example:
ⓘ
#[derive(NifUnitEnum)]
enum UnitEnum {
FooBar,
Baz,
}
Then the traits Encoder
and Decoder
are derived automatically for your Rust struct
such that FooBar
is encoded to, and decoded from, :foo_bar
.
- The variant name is translated from camel case to snake case for the atom name.
- Each constructor is required not to have arguments, i.e. to be of unit type.
An example usage in Rust and Elixir would look like the following.
ⓘ
#[rustler::nif]
pub fn unit_enum_echo(unit_enum: UnitEnum) -> UnitEnum {
unit_enum
}
(We are leaving out some boiler plate code to connect the rust code to elixir functions.)
test "unit enum transcoder" do
assert :foo_bar == unit_enum_echo(:foo_bar)
assert :baz == unit_enum_echo(:baz)
assert :invalid_variant == unit_enum_echo(:somethingelse)
end
Note that the :invalid_variant
atom is returned if the user tries to encode something
that isn’t in the Rust enum.