enum-variants-strings

Crates.ioenum-variants-strings
lib.rsenum-variants-strings
version0.3.0
sourcesrc
created_at2021-12-22 10:43:59.945491
updated_at2024-03-01 09:03:39.539996
descriptionDerive macro for converting instances of enums to and from strs using variant names
homepage
repositoryhttps://github.com/kaleidawave/enum-variants-strings
max_upload_size
id501574
size6,936
Ben (kaleidawave)

documentation

README

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
Commit count: 17

cargo fmt