#generics #traits #macro #proc-macro #features #supertraits

cfg_matrix

根据 cfg 标志生成超级特质的排列的进程宏

1 个不稳定版本

0.1.1 2023 年 8 月 30 日
0.1.0 2023 年 8 月 20 日

#2461Rust 模式

MIT 许可证

7KB
72

Cfg Matrix

根据 cfg 标志生成超级特质的排列的进程宏。

这是如何工作的

简单来说

这是

#[cfg_matrix {
    SomeBound: feature = "somefeature",
    OtherBound: feature = "otherfeature"
}]
pub trait SomeTrait {}

扩展成这样


#[cfg(all(feature = "somefeature", feature = "otherfeature"))]
pub trait SomeTrait: SomeBound + OtherBound {}

#[cfg(all(feature = "somefeature", not(feature = "otherfeature")))]
pub trait SomeTrait: SomeBound {}

#[cfg(all(not(feature = "somefeature"), feature = "otherfeature"))]
pub trait SomeTrait: OtherBound {}

#[cfg(all(not(feature = "somefeature"), not(feature = "otherfeature")))]
pub trait SomeTrait {}

为什么需要这个?

Rust 不支持在泛型参数或类型边界中使用宏。为什么是这样还不清楚,但当前 Cfg Matrix 可以用来解决这个问题。

这不能编译

struct SomeStruct<A: #[cfg(feature = "somefeature")] SomeBound + #[cfg(feature = "otherfeature")] OtherBound> {...}

但这个可以

struct SomeStruct<A: SomeTrait> {...}

#[cfg(all(feature = "somefeature", feature = "otherfeature"))]
pub trait SomeTrait: SomeBound + OtherBound {}

#[cfg(all(feature = "somefeature", not(feature = "otherfeature")))]
pub trait SomeTrait: SomeBound {}

#[cfg(all(not(feature = "somefeature"), feature = "otherfeature"))]
pub trait SomeTrait: OtherBound {}

#[cfg(all(not(feature = "somefeature"), not(feature = "otherfeature")))]
pub trait SomeTrait {}

所以 Cfg Matrix 提供了一种轻松生成此代码的方法。

注意

Cfg Matrix 目前最多支持 4 个参数。这是为了防止使用此 crate 导致的编译时间过长。因为每个功能都可以启用或禁用,所以有 2^n 个不同的特质定义。对于 4 个参数,这是 16,但对于 5 个参数,它会增加到 32。6 是 64,7 是 128,8 是 256。你明白这个意思。如果需要更多功能,请创建两个不同的特质,在这两个特质上使用 cfg matrix,然后使用第三个特质来组合这两个特质。

依赖项

~255–700KB
~17K SLoC