Skip to main content

graphity_core/
top_order.rs

1//! The topological order of a DAG (directed acyclic graph), in which every node comes before its
2//! out-nodes - Java's class `TopOrder`.
3//!
4//! Uses a [depth-first search](https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search),
5//! without recursion: [`of`] returns its reverse postorder. The search starts at the nodes in
6//! ascending order and takes the out-nodes of each node in ascending order, as
7//! [`DfsTraverser::run`](crate::DfsTraverser::run) does, so a graph always gets the same order.
8//! [`TopOrderAndLevels`](crate::TopOrderAndLevels) returns another topological order, together with
9//! a level per node.
10//!
11//! ```
12//! use graphity_core::{top_order, GraphBuilder};
13//!
14//! let mut b = GraphBuilder::new();
15//! b.add_nodes(4);
16//! b.add_edge_pairs(&[0, 2, 0, 1, 1, 3, 2, 3]);
17//! assert_eq!(top_order::of(&b.build()).unwrap(), [0, 2, 1, 3]);
18//! ```
19//!
20//! A graph with a cycle has no topological order, and [`of`] rejects it;
21//! [`graphs::is_dag`](crate::graphs::is_dag) tests for a cycle, and
22//! [`graphs::find_cycle`](crate::graphs::find_cycle) returns one. On a graph with cycles,
23//! [`components::sccs_of`](crate::components::sccs_of) puts each cycle into one SCC (strongly
24//! connected component) and numbers the SCCs in reverse topological order.
25
26use crate::{Graph, GraphError, dfs_frames};
27
28const VISITED: u32 = 0b01;
29const ON_STACK: u32 = 0b10;
30
31/// Returns the nodes of `graph` in topological order: for every edge `u -> v`, `u` comes before `v`.
32///
33/// The result is a vector the caller owns - Java returns an unmodifiable `IntList`.
34///
35/// **Time:** O(node_count + edge_count).
36/// **Memory:** 4 x node_count bytes for the result; while it runs, 2 bits per node and up to
37/// 8 x node_count bytes for the stack, which grows with the deepest path.
38///
39/// # Errors
40/// An [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error, "graph contains a cycle", if
41/// `graph` has a cycle, a self-loop included.
42///
43/// # Panics
44/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
45pub fn of(graph: &Graph) -> Result<Vec<u32>, GraphError> {
46    let n = graph.node_count() as usize;
47    let out = graph.out_adjacency_start();
48    let adj = graph.out_adjacency();
49    // Visited and on-stack, 2 bits per node, 16 nodes per word.
50    let mut state = vec![0u32; (n >> 4) + 1];
51    let mut order = vec![0u32; n];
52    let mut order_pos = n;
53    let mut frames = dfs_frames::initial(n as u32);
54
55    for root in 0..n {
56        let r_shift = (root & 0xF) << 1;
57        if (state[root >> 4] >> r_shift) & VISITED != 0 {
58            continue;
59        }
60        state[root >> 4] |= (VISITED | ON_STACK) << r_shift;
61        frames[0] = root as u32;
62        frames[1] = out[root];
63        let mut top = 0usize;
64
65        'outer: loop {
66            let u = frames[2 * top] as usize;
67            let end = out[u + 1] as usize;
68            let mut i = frames[2 * top + 1] as usize;
69            while i < end {
70                let v = adj[i] as usize;
71                i += 1;
72                let shift = (v & 0xF) << 1;
73                let flags = state[v >> 4] >> shift;
74                if flags & ON_STACK != 0 {
75                    return Err(GraphError::invalid_argument("graph contains a cycle"));
76                }
77                if flags & VISITED == 0 {
78                    frames[2 * top + 1] = i as u32;
79                    state[v >> 4] |= (VISITED | ON_STACK) << shift;
80                    top += 1;
81                    if top == frames.len() >> 1 {
82                        dfs_frames::grow(&mut frames, n as u32);
83                    }
84                    frames[2 * top] = v as u32;
85                    frames[2 * top + 1] = out[v];
86                    continue 'outer;
87                }
88            }
89            state[u >> 4] &= !(ON_STACK << ((u & 0xF) << 1));
90            order_pos -= 1;
91            order[order_pos] = u as u32;
92            if top == 0 {
93                break;
94            }
95            top -= 1;
96        }
97    }
98    Ok(order)
99}