use crate::Rect;
use crate::dynamic::DynamicIndex;
pub(crate) const SLOTS: usize = DynamicIndex::NODE_CAPACITY + 1;
#[derive(Clone, Copy, Debug)]
pub(crate) enum Child {
Node(usize),
Entry(Rect, u32),
}
impl Child {
pub(crate) fn rect(&self, index: &DynamicIndex) -> Rect {
match *self {
Child::Node(slot) => index.arena[slot].rect,
Child::Entry(rect, _) => rect,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct DNode {
pub(crate) rect: Rect,
pub(crate) level: u32,
children: [Option<Child>; SLOTS],
count: usize,
}
impl DNode {
pub(crate) fn with_first(level: u32, first: Child, rect: Rect) -> DNode {
let mut children = [None; SLOTS];
children[0] = Some(first);
DNode {
rect,
level,
children,
count: 1,
}
}
pub(crate) fn len(&self) -> usize {
self.count
}
pub(crate) fn children(&self) -> impl DoubleEndedIterator<Item = &Child> {
self.children[..self.count].iter().flatten()
}
pub(crate) fn child(&self, at: usize) -> Child {
self.children[at].expect("child within count")
}
pub(crate) fn push(&mut self, child: Child) {
assert!(self.count < SLOTS, "a node grew past its overflow slot");
self.children[self.count] = Some(child);
self.count += 1;
}
pub(crate) fn remove(&mut self, at: usize) -> Child {
let taken = self.children[at].expect("child within count");
for i in at..self.count - 1 {
self.children[i] = self.children[i + 1];
}
self.count -= 1;
self.children[self.count] = None;
taken
}
pub(crate) fn set_children(&mut self, kept: &[Child]) {
assert!(kept.len() <= SLOTS);
self.children = [None; SLOTS];
for (slot, child) in self.children.iter_mut().zip(kept.iter()) {
*slot = Some(*child);
}
self.count = kept.len();
}
pub(crate) fn exact_box(&self, index: &DynamicIndex) -> Rect {
let mut boxes = self.children().map(|c| c.rect(index));
let first = boxes.next().expect("a node is never empty");
boxes.fold(first, |acc, r| acc.union(&r))
}
}