Skip to main content

jstd/graph/
edge.rs

1//! Edge views for immutable and mutable graph access.
2use crate::graph::{
3    Graph, GraphMut,
4    node::{Node, NodeMut},
5};
6
7/// Typed edge handle trait for immutable graph references.
8pub trait Edge<'graph> {
9    type Graph: Graph;
10
11    fn new(id: <Self::Graph as Graph>::EdgeId, graph: &'graph Self::Graph) -> Self;
12
13    /// Returns this edge identifier.
14    fn id(&self) -> <Self::Graph as Graph>::EdgeId;
15
16    /// Returns the backing graph reference for this edge.
17    fn graph(&self) -> &'graph Self::Graph;
18
19    /// Returns the source node's id for this edge.
20    #[allow(clippy::wrong_self_convention)]
21    fn from_id(&self) -> <Self::Graph as Graph>::NodeId;
22
23    /// Returns the destination node's id for this edge.
24    fn to_id(&self) -> <Self::Graph as Graph>::NodeId;
25
26    /// Returns the source node for this edge
27    fn from(&self) -> <Self::Graph as Graph>::Node<'graph> {
28        let id = self.from_id();
29        <Self::Graph as Graph>::Node::new(id, self.graph())
30    }
31
32    /// Returns the destination node for this edge
33    fn to(&self) -> <Self::Graph as Graph>::Node<'graph> {
34        let id = self.to_id();
35        <Self::Graph as Graph>::Node::new(id, self.graph())
36    }
37
38    /// Returns `true` when this edge starts and ends at the same node.
39    fn is_loop(&self) -> bool {
40        self.from_id() == self.to_id()
41    }
42}
43
44pub trait EdgeMut<'graph> {
45    type Graph: GraphMut;
46
47    fn new(id: <Self::Graph as Graph>::EdgeId, graph: &'graph mut Self::Graph) -> Self;
48
49    /// Returns this edge identifier.
50    fn id(&self) -> <Self::Graph as Graph>::EdgeId;
51
52    /// Returns the backing graph reference for this edge.
53    fn graph(&mut self) -> &mut Self::Graph;
54
55    /// Returns the source node's id for this edge.
56    #[allow(clippy::wrong_self_convention)]
57    fn from_id(&self) -> <Self::Graph as Graph>::NodeId;
58
59    /// Returns mutable access to the source node for this edge.
60    fn from(&mut self) -> <Self::Graph as GraphMut>::NodeMut<'_> {
61        let id = self.from_id();
62        <Self::Graph as GraphMut>::NodeMut::new(id, self.graph())
63    }
64
65    /// Returns the destination node's id for this edge.
66    fn to_id(&self) -> <Self::Graph as Graph>::NodeId;
67
68    /// Returns mutable access to the destination node for this edge.
69    fn to(&mut self) -> <Self::Graph as GraphMut>::NodeMut<'_> {
70        let id = self.to_id();
71        <Self::Graph as GraphMut>::NodeMut::new(id, self.graph())
72    }
73
74    /// Redirects this edge to originate from `node` instead of its current source.
75    fn set_from(&mut self, node: <Self::Graph as Graph>::NodeId);
76
77    /// Returns an immutable view of this edge handle.
78    fn as_ref(&mut self) -> <Self::Graph as Graph>::Edge<'_> {
79        <Self::Graph as Graph>::Edge::new(self.id(), &*self.graph())
80    }
81}