11 unstable releases (5 breaking)

new 0.6.3 Mar 13, 2025
0.6.1 Dec 2, 2024
0.6.0 Oct 29, 2024
0.5.0 Jun 14, 2024
0.3.0 Oct 13, 2023

#226 in Procedural macros

Download history 346/week @ 2024-11-20 342/week @ 2024-11-27 407/week @ 2024-12-04 730/week @ 2024-12-11 531/week @ 2024-12-18 404/week @ 2024-12-25 420/week @ 2025-01-01 926/week @ 2025-01-08 735/week @ 2025-01-15 1023/week @ 2025-01-22 1563/week @ 2025-01-29 1282/week @ 2025-02-05 533/week @ 2025-02-12 224/week @ 2025-02-19 572/week @ 2025-02-26 636/week @ 2025-03-05

2,044 downloads per month
Used in 3 crates

MIT/Apache

21KB
335 lines

enum-stringify

Set of macros (only one for now) to generate a string representation of an enum. When using #[derive(EnumStringify)] on an enum, it will implement std::fmt::Display, TryFrom<&str>, TryFrom<String> and std::str::FromStr for it. It will use the name of the enum variant as the string representation.

Usage

use enum_stringify::EnumStringify;

#[derive(EnumStringify)]
enum MyEnum {
    Variant1,
    Variant2,
    Variant3,
}

fn main() {
    println!("{}", MyEnum::Variant1); // Prints "Variant1"
    assert_eq!(MyEnum::Variant1.to_string(), "Variant1");
    assert_eq!(MyEnum::try_from("Variant2").unwrap(), MyEnum::Variant2);
    assert_eq!(MyEnum::try_from("Variant3".to_string()).unwrap(), MyEnum::Variant3);
    assert_eq!(MyEnum::from_str("Variant1").unwrap(), MyEnum::Variant1);
}

Custom string representation

You can customize the string representation of the enum by adding prefixes or/and suffixes to the variants and also changing the case of the string representation.

use enum_stringify::EnumStringify;

#[derive(EnumStringify)]
#[enum_stringify(prefix = "MyPrefix", suffix = "MySuffix", case = "upper_flat")]
enum MyEnum {
    Variant1,
    Variant2,
    Variant3,
}

In this case the string representation of MyEnum::Variant1 will be MyPrefixVariant1MySuffix(and so on for the other variants).

Documentation and installation

See docs.rs for documentation. It is available on crates.io as well.

Dependencies

~0.6–1.1MB
~21K SLoC