Skip to main content

zrx_graph/graph/
topology.rs

1// Copyright (c) 2025-2026 Zensical and contributors
2
3// SPDX-License-Identifier: MIT
4// All contributions are certified under the DCO
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to
8// deal in the Software without restriction, including without limitation the
9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10// sell copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22// IN THE SOFTWARE.
23
24// ----------------------------------------------------------------------------
25
26//! Topology.
27
28use std::cell::OnceCell;
29use std::rc::Rc;
30
31use super::builder::Edge;
32
33mod adjacency;
34mod distance;
35
36pub use adjacency::Adjacency;
37pub use distance::Distance;
38
39// ----------------------------------------------------------------------------
40// Structs
41// ----------------------------------------------------------------------------
42
43/// Topology.
44///
45/// This data type represents the topology of a graph, which allows to find the
46/// outgoing and incoming edges for each node in linear time by using efficient
47/// adjacency lists. Note that our implementation does not support edge weights,
48/// as they're not necessary for scheduling purposes, and they would only add
49/// unnecessary complexity and overhead. The topology also contains the lazily
50/// computed [`Distance`] matrix that allows to find the shortest path between
51/// two nodes in the graph, or determine whether they're reachable at all.
52///
53/// [`Graph`]: crate::graph::Graph
54/// [`Traversal`]: crate::graph::traversal::Traversal
55#[derive(Clone, Debug)]
56pub struct Topology {
57    /// Inner state.
58    inner: Rc<Inner>,
59}
60
61// ----------------------------------------------------------------------------
62
63/// Inner state.
64#[derive(Debug)]
65struct Inner {
66    /// Outgoing edges.
67    outgoing: Adjacency,
68    /// Incoming edges.
69    incoming: Adjacency,
70    /// Distance matrix (computed on first access).
71    distance: OnceCell<Distance>,
72}
73
74// ----------------------------------------------------------------------------
75// Implementations
76// ----------------------------------------------------------------------------
77
78impl Topology {
79    /// Creates a topology of the given graph.
80    ///
81    /// This method constructs a topology from a graph's nodes and edges, and is
82    /// the key component of an executable [`Graph`][]. It's usually not needed
83    /// to create a topology manually, as it's automatically created when the
84    /// graph is built using the [`Builder::build`][] method.
85    ///
86    /// [`Builder::build`]: crate::graph::Builder::build
87    /// [`Graph`]: crate::graph::Graph
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// # use std::error::Error;
93    /// # fn main() -> Result<(), Box<dyn Error>> {
94    /// use zrx_graph::{Graph, Topology};
95    ///
96    /// // Create graph builder and add nodes
97    /// let mut builder = Graph::builder();
98    /// let a = builder.add_node("a");
99    /// let b = builder.add_node("b");
100    /// let c = builder.add_node("c");
101    ///
102    /// // Create edges between nodes
103    /// builder.add_edge(a, b)?;
104    /// builder.add_edge(b, c)?;
105    ///
106    /// // Create topology
107    /// let topology = Topology::new(builder.len(), builder.edges());
108    /// # Ok(())
109    /// # }
110    /// ```
111    #[must_use]
112    pub fn new(nodes: usize, edges: &[Edge]) -> Self {
113        Self {
114            inner: Rc::new(Inner {
115                outgoing: Adjacency::outgoing(nodes, edges),
116                incoming: Adjacency::incoming(nodes, edges),
117                distance: OnceCell::new(),
118            }),
119        }
120    }
121}
122
123#[allow(clippy::must_use_candidate)]
124impl Topology {
125    /// Returns a reference to the outgoing edges.
126    #[inline]
127    pub fn outgoing(&self) -> &Adjacency {
128        &self.inner.outgoing
129    }
130
131    /// Returns a reference to the incoming edges.
132    #[inline]
133    pub fn incoming(&self) -> &Adjacency {
134        &self.inner.incoming
135    }
136
137    /// Returns a reference to the distance matrix.
138    #[inline]
139    pub fn distance(&self) -> &Distance {
140        self.inner.distance.get_or_init(|| {
141            // Compute distance matrix on first access, since this incurs cost
142            // of O(n³) because of the usage of the Floyd-Warshall algorithm.
143            Distance::new(&self.inner.outgoing)
144        })
145    }
146}
147
148// ----------------------------------------------------------------------------
149// Trait implementations
150// ----------------------------------------------------------------------------
151
152impl PartialEq for Topology {
153    /// Compares two topologies for equality.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// # use std::error::Error;
159    /// # fn main() -> Result<(), Box<dyn Error>> {
160    /// use zrx_graph::{Graph, Topology};
161    ///
162    /// // Create graph builder and add nodes
163    /// let mut builder = Graph::builder();
164    /// let a = builder.add_node("a");
165    /// let b = builder.add_node("b");
166    /// let c = builder.add_node("c");
167    ///
168    /// // Create edges between nodes
169    /// builder.add_edge(a, b)?;
170    /// builder.add_edge(b, c)?;
171    ///
172    /// // Create and compare topologies
173    /// let topology = Topology::new(builder.len(), builder.edges());
174    /// assert_eq!(topology, topology.clone());
175    /// # Ok(())
176    /// # }
177    /// ```
178    #[inline]
179    fn eq(&self, other: &Self) -> bool {
180        Rc::ptr_eq(&self.inner, &other.inner)
181    }
182}
183
184impl Eq for Topology {}