graphity_core/sccs.rs
1use std::ops::Deref;
2
3use crate::array_limits::{MAX_NODE_COUNT_TWO_INTS, check_node_count};
4use crate::error::check_index;
5use crate::mapping::index_mapping_impl;
6use crate::partition::PartitionArrays;
7use crate::{Graph, IndexPartition, NodePartition, SortedIntView, dfs_frames};
8
9/// The SCCs (strongly connected components) of a graph, as
10/// [`components::sccs_of`](crate::components::sccs_of) returns them.
11///
12/// It is a [`NodePartition`] whose groups are the SCCs, numbered by SCC ID `0..scc_count()`.
13/// [`scc_of`](Self::scc_of) returns the SCC of a node and [`nodes_of`](NodePartition::nodes_of) the
14/// nodes of an SCC. [`contains_cycle`](Self::contains_cycle) distinguishes the SCCs with a cycle from
15/// those of a single node without one. [`condense`](NodePartition::condense) returns the DAG (directed
16/// acyclic graph) of the SCCs. Java's `Sccs` extends `NodePartition`; this type dereferences to its
17/// [`NodePartition`] instead. So every method of a partition applies, and a `&Sccs` is accepted where
18/// a `&NodePartition` is.
19///
20/// Every node is in exactly one SCC; a node that lies on no cycle is an SCC of its own. SCC IDs are in
21/// reverse topological order: every edge between two SCCs goes from the higher SCC ID to the lower
22/// one, so SCC 0 has no edges to other SCCs. The nodes of each SCC are in ascending order. Here,
23/// `dependencies` are the dependencies between the packages of a program, and `names` holds the names
24/// of the packages. The example groups the packages by SCC, in the order of the SCC IDs. In this
25/// order, each package comes after the packages it uses, and the packages that use each other come
26/// together:
27///
28/// <!-- example: connectivity.rs#sccsOf -->
29/// ```
30/// # use graphity_core::components;
31/// # let dependencies = graphity_core::Graph::of(
32/// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
33/// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
34/// # ).unwrap();
35/// # let names = ["app", "cli", "ui", "service", "model", "storage", "json", "util"];
36/// // The SCCs in reverse topological order, each as the names of its packages.
37/// let sccs = components::sccs_of(&dependencies);
38/// let build_order: Vec<Vec<&str>> = (0..sccs.scc_count())
39/// .map(|scc| {
40/// sccs.nodes_of(scc)
41/// .iter()
42/// .map(|&node| names[node as usize])
43/// .collect()
44/// })
45/// .collect();
46/// // build_order: [["util"], ["cli"], ["json"], ["model", "storage"], ["service"],
47/// // ["ui"], ["app"]]
48/// # assert_eq!(build_order[3], ["model", "storage"]);
49/// # assert_eq!(build_order.concat()[..3], ["util", "cli", "json"]);
50/// ```
51///
52/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
53///
54/// **Memory:** 4 x (2 x node_count + scc_count) bytes; the graph is shared, not copied.
55#[derive(Debug, Clone)]
56pub struct Sccs {
57 partition: NodePartition,
58}
59
60impl Sccs {
61 pub(crate) fn new(partition: NodePartition) -> Self {
62 Self { partition }
63 }
64
65 /// The body of [`components::sccs_of`](crate::components::sccs_of), here so that the
66 /// algorithms that need SCCs do not call the facade, as in Java.
67 pub(crate) fn of(graph: &Graph) -> Sccs {
68 tarjan(graph)
69 }
70
71 #[inline]
72 fn arrays(&self) -> &PartitionArrays {
73 self.partition.arrays_ref()
74 }
75
76 #[inline]
77 fn mapping_slice(&self) -> &[u32] {
78 &self.arrays().mapping
79 }
80
81 #[inline]
82 fn valid_count(&self) -> u32 {
83 self.arrays().members.len() as u32
84 }
85
86 /// Returns the SCC ID of `node`. Equivalent to [`get(node)`](crate::IndexMapping::get), which is never
87 /// `None` here.
88 ///
89 /// **Time:** O(1).
90 ///
91 /// # Panics
92 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
93 #[inline]
94 #[track_caller]
95 pub fn scc_of(&self, node: u32) -> u32 {
96 let mapping = self.mapping_slice();
97 check_index(node, mapping.len() as u32);
98 mapping[node as usize]
99 }
100
101 /// Returns the number of SCCs. Equivalent to [`group_count`](NodePartition::group_count).
102 ///
103 /// **Time:** O(1).
104 #[inline]
105 pub fn scc_count(&self) -> u32 {
106 self.partition.group_count()
107 }
108
109 /// Returns whether SCC `scc` contains a cycle: whether it has more than one node, or a single node
110 /// with a self-loop.
111 ///
112 /// **Time:** O(1) for an SCC of more than one node, O(log out_degree(v)) for an SCC of a single node
113 /// `v`.
114 ///
115 /// # Panics
116 /// With an `index out of bounds` message if `scc` is not in `0..scc_count()`.
117 #[track_caller]
118 pub fn contains_cycle(&self, scc: u32) -> bool {
119 check_index(scc, self.scc_count());
120 let arrays = self.arrays();
121 let s = scc as usize;
122 arrays.member_start[s + 1] - arrays.member_start[s] > 1
123 || self
124 .partition
125 .graph()
126 .contains_self_loop(arrays.members[arrays.member_start[s] as usize])
127 }
128
129 /// Returns whether the graph is strongly connected: whether it has at most one SCC. Equivalent to
130 /// `scc_count() <= 1`.
131 ///
132 /// A graph without nodes counts as strongly connected.
133 ///
134 /// **Time:** O(1).
135 #[inline]
136 pub fn is_strongly_connected(&self) -> bool {
137 self.scc_count() <= 1
138 }
139
140 /// Returns the SCCs as a plain [`NodePartition`]; the same as dereferencing.
141 ///
142 /// **Time:** O(1).
143 #[inline]
144 pub fn as_partition(&self) -> &NodePartition {
145 &self.partition
146 }
147
148 /// Returns the SCCs as a plain [`NodePartition`], handed over.
149 ///
150 /// **Time:** O(1).
151 pub fn into_partition(self) -> NodePartition {
152 self.partition
153 }
154}
155
156impl Deref for Sccs {
157 type Target = NodePartition;
158
159 #[inline]
160 fn deref(&self) -> &NodePartition {
161 &self.partition
162 }
163}
164
165impl AsRef<NodePartition> for Sccs {
166 fn as_ref(&self) -> &NodePartition {
167 &self.partition
168 }
169}
170
171index_mapping_impl!(Sccs);
172
173impl IndexPartition for Sccs {
174 #[inline]
175 fn group_count(&self) -> u32 {
176 self.partition.group_count()
177 }
178
179 #[inline]
180 fn indices_of(&self, group: u32) -> SortedIntView<'_> {
181 self.partition.indices_of(group)
182 }
183
184 #[inline]
185 fn size_of(&self, group: u32) -> u32 {
186 self.partition.size_of(group)
187 }
188
189 fn reduce<T: Copy>(&self, values: &[T], identity: T, combine: impl FnMut(T, T) -> T) -> Vec<T> {
190 self.partition.reduce(values, identity, combine)
191 }
192
193 fn reduce_into<T: Clone>(
194 &self,
195 values: &[T],
196 group_values: &mut [T],
197 combine: impl FnMut(T, &T) -> T,
198 ) {
199 self.partition.reduce_into(values, group_values, combine)
200 }
201}
202
203/// Value bits of a Tarjan lane.
204const VALUE: u32 = i32::MAX as u32;
205/// Flag bit of a Tarjan lane: visited in lane 0, on-stack in lane 1.
206const FLAG: u32 = 1 << 31;
207
208/// Tarjan's algorithm with an explicit frame stack, so deep graphs cannot overflow the call stack.
209/// An SCC closes only after every SCC it reaches, which puts the SCC IDs in reverse topological order.
210///
211/// The per-node state - index, lowlink, visited and on-stack - lives in two interleaved lanes per
212/// node: `index | visited << 31` and `lowlink | on_stack << 31`. Every node touch is one cache line,
213/// and two lanes per node cap the node count at `2^30 - 5`. Two stacks drive the traversal: the
214/// frames for the descent, and `scc_stack` holding nodes not yet assigned to a completed SCC: a node
215/// can be finished in the search and still wait there until the root of its SCC finishes.
216fn tarjan(graph: &Graph) -> Sccs {
217 let n = graph.node_count();
218 check_node_count(n, MAX_NODE_COUNT_TWO_INTS, "Tarjan's algorithm");
219 let n = n as usize;
220 let out = graph.out_adjacency_start();
221 let adj = graph.out_adjacency();
222
223 let mut lanes = vec![0u32; 2 * n];
224 let mut scc_stack = vec![0u32; n];
225 let mut scc_top = 0usize;
226 let mut next_index = 0u32;
227 let mut node_to_scc = vec![0u32; n];
228 let mut scc_nodes = vec![0u32; n];
229 // Room for one SCC per node and the sentinel, as Java allocates it; trimmed to the SCC count
230 // when the partition takes it.
231 let mut scc_start: Vec<u32> = Vec::with_capacity(n + 1);
232 let mut scc_nodes_pos = 0usize;
233 // Each frame is two interleaved entries, the node and its resume position in the adjacency
234 // array: both share a cache line, and the stack grows on demand.
235 let mut frames = dfs_frames::initial(n as u32);
236
237 macro_rules! preorder {
238 ($v:expr) => {{
239 let v = $v;
240 let idx = next_index;
241 next_index += 1;
242 lanes[2 * v] = idx | FLAG;
243 lanes[2 * v + 1] = idx | FLAG;
244 scc_stack[scc_top] = v as u32;
245 scc_top += 1;
246 }};
247 }
248
249 for root in 0..n {
250 if lanes[2 * root] & FLAG != 0 {
251 continue;
252 }
253 preorder!(root);
254 frames[0] = root as u32;
255 frames[1] = out[root];
256 let mut top = 0usize;
257
258 'outer: loop {
259 let u = frames[2 * top] as usize;
260 let end = out[u + 1] as usize;
261 // Tight neighbor scan: the frame is touched only when the search descends.
262 let mut i = frames[2 * top + 1] as usize;
263 while i < end {
264 let v = adj[i] as usize;
265 i += 1;
266 if lanes[2 * v] & FLAG == 0 {
267 frames[2 * top + 1] = i as u32; // resume here after v's subtree
268 preorder!(v);
269 top += 1;
270 if top == frames.len() >> 1 {
271 dfs_frames::grow(&mut frames, n as u32);
272 }
273 frames[2 * top] = v as u32;
274 frames[2 * top + 1] = out[v];
275 continue 'outer;
276 } else if lanes[2 * v + 1] & FLAG != 0 {
277 // lowlink[u] = min(lowlink[u], index[v]); v's lanes share a cache line.
278 let idx_v = lanes[2 * v] & VALUE;
279 let low_lane = lanes[2 * u + 1];
280 if idx_v < low_lane & VALUE {
281 lanes[2 * u + 1] = (low_lane & FLAG) | idx_v;
282 }
283 }
284 }
285
286 // Postorder: u is finished. Close its SCC if it is a root, then hand its lowlink to
287 // the parent, the node beneath it on the stack.
288 let low_u = lanes[2 * u + 1] & VALUE;
289 if low_u == lanes[2 * u] & VALUE {
290 let scc = scc_start.len() as u32;
291 let start = scc_nodes_pos;
292 scc_start.push(start as u32);
293 loop {
294 scc_top -= 1;
295 let w = scc_stack[scc_top] as usize;
296 lanes[2 * w + 1] &= VALUE;
297 node_to_scc[w] = scc;
298 scc_nodes[scc_nodes_pos] = w as u32;
299 scc_nodes_pos += 1;
300 if w == u {
301 break;
302 }
303 }
304 scc_nodes[start..scc_nodes_pos].sort_unstable();
305 }
306 if top == 0 {
307 break;
308 }
309 top -= 1;
310 let parent = frames[2 * top] as usize;
311 let low_lane = lanes[2 * parent + 1];
312 if low_u < low_lane & VALUE {
313 lanes[2 * parent + 1] = (low_lane & FLAG) | low_u;
314 }
315 }
316 }
317 scc_start.push(scc_nodes_pos as u32);
318 Sccs::new(NodePartition::from_parts(
319 graph,
320 node_to_scc,
321 scc_nodes,
322 scc_start,
323 ))
324}