grapes 0.3.0

Persistent graph data structures: Tree, Graph, Arena & more
Documentation
use crate::tree::node_ref::NodeRef;
use crate::tree::{NodeId, Tree};

/// An iterator over the children of a node
#[derive(Clone, Debug)]
#[must_use]
pub struct Children<'a, T: Clone> {
    tree: &'a Tree<T>,
    next_index: Option<NodeId>,
}

impl<'a, T: Clone> Children<'a, T> {
    pub(crate) fn new(tree: &'a Tree<T>, next_index: Option<NodeId>) -> Self {
        Self { tree, next_index }
    }
}

impl<'a, T: Clone> Iterator for Children<'a, T> {
    type Item = NodeRef<'a, T>;

    fn next(&mut self) -> Option<Self::Item> {
        let current_index = self.next_index?;
        let node = &self.tree.arena[current_index.0];
        self.next_index = node.next_sibling;
        Some(NodeRef::new(self.tree, current_index))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn no_children() {
        let tree = Tree::new_with_root(42);
        let root = tree.root();
        let mut iterator = root.children();
        assert!(iterator.next().is_none());
    }

    #[test]
    fn root_children() {
        let mut tree = Tree::new_with_root(42);
        let mut root = tree.root_mut();
        root.push_front_child(43);
        root.push_front_child(44);
        root.push_front_child(45);

        let root = tree.root();
        let mut iterator = root.children();
        assert_eq!(iterator.next().unwrap().data(), &45);
        assert_eq!(iterator.next().unwrap().data(), &44);
        assert_eq!(iterator.next().unwrap().data(), &43);
        assert!(iterator.next().is_none());
    }
}