#enums #variant #display #automatic #from-str #generate #others

macro to_and_fro

Proc macro for generating implimentations of Display and FromStr for Enum Variants

15 releases (5 breaking)

new 0.6.0 Jul 26, 2024
0.5.3 May 28, 2024
0.5.1 Apr 7, 2024
0.5.0 Feb 20, 2024
0.1.0 Nov 24, 2023

#1996 in Procedural macros


Used in 3 crates

MIT license

19KB
272 lines

To, and Fro

Automatic implimentations for Display, FromStr, and others for Enums.

Package available through cargo

cargo add to_and_fro

Implimentation

#[derive(ToAndFro)]
pub enum TestEnum {
  ValueOne,
  ValueTwo,
  ValueThree
}

TestEnum::ValueOne.to_string()  // "ValueOne"
TestEnum::from_str("ValueTwo")  //  TestEnum::ValueTwo

TestEnum::from_str("ValueFour") // anyhow::Error("Invalid variant ValueFour for enum TestEnum")

Casing

#[derive(ToAndFro)]
pub enum TestEnum {
  #[input_case("snake")]        // FromStr will parse only snake_case input
  ValueOne,
  #[output_case("kebab")]       // Display methods will produce a kebab-case output
  ValueTwo,
  ValueThree                    // Defaults to as written input, and as-written output
}

Fallback for FromStr

#[derive(ToAndFro)]
#[default("Fallback")]
pub enum TestEnum {
  Fallback,
  ValueOne,
  ValueTwo,
  ValueThree
}

TestEnum::from_str("ValueFour") // TestEnum::Fallback

Disallow field to be parsed FromStr

#[derive(ToAndFro)]
pub enum TestEnum {
  #[reject]
  ValueOne,
  ValueTwo
}

TestEnum::from_str("ValueOne")  // anyhow::Error("Invalid variant ValueOne for enum TestEnum")

Implement Serialize and Deserialize from serde

#[derive(ToAndFro)]
#[serde]
pub enum TestEnum {
  ValueOne,
  ValueTwo,
  ValueThree
}

List of supported cases:

Feedback

I appreciate all feedback, in whatever forms they might take.
If you're looking to specifically make a Bug Report, or Suggest a Feature, please do so through their templates in the issues section.

  • Synstructure, a crate that provides helper types for matching against enum variants, and extracting bindings to each of the fields in the deriving Struct or Enum in a generic way.
  • Heck, a crate that exists to provide case conversion between common cases like CamelCase and snake_case. It is intended to be unicode aware, internally consistent, and reasonably well performing.

Dependencies

~0.8–1.6MB
~35K SLoC