use alloc::vec::Vec;
use crate::Rect;
use crate::dynamic::DynamicIndex;
use crate::dynamic::node::Child;
impl DynamicIndex {
pub fn remove(&mut self, rect: &Rect, id: u32) -> bool {
let Some(root) = self.root else {
return false;
};
if !self.arena[root].rect.contains_rect(rect) {
return false;
}
let mut path: Vec<usize> = Vec::with_capacity(8);
let Some((leaf, at)) = self.find_entry(root, rect, id, &mut path) else {
return false;
};
self.arena[leaf].remove(at);
self.len -= 1;
self.condense(&path);
true
}
fn find_entry(
&self,
slot: usize,
rect: &Rect,
id: u32,
path: &mut Vec<usize>,
) -> Option<(usize, usize)> {
path.push(slot);
let node = &self.arena[slot];
for (at, child) in node.children().enumerate() {
match *child {
Child::Entry(stored, stored_id) => {
if stored_id == id && stored == *rect {
return Some((slot, at));
}
}
Child::Node(child_slot) => {
if self.arena[child_slot].rect.contains_rect(rect) {
if let Some(found) = self.find_entry(child_slot, rect, id, path) {
return Some(found);
}
}
}
}
}
path.pop();
None
}
fn condense(&mut self, path: &[usize]) {
let mut orphans: Vec<(Child, u32)> = Vec::new();
for depth in (1..path.len()).rev() {
let slot = path[depth];
if self.arena[slot].len() < Self::MIN_FILL {
let parent = path[depth - 1];
let at = self.arena[parent]
.children()
.position(|c| matches!(*c, Child::Node(s) if s == slot))
.expect("a path node is its parent's child");
self.arena[parent].remove(at);
let level = self.arena[slot].level;
for child in self.arena[slot].children() {
orphans.push((*child, level));
}
self.release(slot);
} else {
self.arena[slot].rect = self.arena[slot].exact_box(self);
}
}
let root = path[0];
if self.arena[root].len() == 0 {
self.release(root);
self.root = None;
} else {
self.arena[root].rect = self.arena[root].exact_box(self);
}
for (child, level) in orphans {
let mut reinserted: u64 = 0;
self.place(child, level, &mut reinserted);
}
while let Some(root) = self.root {
let node = &self.arena[root];
if node.level == 0 || node.len() > 1 {
break;
}
let Child::Node(only) = node.child(0) else {
unreachable!("an internal node holds subtrees");
};
self.release(root);
self.root = Some(only);
}
}
}