Skip to content

Commit

Permalink
Fix EnumCount with disabled variants
Browse files Browse the repository at this point in the history
Do not include disabled variants in the count with EnumCount. Fixes #267
  • Loading branch information
schultetwin1 committed Apr 26, 2023
1 parent 635ab95 commit 7f476b7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
9 changes: 8 additions & 1 deletion strum_macros/src/macros/enum_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput};

use crate::helpers::variant_props::HasStrumVariantProperties;
use crate::helpers::{non_enum_error, HasTypeProperties};

pub(crate) fn enum_count_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let n = match &ast.data {
Data::Enum(v) => v.variants.len(),
Data::Enum(v) => v.variants.iter().try_fold(0usize, |acc, v| {
if v.get_variant_properties()?.disabled.is_none() {
Ok::<usize, syn::Error>(acc + 1usize)
} else {
Ok::<usize, syn::Error>(acc)
}
})?,
_ => return Err(non_enum_error()),
};
let type_properties = ast.get_type_properties()?;
Expand Down
17 changes: 17 additions & 0 deletions strum_tests/tests/enum_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,29 @@ enum Week {
Saturday,
}

#[allow(dead_code)]
#[derive(Debug, EnumCount, EnumIter)]
enum Pets {
Dog,
Cat,
Fish,
Bird,
#[strum(disabled)]
Hamster,
}

#[test]
fn simple_test() {
assert_eq!(7, Week::COUNT);
assert_eq!(Week::iter().count(), Week::COUNT);
}

#[test]
fn disabled_test() {
assert_eq!(4, Pets::COUNT);
assert_eq!(Pets::iter().count(), Pets::COUNT);
}

#[test]
fn crate_module_path_test() {
pub mod nested {
Expand Down

0 comments on commit 7f476b7

Please sign in to comment.