bitmap.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. pub struct Bitmap<'a>(&'a mut [u8]);
  2. impl<'a> Bitmap<'a> {
  3. pub fn new(bmap: &'a mut [u8]) -> Self {
  4. Self(bmap)
  5. }
  6. pub fn as_raw(&self) -> &[u8] {
  7. self.0
  8. }
  9. pub fn is_bit_clear(&self, bit: usize) -> bool {
  10. self.0[bit / 8] & (1 << (bit % 8)) == 0
  11. }
  12. pub fn set_bit(&mut self, bit: usize) {
  13. self.0[bit / 8] |= 1 << (bit % 8);
  14. }
  15. pub fn clear_bit(&mut self, bit: usize) {
  16. self.0[bit / 8] &= !(1 << (bit % 8));
  17. }
  18. /// Find the first clear bit in the range `[start, end)`
  19. pub fn first_clear_bit(&self, start: usize, end: usize) -> Option<usize> {
  20. let end = core::cmp::min(end, self.0.len() * 8);
  21. for i in start..end {
  22. if self.is_bit_clear(i) {
  23. return Some(i);
  24. }
  25. }
  26. None
  27. }
  28. /// Find the first clear bit in the range `[start, end)` and set it if found
  29. pub fn find_and_set_first_clear_bit(&mut self, start: usize, end: usize) -> Option<usize> {
  30. self.first_clear_bit(start, end).map(|bit| {
  31. self.set_bit(bit);
  32. bit
  33. })
  34. }
  35. }