Skip to content

Commit

Permalink
API: Add clear function to bitwise
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
FedericoBruzzone committed Sep 15, 2022
1 parent 7682e8d commit 4c671a4
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/bitwise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -57,13 +59,43 @@ 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)]
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;
Expand Down

0 comments on commit 4c671a4

Please sign in to comment.