implement FlagOperations for all integers using macro
This commit is contained in:
parent
395cd49d4f
commit
deb188aa14
1 changed files with 23 additions and 18 deletions
41
src/lib.rs
41
src/lib.rs
|
@ -1,4 +1,3 @@
|
||||||
|
|
||||||
//region Clippy config
|
//region Clippy config
|
||||||
#![warn(clippy::pedantic)]
|
#![warn(clippy::pedantic)]
|
||||||
//disable silly rules
|
//disable silly rules
|
||||||
|
@ -12,20 +11,26 @@ 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),*) => {
|
||||||
fn has_one_bit_set(&self) -> bool {
|
$(
|
||||||
*self > 0 && *self & (*self - 1) == 0
|
impl FlagOperations for $ty {
|
||||||
}
|
fn has_one_bit_set(&self) -> bool {
|
||||||
|
*self > 0 && *self & (*self - 1) == 0
|
||||||
|
}
|
||||||
|
|
||||||
fn get_flag(&self, flag: Self) -> bool {
|
fn get_flag(&self, flag: Self) -> bool {
|
||||||
if flag.has_one_bit_set() {
|
if flag.has_one_bit_set() {
|
||||||
self & flag != 0
|
self & flag != 0
|
||||||
} else {
|
} else {
|
||||||
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue