use crate::node::Node;
impl Node {
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
let mut cur = self;
for &i in path {
cur = cur.content.as_ref()?.get(i)?;
}
Some(cur)
}
pub fn node_at_mut(&mut self, path: &[usize]) -> Option<&mut Node> {
let mut cur = self;
for &i in path {
cur = cur.content.as_mut()?.get_mut(i)?;
}
Some(cur)
}
pub fn path_to(&self, mut pred: impl FnMut(&Node) -> bool) -> Option<Vec<usize>> {
let mut path = Vec::new();
if path_to_rec(self, &mut pred, &mut path) {
Some(path)
} else {
None
}
}
pub fn paths_to(&self, mut pred: impl FnMut(&Node) -> bool) -> Vec<Vec<usize>> {
let mut out = Vec::new();
let mut path = Vec::new();
paths_to_rec(self, &mut pred, &mut path, &mut out);
out
}
}
fn path_to_rec(node: &Node, pred: &mut impl FnMut(&Node) -> bool, path: &mut Vec<usize>) -> bool {
if pred(node) {
return true;
}
if let Some(children) = &node.content {
for (i, child) in children.iter().enumerate() {
path.push(i);
if path_to_rec(child, pred, path) {
return true;
}
path.pop();
}
}
false
}
fn paths_to_rec(
node: &Node,
pred: &mut impl FnMut(&Node) -> bool,
path: &mut Vec<usize>,
out: &mut Vec<Vec<usize>>,
) {
if pred(node) {
out.push(path.clone());
}
if let Some(children) = &node.content {
for (i, child) in children.iter().enumerate() {
path.push(i);
paths_to_rec(child, pred, path, out);
path.pop();
}
}
}