Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Const enum variants names #75

Merged
merged 7 commits into from Dec 12, 2019
Merged
3 changes: 2 additions & 1 deletion strum/src/lib.rs
Expand Up @@ -221,7 +221,8 @@ pub trait EnumCount {
/// A trait for retrieving the names of each variant in Enum. This trait can
/// be autoderived by `strum_macros`.
pub trait VariantNames {
fn variants() -> &'static [&'static str];
/// Names of the variants of this enum
const VARIANTS: &'static [&'static str];
}

#[cfg(feature = "derive")]
Expand Down
8 changes: 1 addition & 7 deletions strum_macros/src/macros/enum_variant_names.rs
Expand Up @@ -26,13 +26,7 @@ pub fn enum_variant_names_inner(ast: &syn::DeriveInput) -> TokenStream {

quote! {
impl #impl_generics ::strum::VariantNames for #name #ty_generics #where_clause {
/// Return a slice containing the names of the variants of this enum
#[allow(dead_code)]
fn variants() -> &'static [&'static str] {
&[
#(#names),*
]
}
const VARIANTS: &'static [&'static str] = &[ #(#names),* ];
}
}
}
17 changes: 7 additions & 10 deletions strum_tests/tests/enum_variant_names.rs
Expand Up @@ -15,7 +15,7 @@ fn simple() {
Yellow,
}

assert_eq!(&Color::variants(), &["Red", "Blue", "Yellow"]);
assert_eq!(Color::VARIANTS, &["Red", "Blue", "Yellow"]);
}

#[test]
Expand All @@ -29,7 +29,7 @@ fn variant_names_trait() {
}

fn generic_function<T: VariantNames>() {
assert_eq!(T::variants(), &["Red", "Blue", "Yellow"]);
assert_eq!(T::VARIANTS, &["Red", "Blue", "Yellow"]);
}

generic_function::<Color>();
Expand All @@ -47,10 +47,7 @@ fn plain_kebab() {
RebeccaPurple,
}

assert_eq!(
&Color::variants(),
&["red", "blue", "yellow", "rebecca-purple"]
);
assert_eq!(Color::VARIANTS, &["red", "blue", "yellow", "rebecca-purple"]);
}

#[test]
Expand All @@ -66,7 +63,7 @@ fn non_plain_camel() {
}

assert_eq!(
&Color::variants(),
Color::VARIANTS,
&["deep-pink", "green-yellow", "cornflower-blue", "other"]
);
}
Expand All @@ -83,14 +80,14 @@ fn clap_and_structopt() {
}

assert_eq!(
&Color::variants(),
Color::VARIANTS,
&["red", "blue", "yellow", "rebecca-purple"]
);

let _clap_example = clap::App::new("app").arg(
clap::Arg::with_name("color")
.long("color")
.possible_values(Color::variants())
.possible_values(Color::VARIANTS)
.case_insensitive(true),
);

Expand All @@ -101,7 +98,7 @@ fn clap_and_structopt() {
#[structopt(
long = "color",
default_value = "Color::Blue",
raw(possible_values = "Color::variants()")
raw(possible_values = "Color::VARIANTS")
)]
color: Color,
}
Expand Down