From 4c671a425015d1e7bc191d45f143147579f5809a Mon Sep 17 00:00:00 2001 From: Federico Bruzzone Date: Thu, 15 Sep 2022 16:14:54 +0200 Subject: [PATCH] API: Add `clear` function to `bitwise` These function complete the bitwise file. - The first one allow us to clean (set to 0) all bits from `msg` to `idx`; - The second one allow us to clean (set to 0) all bits from `idx` to `0` Signed-off-by: Federico Bruzzone --- src/bitwise.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/bitwise.rs b/src/bitwise.rs index 2bafcb20..89dba34e 100644 --- a/src/bitwise.rs +++ b/src/bitwise.rs @@ -8,6 +8,8 @@ pub trait Bits { fn toggle_bit(&mut self, bit_idx: u8); fn set_bit(&mut self, bit_idx: u8, value: bool); fn get_bit(self, bit_idx: u8) -> bool; + fn clear_bits_msb_to_idx(&mut self, bit_idx: u8); // msb: most significant bit + fn clear_bits_idx_to_0(&mut self, bit_idx: u8); } impl Bits for u32 { @@ -57,6 +59,22 @@ impl Bits for u32 { fn get_bit(self, bit_idx: u8) -> bool { self.is_bit_on(bit_idx) } + + /// To clear all bits from the `most significant bit` through `bit_idx` (inclusive) + fn clear_bits_msb_to_idx(&mut self, bit_idx: u8) { + debug_assert!(bit_idx < 32); + + let mask = (1 << bit_idx) - 1; + *self &= mask; + } + + /// To clear all bits from `bit_idx` through `0` (inclusive) + fn clear_bits_idx_to_0(&mut self, bit_idx: u8) { + debug_assert!(bit_idx < 32); + + let mask = -1_i32 << (bit_idx + 1); + *self &= mask as u32; + } } #[cfg(test)] @@ -64,6 +82,20 @@ mod tests { use super::*; use rand::Rng; + #[test] + fn test_clear_bits_msb_to_idx() { + let mut b = 0b11111111; + b.clear_bits_msb_to_idx(3); + println!("{}", b) + } + + #[test] + fn test_clear_bits_idx_to_0() { + let mut b = 0b11111; + b.clear_bits_idx_to_0(3); + println!("{}", b) + } + #[test] fn test_is_on() { let b = 0b110011101_u32;