grapes 0.3.0

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

use crate::graph::{Edge, EdgeId, Graph, NodeRef};

/// Reference to a directed edge in a [Graph]
///
/// Also known as an arc
///
/// The library guarantees that this references a valid edge
#[derive(Clone, Debug)]
pub struct EdgeRef<'a, NodeData: Clone, EdgeData: Clone> {
    graph: &'a Graph<NodeData, EdgeData>,
    index: EdgeId,
}

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

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

    /// Get the `Edge` this [EdgeRef] is pointing to
    ///
    /// (internal convenience method)
    #[must_use]
    fn edge(&self) -> &'a Edge<EdgeData> {
        self.graph
            .edges
            .get(self.index.0)
            .expect("invariant violation: EdgeRef points to invalid edge")
    }

    /// The data associated with this edge
    ///
    /// (aka the edge weight)
    #[must_use]
    pub fn data(&self) -> &'a EdgeData {
        &self.edge().data
    }

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

    /// Reference to the Node from which the edge starts
    ///
    /// (aka the tail of the arc)
    #[must_use]
    pub fn get_from_node(&self) -> NodeRef<'a, NodeData, EdgeData> {
        NodeRef::new(self.graph, self.edge().from)
    }

    /// Reference to the Node the edge points to
    ///
    /// (aka the head of the arc)
    #[must_use]
    pub fn get_to_node(&self) -> NodeRef<'a, NodeData, EdgeData> {
        NodeRef::new(self.graph, self.edge().to)
    }
}