#enums #derive #primitive

enum-tools

自动为枚举派生函数和特质实现

4个版本

0.5.3 2023年11月4日
0.5.2 2023年5月17日
0.5.1 2022年10月30日
0.5.0 2022年10月16日

#2853Rust模式

44 每月下载量
用于 2 crates

MIT 许可证

120KB
2.5K SLoC

Codecov Dependency status crates.io Downloads Github stars License

Crate enum-tools

自动为枚举派生函数和特质实现。

枚举必须是字段为空的、有原始表示并且是 Copy

可以派生许多有用的函数

  • 原始类型转换
  • 遍历所有项和/或名称的迭代器
  • 下一个/上一个项
  • 字符串到/从
  • 等等

有关完整文档,请参阅 EnumTools

示例

#[derive(Clone, Copy, EnumTools)]
// features which create function/constant
#[enum_tools(as_str, from_str, into, MAX, MIN, next, next_back, try_from)]
// features which implement a trait
#[enum_tools(Debug, Display, FromStr, Into, IntoStr, TryFrom)]
// features which create a iterator (function and struct with impl)
#[enum_tools(iter, names, range)]
#[repr(i8)]
pub enum MyEnum { A=0, B=5, C=1 }

派生以下类似的内容

// functions on the enum
impl MyEnum {
    pub const MIN : Self = MyEnum::A;
    pub const MAX : Self = MyEnum::B;
    pub fn as_str(self) -> &'static str
    pub fn from_str(s: &str) -> Option<Self>
    pub fn into(self) -> i8 { self as i8 }
    pub fn next(self) -> Option<Self> // the next element by value (or None if last)
    pub fn next_back(self) -> Option<Self> // the previous element by value (or None if first)
    pub fn try_from(value: i8) -> Option<Self>

    pub fn iter() -> MyEnumIter // a iterator over all elements by value
    pub fn names() -> MyEnumNames // a iterator over all names by value
    pub fn range(start: Self, end: Self) -> MyEnumIter // similar to `..=`
}

// implementations on the enum
impl Debug for MyEnum // calls `as_str`
impl Display for MyEnum // calls `as_str`
impl From<MyEnum> for i8 // feature "Into"
impl From<MyEnum> for &'static str // feature "IntoStr", calls "as_str"
impl FromStr for MyEnum
impl TryFrom<i8> for MyEnum

// structs and impls for the iterators
pub struct MyEnumIter
impl Iterator for MyEnumIter
impl DoubleEndedIterator for MyEnumIter
impl ExactSizeIterator for MyEnumIter
impl FusedIterator for MyEnumIter
pub struct MyEnumNames
impl Iterator for MyEnumNames
impl DoubleEndedIterator for MyEnumNames
impl ExactSizeIterator for MyEnumNames
impl FusedIterator for MyEnumNames

依赖项

~0.3–0.8MB
~19K SLoC