Skip to main content

sim_lib_discrete_graph/
edge.rs

1//! Edge records and graph directedness.
2
3/// Whether a graph's edges are directed or undirected.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Directedness {
6    /// Edges are one-way (`source -> target`).
7    Directed,
8    /// Edges are two-way; one record stands for both directions.
9    Undirected,
10}
11
12/// A weighted edge. `id` is stable within a graph; `source`/`target` are node
13/// indices into the graph's `nodes`.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct Edge<W> {
16    /// Stable edge id within its graph.
17    pub id: usize,
18    /// Source node index.
19    pub source: usize,
20    /// Target node index.
21    pub target: usize,
22    /// Edge weight / payload.
23    pub weight: W,
24}
25
26impl<W> Edge<W> {
27    /// Whether this edge is a self-loop (`source == target`).
28    pub fn is_self_loop(&self) -> bool {
29        self.source == self.target
30    }
31
32    /// The endpoint opposite `node`, or `None` if `node` is not an endpoint.
33    /// For a self-loop, returns `node` when `node` is the endpoint.
34    pub fn other(&self, node: usize) -> Option<usize> {
35        if self.source == node {
36            Some(self.target)
37        } else if self.target == node {
38            Some(self.source)
39        } else {
40            None
41        }
42    }
43}