Expand description

This crate provides a custom derive Primitive that helps people providing native Rust bindings to C code by allowing a C-like enum declaration to convert to its primitve values and back from them. You can selectively include num_traits::ToPrimitive and num_traits::FromPrimitive to get these features.

Example

use enum_primitive_derive::Primitive;
use num_traits::{FromPrimitive, ToPrimitive};

#[derive(Debug, Eq, PartialEq, Primitive)]
enum Foo {
    Bar = 32,
    Dead = 42,
    Beef = 50,
}

fn main() {
    assert_eq!(Foo::from_i32(32), Some(Foo::Bar));
    assert_eq!(Foo::from_i32(42), Some(Foo::Dead));
    assert_eq!(Foo::from_i64(50), Some(Foo::Beef));
    assert_eq!(Foo::from_isize(17), None);

    let bar = Foo::Bar;
    assert_eq!(bar.to_i32(), Some(32));

    let dead = Foo::Dead;
    assert_eq!(dead.to_isize(), Some(42));
}

Complex Example

use enum_primitive_derive::Primitive;
use num_traits::{FromPrimitive, ToPrimitive};

pub const ABC: ::std::os::raw::c_uint = 1;
pub const DEF: ::std::os::raw::c_uint = 2;
pub const GHI: ::std::os::raw::c_uint = 4;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Primitive)]
enum BindGenLike {
    ABC = ABC as isize,
    DEF = DEF as isize,
    GHI = GHI as isize,
}

fn main() {
    assert_eq!(BindGenLike::from_isize(4), Some(BindGenLike::GHI));
    assert_eq!(BindGenLike::from_u32(2), Some(BindGenLike::DEF));
    assert_eq!(BindGenLike::from_u32(8), None);

    let abc = BindGenLike::ABC;
    assert_eq!(abc.to_u32(), Some(1));
}

TryFrom Example

use enum_primitive_derive::Primitive;
use core::convert::TryFrom;

#[derive(Debug, Eq, PartialEq, Primitive)]
enum Foo {
    Bar = 32,
    Dead = 42,
    Beef = 50,
}

fn main() {
    let bar = Foo::try_from(32);
    assert_eq!(bar, Ok(Foo::Bar));

    let dead = Foo::try_from(42);
    assert_eq!(dead, Ok(Foo::Dead));

    let unknown = Foo::try_from(12);
    assert!(unknown.is_err());
}

Derive Macros

  • Provides implementation of num_traits::ToPrimitive and num_traits::FromPrimitive