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

macro to_and_fro

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

12 releases (4 breaking)

0.5.1 Apr 7, 2024
0.5.0 Feb 20, 2024
0.4.0 Nov 28, 2023
0.3.5 Nov 27, 2023
0.1.0 Nov 24, 2023

#1815 in Procedural macros

Download history 131/week @ 2024-02-14 54/week @ 2024-02-21 27/week @ 2024-02-28 2/week @ 2024-03-06 11/week @ 2024-03-13 6/week @ 2024-03-20 3/week @ 2024-03-27 112/week @ 2024-04-03 72/week @ 2024-04-10

193 downloads per month
Used in 2 crates

MIT license

17KB
233 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")

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.5–1MB
~21K SLoC