Derive Macro arg_enum_proc_macro::ArgEnum

source ·
#[derive(ArgEnum)]
{
    // Attributes available to this derive:
    #[arg_enum]
}
Expand description

Implement std::fmt::Display, std::str::FromStr and variants().

The invocation:

use arg_enum_proc_macro::ArgEnum;

#[derive(ArgEnum)]
enum Foo {
    A,
    /// Describe B
    #[arg_enum(alias = "Bar")]
    B,
    /// Describe C
    /// Multiline
    #[arg_enum(name = "Baz")]
    C,
}

produces:

enum Foo {
    A,
    B,
    C
}
impl ::std::str::FromStr for Foo {
    type Err = String;

    fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
        match s {
            "A" | _ if s.eq_ignore_ascii_case("A") => Ok(Foo::A),
            "B" | _ if s.eq_ignore_ascii_case("B") => Ok(Foo::B),
            "Bar" | _ if s.eq_ignore_ascii_case("Bar") => Ok(Foo::B),
            "Baz" | _ if s.eq_ignore_ascii_case("Baz") => Ok(Foo::C),
            _ => Err({
                let v = vec![ "A", "B", "Bar", "Baz" ];
                format!("valid values: {}", v.join(" ,"))
            }),
        }
    }
}
impl ::std::fmt::Display for Foo {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        match *self {
            Foo::A => write!(f, "A"),
            Foo::B => write!(f, "B"),
            Foo::C => write!(f, "C"),
        }
    }
}

impl Foo {
    /// Returns an array of valid values which can be converted into this enum.
    #[allow(dead_code)]
    pub fn variants() -> [&'static str; 4] {
        [ "A", "B", "Bar", "Baz", ]
    }
    #[allow(dead_code)]
    pub fn descriptions() -> [(&'static [&'static str], &'static [&'static str]) ;3] {
        [(&["A"], &[]),
         (&["B", "Bar"], &[" Describe B"]),
         (&["Baz"], &[" Describe C", " Multiline"]),]
    }
}