grapes 0.3.0

Persistent graph data structures: Tree, Graph, Arena & more
Documentation
//! Immutable references to nodes

use crate::graph::{EdgesFrom, EdgesTo, Graph, Node, NodeId};

/// Reference to a node in a [Graph]
///
/// The library guarantees that this references a valid node
#[derive(Clone, Debug)]
pub struct NodeRef<'a, NodeData: Clone, EdgeData: Clone> {
    graph: &'a Graph<NodeData, EdgeData>,
    index: NodeId,
}

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

impl<'a, NodeData: Clone, EdgeData: Clone> NodeRef<'a, NodeData, EdgeData> {
    #[must_use]
    pub(crate) fn new(graph: &'a Graph<NodeData, EdgeData>, index: NodeId) -> Self {
        Self { graph, index }
    }

    /// Get the node this [NodeRef] points to
    ///
    /// (internal convenience method)
    #[must_use]
    fn node(&self) -> &'a Node<NodeData> {
        self.graph
            .nodes
            .get(self.index.0)
            .expect("invariant violation: NodeRef points to invalid node")
    }
    /// The data associated with the node
    ///
    /// (a.k.a. the node weight)
    #[must_use]
    pub fn data(&self) -> &'a NodeData {
        &self.node().data
    }

    /// The node's identifier
    ///
    /// You can use this to later reference the node in the graph (if it still exists)
    #[must_use]
    pub fn id(&self) -> NodeId {
        self.index
    }

    /// Iterate over edges leaving this node
    ///
    /// Order is unspecified.
    pub fn iter_edges_from(&self) -> EdgesFrom<'a, NodeData, EdgeData> {
        EdgesFrom::new(self.graph, self.node().first_edge_from)
    }

    /// Iterate over edges entering this node
    ///
    /// Order is unspecified.
    pub fn iter_edges_to(&self) -> EdgesTo<'a, NodeData, EdgeData> {
        EdgesTo::new(self.graph, self.node().first_edge_to)
    }
}