const NATIVE_DEPTH: usize = 8;
pub trait Nested: Sized {
const LEAF: Self;
fn parts(&self) -> impl DoubleEndedIterator<Item = &Self>;
fn parts_mut(&mut self) -> impl Iterator<Item = &mut Self>;
fn fold<F: Fold<Self>>(&self, fold: &mut F) -> F::Made {
fold_within(self, fold, NATIVE_DEPTH)
}
fn same_tree(&self, other: &Self, mut same_node: impl FnMut(&Self, &Self) -> bool) -> bool {
same_within(self, other, &mut same_node, NATIVE_DEPTH)
}
fn free_parts(&mut self) {
free_within(self, NATIVE_DEPTH);
}
}
pub trait Fold<N>: Sized {
type Made;
fn open(&mut self, node: &N) -> Option<Self::Made>;
fn join(&mut self, node: &N, part: impl FnMut(&mut Self, &N) -> Self::Made) -> Self::Made;
}
fn fold_within<N: Nested, F: Fold<N>>(node: &N, fold: &mut F, room: usize) -> F::Made {
if let Some(made) = fold.open(node) {
return made;
}
match room.checked_sub(1) {
Some(room) => fold.join(node, |fold, part| fold_within(part, fold, room)),
None => fold_on_heap(node, fold),
}
}
fn fold_on_heap<N: Nested, F: Fold<N>>(node: &N, fold: &mut F) -> F::Made {
enum Work<'t, N> {
Open(&'t N),
Join(&'t N, usize),
}
let mut work: Vec<Work<'_, N>> = node.parts().rev().map(Work::Open).collect();
let mut made = Vec::new();
while let Some(next) = work.pop() {
match next {
Work::Open(node) => {
if let Some(value) = fold.open(node) {
made.push(value);
} else {
work.push(Work::Join(node, node.parts().count()));
work.extend(node.parts().rev().map(Work::Open));
}
}
Work::Join(node, count) => {
let value = join_made(fold, node, made.drain(made.len() - count..));
made.push(value);
}
}
}
join_made(fold, node, made.drain(..))
}
fn join_made<N, F: Fold<N>>(
fold: &mut F,
node: &N,
mut made: impl Iterator<Item = F::Made>,
) -> F::Made {
fold.join(node, |_, _| {
made.next()
.expect("a join takes each of its node's parts once")
})
}
fn walk<N: Nested>(node: &N) -> impl Iterator<Item = &N> {
let mut next = Some(node);
let mut later = Vec::new();
std::iter::from_fn(move || {
let node = next.take().or_else(|| later.pop())?;
let mut parts = node.parts();
next = parts.next();
later.extend(parts.rev());
Some(node)
})
}
fn same_within<N: Nested>(
node: &N,
other: &N,
same_node: &mut impl FnMut(&N, &N) -> bool,
room: usize,
) -> bool {
if !same_node(node, other) {
return false;
}
let Some(room) = room.checked_sub(1) else {
let mut others = walk(other);
return walk(node).all(|node| others.next().is_some_and(|other| same_node(node, other)));
};
node.parts()
.zip(other.parts())
.all(|(part, other)| same_within(part, other, same_node, room))
}
fn free_within<N: Nested>(node: &mut N, room: usize) {
for part in node.parts_mut() {
if part.parts().next().is_none() {
continue;
}
let mut nested = std::mem::replace(part, N::LEAF);
if let Some(room) = room.checked_sub(1) {
free_within(&mut nested, room);
} else {
let mut held = vec![nested];
while let Some(mut node) = held.pop() {
for part in node.parts_mut() {
if part.parts().next().is_some() {
held.push(std::mem::replace(part, N::LEAF));
}
}
}
}
}
}