This is a custom derive, using procedural macros, implementation of enum_primitive.
MSRV is 1.34.0
https://docs.rs/enum-primitive-derive/
Add the following to Cargo.toml
:
[dependencies]
enum-primitive-derive = "^0.1"
num-traits = "^0.1"
Then to your code add:
```rust
extern crate enumprimitivederive; extern crate num_traits;
enum Variant { Value = 1, Another = 2, } ```
To be really useful you need use num_traits::FromPrimitive
or
use num_traits::ToPrimitive
or both. You will then be able to
use
numtraits::FromPrimitive
and/or
numtraits::ToPrimitive
on your enum.
```rust
extern crate enumprimitivederive; extern crate num_traits;
use num_traits::{FromPrimitive, ToPrimitive};
enum Foo { Bar = 32, Dead = 42, Beef = 50, }
fn main() { asserteq!(Foo::fromi32(32), Some(Foo::Bar)); asserteq!(Foo::fromi32(42), Some(Foo::Dead)); asserteq!(Foo::fromi64(50), Some(Foo::Beef)); asserteq!(Foo::fromisize(17), None);
let bar = Foo::Bar;
assert_eq!(bar.to_i32(), Some(32));
let dead = Foo::Dead;
assert_eq!(dead.to_isize(), Some(42));
} ```
In this case we attempt to use values created by bindgen.
```rust
extern crate enumprimitivederive; extern crate num_traits;
use num_traits::{FromPrimitive, ToPrimitive};
pub const ABC: ::std::os::raw::cuint = 1; pub const DEF: ::std::os::raw::cuint = 2; pub const GHI: ::std::os::raw::c_uint = 4;
enum BindGenLike { ABC = ABC as isize, DEF = DEF as isize, GHI = GHI as isize, }
fn main() { asserteq!(BindGenLike::fromisize(4), Some(BindGenLike::GHI)); asserteq!(BindGenLike::fromu32(2), Some(BindGenLike::DEF)); asserteq!(BindGenLike::fromu32(8), None);
let abc = BindGenLike::ABC;
assert_eq!(abc.to_u32(), Some(1));
} ```