#variant-name #variant #string #enums #string-conversion #string-representation #derive

enum-variants-strings

Derive macro for converting instances of enums to and from strs using variant names

6 releases

0.3.0 Mar 1, 2024
0.2.3 Apr 11, 2023
0.2.2 Mar 7, 2023
0.2.1 Jan 25, 2023
0.1.0 Dec 22, 2021

#608 in Rust patterns

Download history 252/week @ 2023-12-22 180/week @ 2023-12-29 313/week @ 2024-01-05 179/week @ 2024-01-12 58/week @ 2024-01-19 65/week @ 2024-01-26 81/week @ 2024-02-02 96/week @ 2024-02-09 112/week @ 2024-02-16 152/week @ 2024-02-23 254/week @ 2024-03-01 86/week @ 2024-03-08 70/week @ 2024-03-15 58/week @ 2024-03-22 116/week @ 2024-03-29 57/week @ 2024-04-05

307 downloads per month
Used in 10 crates (7 directly)

MIT license

5KB

Enum Variants Strings

Crates.io badge Docs.rs badge

Generates conversions of enums from strings and into strings based on variant identifiers

use enum_variants_strings::EnumVariantsStrings;

#[derive(Debug, PartialEq, EnumVariantsStrings)]
enum Variants {
    X,
    Y(i32),
    #[enum_variants_strings_mappings("z", "zee")]
    Z {
        x: String,
        y: String,
    },
}

fn main() {
    assert_eq!(Variants::from_str("x"), Ok(Variants::X));
    assert_eq!(Variants::from_str("y"), Ok(Variants::Y(0)));
    assert_eq!(
        Variants::from_str("z"),
        Ok(Variants::Z {
            x: String::default(),
            y: String::default(),
        })
    );

    assert_eq!(Variants::X.to_str(), "x");
    assert_eq!(
        Variants::Z {
            x: "abc".into(),
            y: "xyz".into()
        }
        .to_str(),
        "zee"
    );
}

Identifier mapping

By default variant identifier/names are transformed to their snake case version

This can be changed via #[enum_variants_strings_transform(transform = ...)]

use enum_variants_strings::EnumVariantsStrings;

#[derive(Debug, PartialEq, EnumVariantsStrings)]
#[enum_variants_strings_transform(transform = "none")]
enum EnumA {
    Foo,
    Bar,
}

There are several transforms

  • "snake_case", separate uppercase and numeric boundaries with _ (default)
  • "kebab_case", snake case with - instead of underscores
  • "upper_case", uppercase of identifier in source
  • "lower_case", lowercase of identifier in source
  • "none", no mapping from the identifier in the source

Dependencies

~0.4–0.9MB
~20K SLoC