Skip to content

Commit

Permalink
Const enum variants names (#75)
Browse files Browse the repository at this point in the history
* Add implementing const `VARIANTS` by `EnumVariantsNames`, deprecate old `::variants`

* Move `const VARIANTS` to `VariantNames` trait

* Remove `VariantNames::variants` function
  • Loading branch information
WaffleLapkin authored and peter-glotfelty committed Dec 12, 2019
1 parent a94c8b0 commit eea32db
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 18 deletions.
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

0 comments on commit eea32db

Please sign in to comment.