grapes 0.3.0

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

/// A reference to a node in a [Tree]
///
/// The library guarantees that this references a valid node in the associated tree
#[derive(Clone, Debug)]
pub struct NodeRef<'a, T: Clone> {
    tree: &'a Tree<T>,
    index: NodeId,
}

impl<'a, T: Clone> Copy for NodeRef<'a, T> {}

impl<'a, T: Clone> NodeRef<'a, T> {
    #[must_use]
    pub(crate) fn new(tree: &'a Tree<T>, index: NodeId) -> Self {
        Self { tree, index }
    }

    /// The data associated with the node
    #[must_use]
    pub fn data(&self) -> &'a T {
        // todo: new lookup every time, bad. should we cache the pointer somehow since it can't change?
        &self.tree.arena[self.index.0].data
    }

    /// The node's ID
    #[must_use]
    pub fn id(&self) -> NodeId {
        self.index
    }

    /// Iterate over the node's children
    pub fn children(&self) -> Children<'a, T> {
        let first_child = self.tree.arena[self.index.0].first_child;
        Children::new(self.tree, first_child)
    }
}