Skip to content

Commit

Permalink
fix: filter catch_all variant in EnumInfo methods (#150)
Browse files Browse the repository at this point in the history
This commit filters out catch_all variant in the `variant_idents` and
`variant_expressions` of `EnumInfo`. This allows the catch_all variant
to be in the middle of enum.

A test of catch_all variant in the middle of enum is also added.

Fix #149
  • Loading branch information
duskmoon314 authored Jul 29, 2024
1 parent c12fb92 commit b006342
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
24 changes: 24 additions & 0 deletions num_enum/tests/from_primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,30 @@ fn from_primitive_number_catch_all() {
assert_eq!(two, Enum::NonZero(2_u8));
}

#[test]
fn from_primitive_number_catch_all_in_middle() {
#[derive(Debug, PartialEq, Eq, FromPrimitive)]
#[repr(u8)]
enum Enum {
Zero = 0,
#[num_enum(catch_all)]
Else(u8) = 2,
One = 1,
}

let zero = Enum::from_primitive(0_u8);
assert_eq!(zero, Enum::Zero);

let one = Enum::from_primitive(1_u8);
assert_eq!(one, Enum::One);

let two = Enum::from_primitive(2_u8);
assert_eq!(two, Enum::Else(2_u8));

let three = Enum::from_primitive(3_u8);
assert_eq!(three, Enum::Else(3_u8));
}

#[cfg(feature = "complex-expressions")]
#[test]
fn from_primitive_number_with_inclusive_range() {
Expand Down
2 changes: 2 additions & 0 deletions num_enum_derive/src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl EnumInfo {
pub(crate) fn variant_idents(&self) -> Vec<Ident> {
self.variants
.iter()
.filter(|variant| !variant.is_catch_all)
.map(|variant| variant.ident.clone())
.collect()
}
Expand All @@ -81,6 +82,7 @@ impl EnumInfo {
pub(crate) fn variant_expressions(&self) -> Vec<Vec<Expr>> {
self.variants
.iter()
.filter(|variant| !variant.is_catch_all)
.map(|variant| variant.all_values().cloned().collect())
.collect()
}
Expand Down

0 comments on commit b006342

Please sign in to comment.