use core::convert::Infallible;
use core::ops::ControlFlow;
use super::Index;
use crate::Rect;
pub(super) const MAX_DEPTH: usize = (usize::BITS as usize).div_ceil(4) + 1;
pub(super) const STACK_CAPACITY: usize = (Index::NODE_CAPACITY - 1) * MAX_DEPTH + 1;
pub(super) struct Stack {
items: [usize; STACK_CAPACITY],
len: usize,
limit: usize,
#[cfg(test)]
high: usize,
}
impl Stack {
pub(super) const fn new(depth: usize) -> Stack {
Stack {
items: [0; STACK_CAPACITY],
len: 0,
limit: (Index::NODE_CAPACITY - 1) * depth + 1,
#[cfg(test)]
high: 0,
}
}
fn len(&self) -> usize {
self.len
}
fn push(&mut self, node: usize) {
debug_assert!(
self.len < self.limit,
"search stack would exceed (M - 1) * depth + 1 = {}",
self.limit
);
match self.items.get_mut(self.len) {
Some(slot) => *slot = node,
None => panic!("situs: search stack exceeded its proven bound of {STACK_CAPACITY}"),
}
self.len += 1;
#[cfg(test)]
{
self.high = self.high.max(self.len);
}
}
fn pop(&mut self) -> Option<usize> {
self.len = self.len.checked_sub(1)?;
Some(self.items[self.len])
}
}
impl Index {
pub fn query(&self, window: &Rect, mut visit: impl FnMut(u32)) {
let ControlFlow::Continue(()) = self.try_query::<Infallible>(window, |id| {
visit(id);
ControlFlow::Continue(())
});
}
pub fn try_query<B>(
&self,
window: &Rect,
mut visit: impl FnMut(u32) -> ControlFlow<B>,
) -> ControlFlow<B> {
debug_assert!(self.depth <= MAX_DEPTH, "depth above the proven bound");
let mut stack = Stack::new(self.depth);
self.search::<B, true>(window, &mut stack, &mut visit)
}
pub(super) fn search<B, const SHORTCUT: bool>(
&self,
window: &Rect,
stack: &mut Stack,
visit: &mut impl FnMut(u32) -> ControlFlow<B>,
) -> ControlFlow<B> {
if self.nodes.is_empty() {
return ControlFlow::Continue(());
}
stack.push(0);
while let Some(i) = stack.pop() {
let node = &self.nodes[i];
if !node.rect.intersects(window) {
continue;
}
if SHORTCUT && window.contains_rect(&node.rect) {
self.emit_subtree(i, stack, visit)?;
} else if node.leaf {
for (rect, id) in &self.entries[node.first..node.end] {
if rect.intersects(window) {
visit(*id)?;
}
}
} else {
for child in (node.first..node.end).rev() {
stack.push(child);
}
}
}
ControlFlow::Continue(())
}
fn emit_subtree<B>(
&self,
top: usize,
stack: &mut Stack,
visit: &mut impl FnMut(u32) -> ControlFlow<B>,
) -> ControlFlow<B> {
let base = stack.len();
stack.push(top);
while stack.len() > base {
let Some(i) = stack.pop() else { break };
let n = &self.nodes[i];
if n.leaf {
for &(_, id) in &self.entries[n.first..n.end] {
visit(id)?;
}
} else {
for c in (n.first..n.end).rev() {
stack.push(c);
}
}
}
ControlFlow::Continue(())
}
}
#[cfg(test)]
mod tests;