implement FlagOperations for all integers using macro

This commit is contained in:
LordMZTE 2020-09-07 22:54:30 +02:00
parent 395cd49d4f
commit deb188aa14

View file

@ -1,4 +1,3 @@
//region Clippy config //region Clippy config
#![warn(clippy::pedantic)] #![warn(clippy::pedantic)]
//disable silly rules //disable silly rules
@ -12,8 +11,10 @@ clippy::cast_lossless, clippy::cast_possible_wrap, //lossy casts are required to
pub mod logging; pub mod logging;
pub mod key; pub mod key;
//TODO generify this? macro_rules! impl_flag_operations {
impl FlagOperations for u32 { ($($ty:ty),*) => {
$(
impl FlagOperations for $ty {
fn has_one_bit_set(&self) -> bool { fn has_one_bit_set(&self) -> bool {
*self > 0 && *self & (*self - 1) == 0 *self > 0 && *self & (*self - 1) == 0
} }
@ -25,7 +26,11 @@ impl FlagOperations for u32 {
panic!("flag must have 1 bit set") panic!("flag must have 1 bit set")
} }
} }
}
)*
};
} }
impl_flag_operations!(usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128);
trait FlagOperations { trait FlagOperations {
///true if exactly 1 bit of the given number is set ///true if exactly 1 bit of the given number is set
@ -42,19 +47,19 @@ mod tests {
#[test] #[test]
fn get_flag() { fn get_flag() {
assert!(5u32.get_flag(1 << 2)); assert!(5.get_flag(1 << 2));
assert!(!3u32.get_flag(1 << 2)); assert!(!3.get_flag(1 << 2));
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn get_flag_panic() { fn get_flag_panic() {
0u32.get_flag(3); 0.get_flag(3);
} }
#[test] #[test]
fn has_one_bit_set() { fn has_one_bit_set() {
assert!(1u32.has_one_bit_set()); assert!(1.has_one_bit_set());
assert!(!3u32.has_one_bit_set()); assert!(!3.has_one_bit_set());
} }
} }