use super::*;
#[derive(Debug, Clone, Copy)]
pub struct BitRef<'map, const BYTES: usize> {
pub(super) value: bool,
_map: &'map Bitmap<BYTES>,
}
#[derive(Debug)]
pub struct BitRefMut<'map, const BYTES: usize> {
idx: usize,
pub(super) value: bool,
map: &'map mut Bitmap<BYTES>,
}
impl<'map, const BYTES: usize> BitRef<'map, BYTES> {
pub fn new(map: &'map Bitmap<BYTES>, index: usize) -> Self {
if __out_bound(BYTES, index) {
panic!("Bitmap: indexing out of range");
}
let (byte, bit) = __idx_1dto2d(index);
Self {
value: map.__get_bool(byte, bit),
_map: map,
}
}
}
impl<'map, const BYTES: usize> BitRefMut<'map, BYTES> {
#[inline]
fn __get_byte(&mut self) -> &mut u8 {
let by = __idx_get_byte(self.idx);
self.map.__get_mut_u8(by)
}
pub fn new(map: &'map mut Bitmap<BYTES>, index: usize) -> Self {
if __out_bound(BYTES, index) {
panic!("Bitmap: indexing out of range");
}
let (byte, bit) = __idx_1dto2d(index);
let value = map.__get_bool(byte, bit);
Self {
idx: index,
value: value,
map: map,
}
}
pub fn set(&mut self) -> &mut Self {
let mask = 1 << (__idx_get_bit(self.idx));
__byte_or_u8(self.__get_byte(), mask);
self.value = true;
self
}
pub fn reset(&mut self) -> &mut Self {
let mask = !(1 << (__idx_get_bit(self.idx)));
__byte_and_u8(self.__get_byte(), mask);
self.value = false;
self
}
pub fn flip(&mut self) -> &mut Self {
let mask = 1 << __idx_get_bit(self.idx);
let byte = self.__get_byte();
*byte ^= mask;
self.value = !self.value;
self
}
}
impl<const BYTES: usize> Bitmap<BYTES> {
pub fn at<'map>(&'map self, index: usize) -> BitRef<'map, BYTES> {
BitRef::new(self, index)
}
pub fn at_mut<'map>(&'map mut self, index: usize) -> BitRefMut<'map, BYTES> {
BitRefMut::new(self, index)
}
}