#traits #dynamic #high-performance #generate

macro denumic

创建基于枚举的运行时分派特质

1 个不稳定版本

0.1.0 2024年4月12日

#449过程宏

每月下载 23 次

自定义许可证

27KB
637

denumic

denumic 宏用于创建基于枚举的运行时分派特质。

当应用于 trait 时,它导出将被传递给其他 enum 上的 denumic 属性的特质定义。

当应用于 enum 时,它生成一个宏,可用于为 enum 的每个变体分派适当的特质实现。

FromTryFrom 也自动应用于 enum,只要它不违反一致性规则,因此它可以转换为和从变体进行转换。

示例

use denumic::denumic;

// Generic parameters of the trait and the enum could be finly merged matching by names.
#[denumic]
pub trait Trait {
    const MY_CONST: i32;
    type MyType;
    fn foo(self) -> i32;
}

// Note that the identifiers `used` before the trait definition also have to be `use`d before the enum definition.
#[denumic(Trait)]
// Associated types and consts can be specified using attributes:
#[MY_CONST = 1]
// As for types that are not a valid `expr`, quote them instead of raw types:
#[MyType = "&'static str"]
pub enum Impl<Other = ()>
where
    Other: Trait,
{
    // `From` and `TryFrom` are only generated if the enum has only a single field.
    A(A),
    // If multiple fields are found, the one with `#[denumic]` otherwise the first one is dispatched.
    Other(Other, String),
}

pub struct A;

impl Trait for A {
    const MY_CONST: i32 = 2;

    type MyType = ();

    fn foo(self) -> i32 {
        10
    }
}

impl Trait for () {
    const MY_CONST: i32 = 0;

    type MyType = String;

    fn foo(self) -> i32 {
        20
    }
}

fn call_foo(v: A) -> i32 {
    let v: Impl = v.into();
    v.foo()
}

依赖项

~265–710KB
~17K SLoC