knotrel_core/workspace.rs
1//! Caller-owned reusable BFS storage; no graph answers or IDs are retained.
2use crate::{Graph, GraphError, NodeId};
3
4/// Reusable temporary storage for [`Graph::connected_with_workspace`].
5///
6/// Each caller or worker owns its workspace. Separate workspaces permit shared
7/// graph queries without internal locks. A workspace can be reused across graph
8/// growth, mutations and different graphs. It never caches connectivity answers.
9/// Marks use four bytes per registered vertex. Storage retains O(N + R) capacity for the largest registered node count N and
10/// largest visited set R so far; drop the workspace to release that memory.
11#[derive(Debug, Default)]
12pub struct BfsWorkspace {
13 visited: Vec<u32>,
14 generation: u32,
15 queue: Vec<usize>,
16}
17
18impl Graph {
19 /// Tests connectivity using reusable caller-owned traversal storage.
20 ///
21 /// Unlike [`Graph::connected`], repeated calls reuse allocations. A generation
22 /// counter makes old marks inactive without clearing them after each query.
23 /// Traversal takes O(V_reached + E_examined), plus O(log V) endpoint lookup
24 /// and amortized storage growth (initial growth is O(V)). Generation rollover
25 /// clears the retained mark array once per u32::MAX non-reflexive queries,
26 /// costing O(N) for the largest graph previously queried with this workspace.
27 /// No answers are cached; queries always observe current edges.
28 ///
29 /// ```
30 /// use knotrel_core::{BfsWorkspace, Graph};
31 /// let mut graph = Graph::new();
32 /// graph.link(10, 20)?;
33 /// let mut workspace = BfsWorkspace::default();
34 /// assert!(graph.connected_with_workspace(10, 20, &mut workspace)?);
35 /// graph.cut(10, 20)?;
36 /// assert!(!graph.connected_with_workspace(10, 20, &mut workspace)?);
37 /// # Ok::<(), knotrel_core::GraphError>(())
38 /// ```
39 ///
40 /// # Errors
41 /// Returns [`GraphError::UnknownNode`] for absent endpoints, source first.
42 pub fn connected_with_workspace(
43 &self,
44 source: NodeId,
45 target: NodeId,
46 workspace: &mut BfsWorkspace,
47 ) -> Result<bool, GraphError> {
48 let a = *self
49 .ids
50 .get(&source)
51 .ok_or(GraphError::UnknownNode { node: source })?;
52 let b = *self
53 .ids
54 .get(&target)
55 .ok_or(GraphError::UnknownNode { node: target })?;
56 if a == b {
57 return Ok(true);
58 }
59 if workspace.visited.len() < self.adjacency.len() {
60 workspace.visited.resize(self.adjacency.len(), 0);
61 }
62 workspace.generation = workspace.generation.wrapping_add(1);
63 if workspace.generation == 0 {
64 workspace.visited.fill(0);
65 workspace.generation = 1;
66 }
67 let generation = workspace.generation;
68 workspace.visited[a] = generation;
69 workspace.queue.push(a);
70 let mut cursor = 0;
71 let mut found = false;
72 // Mark on enqueue. The generation distinguishes every call, including
73 // queries on another graph with unrelated indices or after early exit.
74 'search: while cursor < workspace.queue.len() {
75 for &neighbor in &self.adjacency[workspace.queue[cursor]] {
76 if neighbor == b {
77 found = true;
78 break 'search;
79 }
80 if workspace.visited[neighbor] != generation {
81 workspace.visited[neighbor] = generation;
82 workspace.queue.push(neighbor);
83 }
84 }
85 cursor += 1;
86 }
87 workspace.queue.clear();
88 Ok(found)
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn generation_rollover_clears_old_marks() {
98 let mut graph = Graph::new();
99 graph.link(1, 2).unwrap();
100 graph.link(2, 3).unwrap();
101 let mut workspace = BfsWorkspace::default();
102 assert!(
103 graph
104 .connected_with_workspace(1, 2, &mut workspace)
105 .unwrap()
106 );
107 workspace.generation = u32::MAX;
108 workspace.visited.fill(1);
109 assert!(
110 graph
111 .connected_with_workspace(1, 3, &mut workspace)
112 .unwrap()
113 );
114 assert_eq!(workspace.generation, 1);
115 }
116
117 #[test]
118 fn unknown_nodes_return_error() {
119 let mut graph = Graph::new();
120 graph.link(1, 2).unwrap();
121 let mut workspace = BfsWorkspace::default();
122 assert!(matches!(
123 graph.connected_with_workspace(10, 20, &mut workspace),
124 Err(GraphError::UnknownNode { node: 10 })
125 ));
126 assert!(matches!(
127 graph.connected_with_workspace(1, 20, &mut workspace),
128 Err(GraphError::UnknownNode { node: 20 })
129 ));
130 }
131}