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