#derive #enum #fromprimitive #primitive #ffi

macro enum-primitive-derive

enum_primitive implementation using procedural macros to have a custom derive

4 releases

0.2.1 May 30, 2020
0.2.0 May 30, 2020
0.1.2 Aug 31, 2017
0.1.1 Aug 31, 2017
0.1.0 Aug 30, 2017

#53 in Rust patterns

Download history 6761/week @ 2021-02-24 6257/week @ 2021-03-03 7100/week @ 2021-03-10 6941/week @ 2021-03-17 6320/week @ 2021-03-24 5858/week @ 2021-03-31 5923/week @ 2021-04-07 6570/week @ 2021-04-14 8119/week @ 2021-04-21 7948/week @ 2021-04-28 7908/week @ 2021-05-05 6913/week @ 2021-05-12 5979/week @ 2021-05-19 6257/week @ 2021-05-26 5870/week @ 2021-06-02 5552/week @ 2021-06-09

29,326 downloads per month
Used in 110 crates (44 directly)

MIT license

14KB
130 lines

Build status Rust version Documentation Latest version All downloads Downloads of latest version

This is a custom derive, using procedural macros, implementation of enum_primitive.

MSRV is 1.34.0

Documentation

https://docs.rs/enum-primitive-derive/

Usage

Add the following to Cargo.toml:

[dependencies]
enum-primitive-derive = "^0.1"
num-traits = "^0.1"

Then to your code add:

#[macro_use]
extern crate enum_primitive_derive;
extern crate num_traits;

#[derive(Primitive)]
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 num_traits::FromPrimitive and/or num_traits::ToPrimitive on your enum.

Full Example

#[macro_use]
extern crate enum_primitive_derive;
extern crate num_traits;

use num_traits::{FromPrimitive, ToPrimitive};

#[derive(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

In this case we attempt to use values created by bindgen.

#[macro_use]
extern crate enum_primitive_derive;
extern crate num_traits;

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));
}

Dependencies

~0.4–0.9MB
~21K SLoC