use super::Allocator; use alloc::{vec, vec::Vec}; use bit_field::BitArray;
pubstructSegmentTreeAllocator { tree: Vec<u8>, }
impl Allocator for SegmentTreeAllocator { fnnew(capacity: usize) -> Self { let leaf_count = capacity.next_power_of_two(); letmut tree = vec![0u8; leaf_count * 2];
for index in (capacity..leaf_count){ tree.set_bit(index, true); }
for index in (1..leaf_count).rev() { let value = tree.get_bit(2 * index) && tree.get_bit(2 * index + 1) && tree.get_bit(index); tree.set_bit(index, value); }
Self{ tree }
}
fnalloc(&mutself) -> Option<usize> { letmut index = 1; ifself.tree.get_bit(index) { returnNone; }else{ while index < self.tree.len()/2{ if(!self.tree.get_bit(index * 2)){ index *= 2; }elseif(!self.tree.get_bit(index * 2 + 1)){ index = index * 2 + 1; }else { panic!("Damaged Segement Tree!"); } } } self.uploadNode(index, true); returnSome(index - self.tree.len()/2); }
fndealloc(&mutself, index: usize) { let node = index + self.tree.len()/2; self.uploadNode(node, false); } }
impl SegmentTreeAllocator{
fnuploadNode(&mutself, mut index: usize, value: bool){ self.tree.set_bit(index, value); while index > 1 { index /= 2; let v = self.tree.get_bit(2 * index) && self.tree.get_bit(2 * index + 1); self.tree.set_bit(index, v); } } }