8 releases (5 breaking)

new 0.6.0 Oct 29, 2024
0.5.0 Jun 14, 2024
0.4.2 May 6, 2024
0.4.1 Mar 18, 2024
0.1.0 Sep 13, 2023

#1897 in Procedural macros

Download history 84/week @ 2024-07-09 46/week @ 2024-07-16 55/week @ 2024-07-23 155/week @ 2024-07-30 226/week @ 2024-08-06 197/week @ 2024-08-13 215/week @ 2024-08-20 116/week @ 2024-08-27 90/week @ 2024-09-03 188/week @ 2024-09-10 226/week @ 2024-09-17 152/week @ 2024-09-24 81/week @ 2024-10-01 107/week @ 2024-10-08 164/week @ 2024-10-15 242/week @ 2024-10-22

602 downloads per month
Used in chimpanzee

MIT/Apache

20KB
328 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")]
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.7–1.2MB
~23K SLoC