Skip to content

Commit

Permalink
Fix is_naturally_exhaustive test for usize/isize. (#116)
Browse files Browse the repository at this point in the history
Always return false in those cases (as is the case for u64/i64).
  • Loading branch information
fshaked authored Apr 15, 2023
1 parent d5662e4 commit f1ee727
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 35 deletions.
66 changes: 32 additions & 34 deletions num_enum/tests/from_primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,42 @@ mod core {}
mod num_enum {}
mod std {}

#[test]
fn has_from_primitive_number_u64() {
#[derive(Debug, Eq, PartialEq, FromPrimitive)]
#[repr(u64)]
enum Enum {
Zero = 0,
#[num_enum(default)]
NonZero = 1,
}

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

let one = Enum::from_primitive(1_u64);
assert_eq!(one, Enum::NonZero);

let two = Enum::from_primitive(2_u64);
assert_eq!(two, Enum::NonZero);
macro_rules! has_from_primitive_number {
( $type:ty ) => {{
#[derive(Debug, Eq, PartialEq, FromPrimitive)]
#[repr($type)]
enum Enum {
Zero = 0,
#[num_enum(default)]
NonZero = 1,
}

let zero = Enum::from_primitive(0 as $type);
assert_eq!(zero, Enum::Zero);

let one = Enum::from_primitive(1 as $type);
assert_eq!(one, Enum::NonZero);

let two = Enum::from_primitive(2 as $type);
assert_eq!(two, Enum::NonZero);
}};
}

#[test]
fn has_from_primitive_number() {
#[derive(Debug, Eq, PartialEq, FromPrimitive)]
#[repr(u8)]
enum Enum {
Zero = 0,
#[num_enum(default)]
NonZero = 1,
}

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

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

let two = Enum::from_primitive(2_u8);
assert_eq!(two, Enum::NonZero);
has_from_primitive_number!(u8);
has_from_primitive_number!(u16);
has_from_primitive_number!(u32);
has_from_primitive_number!(u64);
has_from_primitive_number!(usize);
has_from_primitive_number!(i8);
has_from_primitive_number!(i16);
has_from_primitive_number!(i32);
has_from_primitive_number!(i64);
has_from_primitive_number!(isize);
// repr with 128-bit type is unstable
// has_from_primitive_number!(u128);
// has_from_primitive_number!(i128);
}

#[test]
Expand Down
4 changes: 3 additions & 1 deletion num_enum_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,9 @@ impl EnumInfo {
.strip_prefix('i')
.or_else(|| repr_str.strip_prefix('u'));
if let Some(suffix) = suffix {
if let Ok(bits) = suffix.parse::<u32>() {
if suffix == "size" {
return Ok(false);
} else if let Ok(bits) = suffix.parse::<u32>() {
let variants = 1usize.checked_shl(bits);
return Ok(variants.map_or(false, |v| {
v == self
Expand Down

0 comments on commit f1ee727

Please sign in to comment.