grapes/graph/
edge_ref.rs

1//! Immutable references to edges
2
3use crate::graph::{Edge, EdgeId, Graph, NodeRef};
4
5/// Reference to a directed edge in a [Graph]
6///
7/// Also known as an arc
8///
9/// The library guarantees that this references a valid edge
10#[derive(Clone, Debug)]
11pub struct EdgeRef<'a, NodeData: Clone, EdgeData: Clone> {
12    graph: &'a Graph<NodeData, EdgeData>,
13    index: EdgeId,
14}
15
16impl<'a, NodeData: Clone, EdgeData: Clone> Copy for EdgeRef<'a, NodeData, EdgeData> {}
17
18impl<'a, NodeData: Clone, EdgeData: Clone> EdgeRef<'a, NodeData, EdgeData> {
19    #[must_use]
20    pub(crate) fn new(graph: &'a Graph<NodeData, EdgeData>, index: EdgeId) -> Self {
21        Self { graph, index }
22    }
23
24    /// Get the `Edge` this [EdgeRef] is pointing to
25    ///
26    /// (internal convenience method)
27    #[must_use]
28    fn edge(&self) -> &'a Edge<EdgeData> {
29        self.graph
30            .edges
31            .get(self.index.0)
32            .expect("invariant violation: EdgeRef points to invalid edge")
33    }
34
35    /// The data associated with this edge
36    ///
37    /// (aka the edge weight)
38    #[must_use]
39    pub fn data(&self) -> &'a EdgeData {
40        &self.edge().data
41    }
42
43    /// The edge's identifier
44    ///
45    /// You can use this to later reference the edge in the graph (if it still exists)
46    #[must_use]
47    pub fn id(&self) -> EdgeId {
48        self.index
49    }
50
51    /// Reference to the Node from which the edge starts
52    ///
53    /// (aka the tail of the arc)
54    #[must_use]
55    pub fn get_from_node(&self) -> NodeRef<'a, NodeData, EdgeData> {
56        NodeRef::new(self.graph, self.edge().from)
57    }
58
59    /// Reference to the Node the edge points to
60    ///
61    /// (aka the head of the arc)
62    #[must_use]
63    pub fn get_to_node(&self) -> NodeRef<'a, NodeData, EdgeData> {
64        NodeRef::new(self.graph, self.edge().to)
65    }
66}