#primitive #enums #derive #ffi #macro-derive #proc-macro #fromprimitive

enum-primitive-derive-nostd

使用过程宏实现自定义 derive 的 enum_primitive 实现

1 个不稳定版本

0.2.2 2020年12月13日

#421 in #primitive


drv8305 中使用

MIT 许可证

15KB
130

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

这是一个自定义 derive,使用过程宏实现 enum_primitive

最低支持的Rust版本为1.34.0

文档

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

用法

将以下内容添加到 Cargo.toml

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

然后在您的代码中添加以下内容

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

#[derive(Primitive)]
enum Variant {
    Value = 1,
    Another = 2,
}

为了真正有用,您需要 use num_traits::FromPrimitiveuse num_traits::ToPrimitive 或两者都。然后您将能够在您的枚举中使用 num_traits::FromPrimitive 和/或 num_traits::ToPrimitive

完整示例

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

复杂示例

在这种情况下,我们尝试使用由 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));
}

依赖项

~1.5MB
~38K SLoC