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

enum-primitive-derive

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

6 个版本

0.3.0 2023 年 11 月 22 日
0.2.2 2021 年 10 月 30 日
0.2.1 2020 年 5 月 30 日
0.1.2 2017 年 8 月 31 日

#557Rust 模式

Download history 33854/week @ 2024-03-14 43674/week @ 2024-03-21 39980/week @ 2024-03-28 30895/week @ 2024-04-04 32036/week @ 2024-04-11 37901/week @ 2024-04-18 36042/week @ 2024-04-25 37688/week @ 2024-05-02 30415/week @ 2024-05-09 38905/week @ 2024-05-16 39158/week @ 2024-05-23 44247/week @ 2024-05-30 33948/week @ 2024-06-06 35881/week @ 2024-06-13 36970/week @ 2024-06-20 30473/week @ 2024-06-27

146,842 每月下载量
用于 211 个 crate (57 个直接使用)

MIT 许可证

15KB
130

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

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

最低支持版本 (MSRV) 是 1.56.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));
}

依赖项

~0.4–1MB
~20K SLoC