#enum #derive #strings #string #macro #derive-macro #enum-variants #variant #enums #variants

enum-variants-strings

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

2 unstable releases

0.2.0 Apr 7, 2022
0.1.0 Dec 22, 2021

#1181 in Rust patterns

MIT license

4KB

Enum variants strings

Docs Crates

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 = ...)]

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

There are several transforms

  • "none", no mapping from source
  • "upper_case", uppercase of identifier in source
  • "lower_case", lowercase of identifier in source
  • "snake_case", (default)

Dependencies

~390–800KB
~18K SLoC