use moa_bitops::bitmap::BitMap;
const INITIAL_CAP: usize = 64;
pub struct IdAllocator {
map: BitMap,
next: usize,
cap: usize,
}
impl IdAllocator {
pub const fn new() -> Self {
Self { map: BitMap::new(), next: 0, cap: 0 }
}
#[inline]
pub fn alloc(&mut self) -> usize {
if self.cap == 0 {
self.map.init(INITIAL_CAP);
self.cap = INITIAL_CAP;
}
let mut idx = self.map.find_next_zero_bit(self.next);
if idx == self.cap {
self.map.extend(self.cap);
self.cap *= 2;
idx = self.map.find_next_zero_bit(idx);
}
self.next = idx + 1;
self.map.set_bit(idx);
idx
}
#[inline]
pub fn free(&mut self, id: usize) {
if id >= self.cap {
return;
}
self.map.clear_bit(id);
if self.next > id {
self.next = id;
}
}
}
impl Default for IdAllocator {
fn default() -> Self {
Self::new()
}
}