graphity_core/builder.rs
1use crate::array_limits::{MAX_ARRAY_LENGTH, MAX_NODE_COUNT};
2use crate::error::{illegal_state, index_out_of_bounds, invalid_argument};
3use crate::{Edges, Graph};
4
5/// The room the first single edge reserves, the initial capacity of fastutil's `IntArrayList`.
6const FIRST_EDGE_CAPACITY: usize = 10;
7
8/// A builder for a [`Graph`], from nodes and edges added in any order.
9///
10/// The nodes added so far have the node IDs `0..node_count`, in the order they were added;
11/// [`add_node`](Self::add_node) and [`add_nodes`](Self::add_nodes) return the IDs of new ones. Edges
12/// name their source and target by node ID, in any order and as often as the input has them. Here, the
13/// calls between the methods of a program are built from its call sites, one edge per call site;
14/// `names` holds the names of the methods:
15///
16/// <!-- example: building_and_reading.rs#build -->
17/// ```
18/// # use graphity_core::GraphBuilder;
19/// # let names: &[&str] = &[
20/// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
21/// # ];
22/// # struct CallSite {
23/// # caller: u32,
24/// # callee: u32,
25/// # }
26/// # let call_sites: Vec<CallSite> = [
27/// # (0, 1), (0, 2), (2, 3), (2, 5), (2, 4), (2, 5), (3, 8),
28/// # (3, 6), (4, 7), (4, 9), (5, 7), (6, 6), (6, 6), (7, 7),
29/// # ]
30/// # .into_iter()
31/// # .map(|(caller, callee)| CallSite { caller, callee })
32/// # .collect();
33/// let mut builder = GraphBuilder::new();
34/// builder.add_nodes(names.len() as u32); // one node per method, numbered as in names
35/// for site in &call_sites {
36/// builder.add_edge(site.caller, site.callee);
37/// }
38/// let calls = builder.build();
39/// // 14 call sites, 12 edges: run -> show and parse -> parse were added twice
40/// # assert_eq!(call_sites.len(), 14);
41/// # assert_eq!(calls.edge_count(), 12);
42/// ```
43///
44/// [`build`](Self::build) sorts the edges into edge index order and merges duplicates. The builder
45/// stays usable afterwards: more nodes and edges can be added, and `build` called again.
46///
47/// Besides single edges, the builder takes edges in batches: the out-edges or in-edges of one node
48/// ([`add_out_edges`](Self::add_out_edges), [`add_in_edges`](Self::add_in_edges)), a path
49/// ([`add_path`](Self::add_path)), pairs of node IDs ([`add_edge_pairs`](Self::add_edge_pairs)), the
50/// edges of an algorithm result ([`add_edges`](Self::add_edges)) or a whole graph
51/// ([`add_graph`](Self::add_graph)). [`add_child`](Self::add_child), [`add_parent`](Self::add_parent)
52/// and their plural forms add new nodes together with their edges. The out-edges, in-edges and paths
53/// take their node IDs as a slice: an array, a `Vec`, or a [`SortedIntView`](crate::SortedIntView)
54/// such as [`Graph::out_nodes`] returns. So a result of this library goes in without being copied into
55/// an array first. Java has an overload for `int...` and one for `IntList`. A slice is read during the
56/// call and not kept.
57///
58/// A method that takes the node ID of an existing node panics with an `index out of bounds` message if
59/// it is not in `0..node_count`, so that an edge to a missing node fails at the call. A batch method
60/// that panics adds nothing. The methods that add edges between given nodes each have a twin with the
61/// suffix `_and_nodes`, such as [`add_edge_and_nodes`](Self::add_edge_and_nodes), which adds missing
62/// nodes instead. A twin raises the node count to one more than the highest node ID it is given, and
63/// the nodes in between are added too, without edges. So a graph can be built from input numbered
64/// elsewhere without counting its nodes first. However, a node ID that is too high adds nodes instead
65/// of failing.
66///
67/// ```
68/// # use graphity_core::GraphBuilder;
69/// let mut builder = GraphBuilder::new();
70/// builder.add_edge_and_nodes(7, 3); // 8 nodes, one edge
71/// assert_eq!(builder.build().node_count(), 8);
72/// ```
73///
74/// Nodes and edges cannot be removed. To leave nodes out, build the graph and take a subgraph with
75/// [`graphs::remapped`](crate::graphs::remapped) and
76/// [`NodeMapping::for_subgraph_mask`](crate::NodeMapping::for_subgraph_mask).
77///
78/// A builder is mutable; the borrow rules keep two threads from changing it at once - Java's
79/// instances are not safe to share between threads.
80///
81/// **Memory:** 8 bytes per added edge, duplicates included, plus room to grow.
82///
83/// A builder holds at most `2^31 - 10` nodes, as many as a graph can have. This number is the *node
84/// limit*. A method that would add more panics before it changes anything. The panic has an
85/// `invalid argument` message for a count, an `illegal state` message for a single node (Java's
86/// `IllegalStateException`), and an `index out of bounds` message for a node ID given to an
87/// `_and_nodes` method. A builder builds a graph from at most `2^31 - 9` added edges, duplicates
88/// included. This number is the *edge limit*. A batch method that would add more panics with an
89/// `invalid argument` message and adds nothing. The single-edge methods [`add_edge`](Self::add_edge),
90/// [`add_edge_and_nodes`](Self::add_edge_and_nodes), [`add_child`](Self::add_child) and
91/// [`add_parent`](Self::add_parent) do not check the edge limit: beyond it, [`build`](Self::build)
92/// panics with an `invalid argument` message. In Java, the single-edge methods also fail with
93/// `OutOfMemoryError` once the edge storage cannot grow any further; a `Vec` keeps growing.
94#[derive(Debug, Clone, Default)]
95pub struct GraphBuilder {
96 node_count: u32,
97 edge_sources: Vec<u32>,
98 edge_targets: Vec<u32>,
99}
100
101impl GraphBuilder {
102 /// Returns an empty builder, without nodes or edges - Java's constructor.
103 pub fn new() -> Self {
104 Self::default()
105 }
106
107 /// Makes room for `total_edges` edges in total, so that adding up to that many allocates nothing
108 /// more.
109 ///
110 /// The argument counts all edges the builder will hold, duplicates included, not the ones still to
111 /// come. It can be called at any time and does not change the graph that [`build`](Self::build)
112 /// returns.
113 ///
114 /// **Time:** O(total_edges) if the room does not suffice yet, otherwise O(1).
115 /// **Memory:** 8 x total_edges bytes if the room does not suffice yet, otherwise none.
116 ///
117 /// # Panics
118 /// With an `invalid argument` message if `total_edges` is above the edge limit.
119 #[track_caller]
120 pub fn ensure_edge_capacity(&mut self, total_edges: u32) {
121 if total_edges > MAX_ARRAY_LENGTH {
122 invalid_argument!(
123 "total_edges {total_edges} exceeds the edge limit of {MAX_ARRAY_LENGTH}"
124 );
125 }
126 let total_edges = total_edges as usize;
127 let len = self.edge_sources.len();
128 if total_edges > len {
129 self.edge_sources.reserve_exact(total_edges - len);
130 self.edge_targets.reserve_exact(total_edges - len);
131 }
132 }
133
134 /// Adds a node and returns its node ID, which is the next in order.
135 ///
136 /// **Time:** O(1).
137 ///
138 /// # Panics
139 /// With an `illegal state` message if the node count has reached the node limit.
140 #[track_caller]
141 pub fn add_node(&mut self) -> u32 {
142 self.check_room_for_node();
143 let id = self.node_count;
144 self.node_count += 1;
145 id
146 }
147
148 /// Adds `count` nodes and returns the node ID of the first; the others follow in order.
149 ///
150 /// **Time:** O(1).
151 ///
152 /// # Panics
153 /// With an `invalid argument` message if the nodes would exceed the node limit.
154 #[track_caller]
155 pub fn add_nodes(&mut self, count: u32) -> u32 {
156 self.check_new_node_count(count);
157 let first = self.node_count;
158 self.node_count += count;
159 first
160 }
161
162 /// Adds a node with an edge from `parent` to it, and returns its node ID.
163 ///
164 /// **Time:** O(1) amortized.
165 ///
166 /// # Panics
167 /// With an `illegal state` message if the node count has reached the node limit; with an
168 /// `index out of bounds` message if `parent` is not in `0..node_count`.
169 #[track_caller]
170 pub fn add_child(&mut self, parent: u32) -> u32 {
171 self.check_room_for_node();
172 self.check_node(parent, "parent");
173 let child = self.node_count;
174 self.node_count += 1;
175 self.push_one(parent, child);
176 child
177 }
178
179 /// Adds `count` nodes, each with an edge from `parent` to it, and returns the node ID of the first;
180 /// the others follow in order.
181 ///
182 /// **Time:** O(count) amortized.
183 ///
184 /// # Panics
185 /// With an `invalid argument` message if the nodes or edges would exceed their limit; with an
186 /// `index out of bounds` message if `parent` is not in `0..node_count`.
187 #[track_caller]
188 pub fn add_children(&mut self, parent: u32, count: u32) -> u32 {
189 self.check_new_node_count(count);
190 self.check_node(parent, "parent");
191 self.reserve(count as usize);
192 let first = self.node_count;
193 self.node_count += count;
194 for child in first..first + count {
195 self.push(parent, child);
196 }
197 first
198 }
199
200 /// Adds a node with an edge from it to `child`, and returns its node ID.
201 ///
202 /// **Time:** O(1) amortized.
203 ///
204 /// # Panics
205 /// With an `illegal state` message if the node count has reached the node limit; with an
206 /// `index out of bounds` message if `child` is not in `0..node_count`.
207 #[track_caller]
208 pub fn add_parent(&mut self, child: u32) -> u32 {
209 self.check_room_for_node();
210 self.check_node(child, "child");
211 let parent = self.node_count;
212 self.node_count += 1;
213 self.push_one(parent, child);
214 parent
215 }
216
217 /// Adds `count` nodes, each with an edge from it to `child`, and returns the node ID of the first;
218 /// the others follow in order.
219 ///
220 /// **Time:** O(count) amortized.
221 ///
222 /// # Panics
223 /// With an `invalid argument` message if the nodes or edges would exceed their limit; with an
224 /// `index out of bounds` message if `child` is not in `0..node_count`.
225 #[track_caller]
226 pub fn add_parents(&mut self, child: u32, count: u32) -> u32 {
227 self.check_new_node_count(count);
228 self.check_node(child, "child");
229 self.reserve(count as usize);
230 let first = self.node_count;
231 self.node_count += count;
232 for parent in first..first + count {
233 self.push(parent, child);
234 }
235 first
236 }
237
238 /// Adds the edge `source -> target`.
239 ///
240 /// An edge added more than once is still one edge in the graph: [`build`](Self::build) merges
241 /// duplicates.
242 ///
243 /// **Time:** O(1) amortized.
244 ///
245 /// # Panics
246 /// With an `index out of bounds` message if `source` or `target` is not in `0..node_count`.
247 #[inline]
248 #[track_caller]
249 pub fn add_edge(&mut self, source: u32, target: u32) {
250 self.check_node(source, "source");
251 self.check_node(target, "target");
252 self.push_one(source, target);
253 }
254
255 /// Adds the edge `source -> target`, and the missing nodes up to the higher of the two node IDs.
256 ///
257 /// **Time:** O(1) amortized.
258 ///
259 /// # Panics
260 /// With an `index out of bounds` message if `source` or `target` is not below the node limit.
261 #[track_caller]
262 pub fn add_edge_and_nodes(&mut self, source: u32, target: u32) {
263 check_creatable(source);
264 check_creatable(target);
265 self.raise_node_count(Some(source.max(target)));
266 self.push_one(source, target);
267 }
268
269 /// Adds an edge from `source` to each node of `targets` - Java's overloads `addOutEdges(int, IntList)`
270 /// and `addOutEdges(int, int...)`.
271 ///
272 /// **Time:** O(targets.len()) amortized.
273 ///
274 /// # Panics
275 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
276 /// `index out of bounds` message if `source` or a node of `targets` is not in `0..node_count`.
277 #[track_caller]
278 pub fn add_out_edges(&mut self, source: u32, targets: &[u32]) {
279 self.check_node(source, "source");
280 self.check_nodes(targets, "target");
281 self.write_fan_out(source, targets);
282 }
283
284 /// Adds an edge from `source` to each node of `targets`, and the missing nodes up to the highest of
285 /// these node IDs.
286 ///
287 /// **Time:** O(targets.len()) amortized.
288 ///
289 /// # Panics
290 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
291 /// `index out of bounds` message if a node ID is not below the node limit.
292 #[track_caller]
293 pub fn add_out_edges_and_nodes(&mut self, source: u32, targets: &[u32]) {
294 check_creatable(source);
295 let highest = highest_creatable(targets).map_or(source, |h| h.max(source));
296 self.write_fan_out(source, targets);
297 self.raise_node_count(Some(highest));
298 }
299
300 /// Adds an edge from each node of `sources` to `target` - Java's overloads `addInEdges(int, IntList)`
301 /// and `addInEdges(int, int...)`.
302 ///
303 /// **Time:** O(sources.len()) amortized.
304 ///
305 /// # Panics
306 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
307 /// `index out of bounds` message if `target` or a node of `sources` is not in `0..node_count`.
308 #[track_caller]
309 pub fn add_in_edges(&mut self, target: u32, sources: &[u32]) {
310 self.check_node(target, "target");
311 self.check_nodes(sources, "source");
312 self.write_fan_in(target, sources);
313 }
314
315 /// Adds an edge from each node of `sources` to `target`, and the missing nodes up to the highest of
316 /// these node IDs.
317 ///
318 /// **Time:** O(sources.len()) amortized.
319 ///
320 /// # Panics
321 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
322 /// `index out of bounds` message if a node ID is not below the node limit.
323 #[track_caller]
324 pub fn add_in_edges_and_nodes(&mut self, target: u32, sources: &[u32]) {
325 check_creatable(target);
326 let highest = highest_creatable(sources).map_or(target, |h| h.max(target));
327 self.write_fan_in(target, sources);
328 self.raise_node_count(Some(highest));
329 }
330
331 /// Adds a path through `nodes`: an edge from each node of the slice to the next - Java's overloads
332 /// `addPath(IntList)` and `addPath(int...)`.
333 ///
334 /// Fewer than two nodes add no edge.
335 ///
336 /// **Time:** O(nodes.len()) amortized.
337 ///
338 /// # Panics
339 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
340 /// `index out of bounds` message if a node of `nodes` is not in `0..node_count`.
341 #[track_caller]
342 pub fn add_path(&mut self, nodes: &[u32]) {
343 self.check_nodes(nodes, "path");
344 self.write_path(nodes);
345 }
346
347 /// Adds a path through `nodes`, and the missing nodes up to the highest of these node IDs. The path
348 /// has an edge from each node of the slice to the next.
349 ///
350 /// Fewer than two nodes add no edge, but still add the nodes.
351 ///
352 /// **Time:** O(nodes.len()) amortized.
353 ///
354 /// # Panics
355 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
356 /// `index out of bounds` message if a node ID is not below the node limit.
357 #[track_caller]
358 pub fn add_path_and_nodes(&mut self, nodes: &[u32]) {
359 let highest = highest_creatable(nodes);
360 self.write_path(nodes);
361 self.raise_node_count(highest);
362 }
363
364 /// Adds an edge for each pair of node IDs in `endpoints`: `endpoints[0] -> endpoints[1]`,
365 /// `endpoints[2] -> endpoints[3]`, and so on.
366 ///
367 /// **Time:** O(endpoints.len()) amortized.
368 ///
369 /// # Panics
370 /// With an `invalid argument` message if `endpoints` has an odd length, or the edges would exceed the
371 /// edge limit; with an `index out of bounds` message if a node of `endpoints` is not in
372 /// `0..node_count`.
373 #[track_caller]
374 pub fn add_edge_pairs(&mut self, endpoints: &[u32]) {
375 check_pair_count(endpoints.len());
376 self.check_nodes(endpoints, "endpoint");
377 self.write_pairs(endpoints);
378 }
379
380 /// Adds an edge for each pair of node IDs in `endpoints`, as [`add_edge_pairs`](Self::add_edge_pairs)
381 /// does, and the missing nodes up to the highest of these node IDs.
382 ///
383 /// **Time:** O(endpoints.len()) amortized.
384 ///
385 /// # Panics
386 /// With an `invalid argument` message if `endpoints` has an odd length, or the edges would exceed the
387 /// edge limit; with an `index out of bounds` message if a node ID is not below the node limit.
388 #[track_caller]
389 pub fn add_edge_pairs_and_nodes(&mut self, endpoints: &[u32]) {
390 check_pair_count(endpoints.len());
391 let highest = highest_creatable(endpoints);
392 self.write_pairs(endpoints);
393 self.raise_node_count(highest);
394 }
395
396 /// Adds the edges of an algorithm result, such as [`back_edges::of`](crate::back_edges::of) or
397 /// [`Biconnectivity::bridges`](crate::Biconnectivity::bridges).
398 ///
399 /// Only the sources and targets are read: the edge indices of `edges` belong to the graph the
400 /// algorithm ran on.
401 ///
402 /// **Time:** O(edges.count()) amortized.
403 ///
404 /// # Panics
405 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
406 /// `index out of bounds` message if a source or target is not in `0..node_count`.
407 #[track_caller]
408 pub fn add_edges(&mut self, edges: &Edges) {
409 self.check_nodes(edges.source_nodes(), "source");
410 self.check_nodes(edges.target_nodes(), "target");
411 self.write_lists(edges.source_nodes(), edges.target_nodes());
412 }
413
414 /// Adds the edges of an algorithm result, as [`add_edges`](Self::add_edges) does, and the missing
415 /// nodes up to the highest of their node IDs.
416 ///
417 /// **Time:** O(edges.count()) amortized.
418 ///
419 /// # Panics
420 /// With an `invalid argument` message if the edges would exceed the edge limit; with an
421 /// `index out of bounds` message if a source or target is not below the node limit.
422 #[track_caller]
423 pub fn add_edges_and_nodes(&mut self, edges: &Edges) {
424 let highest =
425 highest_creatable(edges.source_nodes()).max(highest_creatable(edges.target_nodes()));
426 self.write_lists(edges.source_nodes(), edges.target_nodes());
427 self.raise_node_count(highest);
428 }
429
430 /// Adds the nodes and edges of `graph` after the nodes already added, and returns the offset of its
431 /// node IDs.
432 ///
433 /// Node `v` of `graph` becomes node `offset + v` of this builder, where the offset is the node count
434 /// before the call. Into an empty builder, the node IDs stay the same, which makes this the way to
435 /// extend a graph: a [`Graph`] is immutable, but a builder that starts with it can add to it and build
436 /// a new one. Here, the dependencies between the packages of a program are extended to a next
437 /// version, in which `ui` also uses `storage`:
438 ///
439 /// <!-- example: building_and_reading.rs#addGraph -->
440 /// ```
441 /// # use graphity_core::GraphBuilder;
442 /// # let dependencies = graphity_core::Graph::of(
443 /// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
444 /// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
445 /// # ).unwrap();
446 /// # let (ui, storage) = (2, 5);
447 /// let mut builder = GraphBuilder::new();
448 /// builder.add_graph(&dependencies); // into an empty builder: the node IDs stay the same
449 /// builder.add_edge(ui, storage);
450 /// let next_version = builder.build();
451 /// # assert_eq!(next_version.edge_count(), 15);
452 /// # assert!(next_version.has_out_node(ui, storage));
453 /// ```
454 ///
455 /// **Time:** O(graph.node_count() + graph.edge_count()) amortized.
456 ///
457 /// # Panics
458 /// With an `invalid argument` message if the nodes or edges of `graph` would exceed their limit.
459 #[track_caller]
460 pub fn add_graph(&mut self, graph: &Graph) -> u32 {
461 let src_node_count = graph.node_count();
462 if src_node_count > MAX_NODE_COUNT - self.node_count {
463 self.beyond_node_limit(format_args!("a graph of {src_node_count} nodes"));
464 }
465 self.reserve(graph.edge_count() as usize);
466 let offset = self.node_count;
467 self.node_count += src_node_count;
468 let start = graph.out_adjacency_start();
469 let adjacency = graph.out_adjacency();
470 for node in 0..src_node_count as usize {
471 for &target in &adjacency[start[node] as usize..start[node + 1] as usize] {
472 self.edge_sources.push(node as u32 + offset);
473 self.edge_targets.push(target + offset);
474 }
475 }
476 offset
477 }
478
479 /// Returns a graph with the nodes and edges added so far.
480 ///
481 /// The edges are sorted into edge index order (by source and then by target), and duplicates are
482 /// merged, so an edge does not keep the position at which it was added; [`Graph::edge_index_of`] finds
483 /// where it went. The builder does not change: more nodes and edges can be added and built into
484 /// another graph.
485 ///
486 /// **Time:** O(node_count + k log d), where k is the number of added edges, duplicates included, and
487 /// d the most of them with the same source.
488 /// **Memory:** 4 x (node_count + edge_count) bytes for the result; while it runs, briefly up to
489 /// 4 x (node_count + k) bytes more.
490 ///
491 /// # Panics
492 /// With an `invalid argument` message if the edges added exceed the edge limit.
493 #[track_caller]
494 pub fn build(&self) -> Graph {
495 let n = self.node_count as usize;
496 let sources = &self.edge_sources;
497 let targets = &self.edge_targets;
498 check_edge_limit(sources.len());
499
500 // 1) Count out-degrees.
501 let mut out_start = vec![0u32; n + 1];
502 for &s in sources {
503 out_start[s as usize + 1] += 1;
504 }
505 // 2) Prefix sum: degrees to start offsets.
506 for v in 0..n {
507 out_start[v + 1] += out_start[v];
508 }
509 // 3) Distribute targets into per-node buckets.
510 let mut out_adj = vec![0u32; out_start[n] as usize];
511 let mut write = out_start[..n].to_vec();
512 for (&s, &t) in sources.iter().zip(targets) {
513 let slot = &mut write[s as usize];
514 out_adj[*slot as usize] = t;
515 *slot += 1;
516 }
517 // 4) Sort and deduplicate each bucket, compacting left: writes never pass the read
518 // position.
519 let mut compact_end = 0usize;
520 for v in 0..n {
521 let start = out_start[v] as usize;
522 let end = out_start[v + 1] as usize;
523 out_adj[start..end].sort_unstable();
524 out_start[v] = compact_end as u32;
525 if start < end {
526 out_adj[compact_end] = out_adj[start];
527 compact_end += 1;
528 for r in start + 1..end {
529 if out_adj[r] != out_adj[r - 1] {
530 out_adj[compact_end] = out_adj[r];
531 compact_end += 1;
532 }
533 }
534 }
535 }
536 out_start[n] = compact_end as u32;
537 out_adj.truncate(compact_end);
538 Graph::from_csr_unchecked(out_start, out_adj)
539 }
540
541 /// Current capacity of the edge storage, so that tests can observe when it reallocates.
542 #[cfg(test)]
543 pub(crate) fn edge_capacity(&self) -> usize {
544 self.edge_sources
545 .capacity()
546 .min(self.edge_targets.capacity())
547 }
548
549 /// Adds an edge into room the batch methods reserved.
550 #[inline]
551 fn push(&mut self, source: u32, target: u32) {
552 self.edge_sources.push(source);
553 self.edge_targets.push(target);
554 }
555
556 /// Adds an edge for the single-edge methods. Full lists grow by half, as fastutil's
557 /// `IntArrayList.add` grows Java's, rather than double, as `Vec::push` would; the edge limit
558 /// is not checked here.
559 #[inline]
560 fn push_one(&mut self, source: u32, target: u32) {
561 if self.edge_sources.len() == self.edge_sources.capacity() {
562 self.grow_by_half();
563 }
564 self.push(source, target);
565 }
566
567 /// Grows full edge lists by half their length.
568 #[cold]
569 fn grow_by_half(&mut self) {
570 let len = self.edge_sources.len();
571 let grown = (len + (len >> 1)).max(FIRST_EDGE_CAPACITY);
572 self.edge_sources.reserve_exact(grown - len);
573 self.edge_targets.reserve_exact(grown - len);
574 }
575
576 fn write_fan_out(&mut self, source: u32, targets: &[u32]) {
577 self.reserve(targets.len());
578 for &target in targets {
579 self.push(source, target);
580 }
581 }
582
583 fn write_fan_in(&mut self, target: u32, sources: &[u32]) {
584 self.reserve(sources.len());
585 for &source in sources {
586 self.push(source, target);
587 }
588 }
589
590 fn write_path(&mut self, nodes: &[u32]) {
591 self.reserve(nodes.len().saturating_sub(1));
592 for pair in nodes.windows(2) {
593 self.push(pair[0], pair[1]);
594 }
595 }
596
597 fn write_pairs(&mut self, endpoints: &[u32]) {
598 self.reserve(endpoints.len() >> 1);
599 for pair in endpoints.chunks_exact(2) {
600 self.push(pair[0], pair[1]);
601 }
602 }
603
604 fn write_lists(&mut self, sources: &[u32], targets: &[u32]) {
605 self.reserve(sources.len());
606 for (&source, &target) in sources.iter().zip(targets) {
607 self.push(source, target);
608 }
609 }
610
611 #[inline]
612 #[track_caller]
613 fn check_node(&self, node: u32, role: &str) {
614 if node >= self.node_count {
615 index_out_of_bounds!(
616 "{role} node does not exist: {node} (node_count={})",
617 self.node_count
618 );
619 }
620 }
621
622 /// Validates every consumed node ID before any of them is written, so that a rejected batch
623 /// leaves the builder unchanged.
624 #[track_caller]
625 fn check_nodes(&self, nodes: &[u32], role: &str) {
626 for &node in nodes {
627 self.check_node(node, role);
628 }
629 }
630
631 #[track_caller]
632 fn check_new_node_count(&self, count: u32) {
633 // Cannot overflow: the node count never exceeds the limit.
634 if count > MAX_NODE_COUNT - self.node_count {
635 self.beyond_node_limit(format_args!("count {count}"));
636 }
637 }
638
639 #[track_caller]
640 fn check_room_for_node(&self) {
641 if self.node_count == MAX_NODE_COUNT {
642 illegal_state!("the node limit of {MAX_NODE_COUNT} is reached");
643 }
644 }
645
646 #[track_caller]
647 fn beyond_node_limit(&self, what: std::fmt::Arguments<'_>) -> ! {
648 invalid_argument!(
649 "{what} would exceed the node limit of {MAX_NODE_COUNT} (node_count={})",
650 self.node_count
651 )
652 }
653
654 /// Raises the node count so that `node` exists; every ID below it is created too, because
655 /// node IDs are contiguous. `None` leaves the count untouched.
656 ///
657 /// The batch twins call it after writing their edges, because the write can still reject the
658 /// batch at the edge limit and must then leave the node count as it was. The writers do not
659 /// read the node count.
660 fn raise_node_count(&mut self, node: Option<u32>) {
661 if let Some(node) = node.filter(|&node| node >= self.node_count) {
662 self.node_count = node + 1;
663 }
664 }
665
666 /// Reserves room for `count` more edges in both edge lists, or rejects them before any is
667 /// written if they would exceed the edge limit. Grows by at least half the capacity, as a
668 /// single edge does, so that batch calls in a loop cost amortized O(1) per edge; reserving the
669 /// exact size alone would make such a loop quadratic. The half step stops at the edge limit,
670 /// and a batch larger than the step gets exactly the room it needs, one allocation per list.
671 #[track_caller]
672 fn reserve(&mut self, count: usize) {
673 let len = self.edge_sources.len();
674 let required = len + count;
675 let limit = edge_limit();
676 if required > limit {
677 invalid_argument!(
678 "{count} more edges would exceed the edge limit of {limit} ({len} edges added)"
679 );
680 }
681 let capacity = self.edge_sources.capacity();
682 if required <= capacity {
683 return;
684 }
685 let grown = required.max(capacity + (capacity >> 1)).min(limit);
686 self.edge_sources.reserve_exact(grown - len);
687 self.edge_targets.reserve_exact(grown - len);
688 }
689}
690
691/// The edge limit, the largest array. The unit tests lower it for their thread: a slice of
692/// `2^31 - 9` IDs, which reaches the real one, takes 8 GiB, where Java's tests pass a list backed by
693/// no array.
694#[inline]
695fn edge_limit() -> usize {
696 #[cfg(not(test))]
697 {
698 MAX_ARRAY_LENGTH as usize
699 }
700 #[cfg(test)]
701 {
702 tests::THREAD_EDGE_LIMIT.with(std::cell::Cell::get)
703 }
704}
705
706/// Rejects more added edges than the edge limit: the check of [`GraphBuilder::build`], which the
707/// single-edge methods leave to it. Free, so that the tests reach the limit without adding the
708/// edges.
709#[track_caller]
710fn check_edge_limit(added_edges: usize) {
711 if added_edges > MAX_ARRAY_LENGTH as usize {
712 invalid_argument!("{added_edges} edges added exceed the edge limit of {MAX_ARRAY_LENGTH}");
713 }
714}
715
716/// Rejects IDs that cannot be created: those whose node count would exceed the node limit -
717/// including every ID that is negative in Java's 32-bit `int`.
718#[inline]
719#[track_caller]
720fn check_creatable(node: u32) {
721 if node >= MAX_NODE_COUNT {
722 index_out_of_bounds!("node ID must be below the node limit of {MAX_NODE_COUNT}: {node}");
723 }
724}
725
726/// Validates every ID before any node is created, and returns the highest, or `None` if empty.
727#[track_caller]
728fn highest_creatable(nodes: &[u32]) -> Option<u32> {
729 let mut highest = None;
730 for &node in nodes {
731 check_creatable(node);
732 highest = highest.max(Some(node));
733 }
734 highest
735}
736
737#[track_caller]
738fn check_pair_count(length: usize) {
739 if length & 1 != 0 {
740 invalid_argument!("expected an even number of node IDs, got {length}");
741 }
742}
743
744#[cfg(test)]
745mod tests {
746 use graphity_testutils::panic_message;
747
748 use super::*;
749 use std::cell::Cell;
750
751 /// The node limit stated in the type's documentation.
752 const NODE_LIMIT: u32 = i32::MAX as u32 - 9;
753
754 /// The edge limit stated in the type's documentation.
755 const EDGE_LIMIT: usize = i32::MAX as usize - 8;
756
757 thread_local! {
758 /// The edge limit of the builders on this thread; a test may lower it.
759 pub(super) static THREAD_EDGE_LIMIT: Cell<usize> = const { Cell::new(EDGE_LIMIT) };
760 }
761
762 fn path(n: u32) -> Graph {
763 let mut b = GraphBuilder::new();
764 b.add_nodes(n);
765 for i in 1..n {
766 b.add_edge(i - 1, i);
767 }
768 b.build()
769 }
770
771 fn isolated(n: u32) -> Graph {
772 let mut b = GraphBuilder::new();
773 b.add_nodes(n);
774 b.build()
775 }
776
777 #[test]
778 fn ensure_edge_capacity_prevents_reallocation() {
779 let mut b = GraphBuilder::new();
780 b.ensure_edge_capacity(1000);
781 b.add_nodes(2);
782 let reserved = b.edge_capacity();
783 assert!(reserved >= 1000);
784 for _ in 0..1000 {
785 b.add_edge(0, 1);
786 }
787 assert_eq!(b.edge_capacity(), reserved);
788 }
789
790 #[test]
791 fn without_a_hint_the_edge_storage_grows() {
792 let mut b = GraphBuilder::new();
793 b.add_nodes(2);
794 b.add_edge(0, 1);
795 let initial = b.edge_capacity();
796 for _ in 0..1000 {
797 b.add_edge(0, 1);
798 }
799 assert!(b.edge_capacity() > initial);
800 }
801
802 #[test]
803 fn single_edges_grow_the_edge_storage_by_half() {
804 // As fastutil's IntArrayList.add in Java: 10 edges first, then half the capacity more.
805 let mut b = GraphBuilder::new();
806 b.add_nodes(2);
807 let mut capacities = Vec::new();
808 for i in 0..100u32 {
809 match i % 4 {
810 0 => b.add_edge(0, 1),
811 1 => b.add_edge_and_nodes(1, 0),
812 2 => {
813 b.add_child(0);
814 }
815 _ => {
816 b.add_parent(1);
817 }
818 }
819 if capacities.last() != Some(&b.edge_capacity()) {
820 capacities.push(b.edge_capacity());
821 }
822 }
823 assert_eq!(capacities, [10, 15, 22, 33, 49, 73, 109]);
824 }
825
826 #[test]
827 fn ensure_edge_capacity_reserves_exactly() {
828 let mut b = GraphBuilder::new();
829 b.add_nodes(2);
830 b.add_out_edges(0, &[0; 100]);
831 b.ensure_edge_capacity(101);
832 assert_eq!(b.edge_capacity(), 101);
833 }
834
835 /// Counts how often 10 000 applications of `call` change the edge capacity.
836 fn capacity_changes(mut call: impl FnMut(&mut GraphBuilder)) -> u32 {
837 let mut b = GraphBuilder::new();
838 b.add_nodes(2);
839 let mut capacity = b.edge_capacity();
840 let mut changes = 0;
841 for _ in 0..10_000 {
842 call(&mut b);
843 if b.edge_capacity() != capacity {
844 capacity = b.edge_capacity();
845 changes += 1;
846 }
847 }
848 changes
849 }
850
851 #[test]
852 fn batch_calls_in_a_loop_grow_the_edge_storage_geometrically() {
853 // 10 000 calls of two edges each: growing by half takes about 20 capacity changes,
854 // growing to the exact size one per call.
855 let path = path(3);
856 assert!(capacity_changes(|b| b.add_out_edges(0, &[1, 1])) <= 30);
857 assert!(capacity_changes(|b| b.add_in_edges(1, &[1, 1])) <= 30);
858 assert!(capacity_changes(|b| b.add_path(&[0, 1, 0])) <= 30);
859 assert!(capacity_changes(|b| b.add_edge_pairs(&[0, 1, 1, 0])) <= 30);
860 assert!(
861 capacity_changes(|b| {
862 b.add_children(0, 2);
863 }) <= 30
864 );
865 assert!(
866 capacity_changes(|b| {
867 b.add_parents(0, 2);
868 }) <= 30
869 );
870 assert!(
871 capacity_changes(|b| {
872 b.add_graph(&path);
873 }) <= 30
874 );
875 }
876
877 #[test]
878 fn a_batch_beyond_the_growth_step_allocates_exactly_once() {
879 let mut imported = GraphBuilder::new();
880 imported.add_graph(&path(1001));
881 assert_eq!(imported.edge_capacity(), 1000);
882
883 let mut b = GraphBuilder::new();
884 b.add_nodes(2);
885 b.add_edge(0, 1);
886 b.add_out_edges(0, &[0; 1000]);
887 assert_eq!(b.edge_capacity(), 1001);
888 }
889
890 #[test]
891 fn single_node_methods_fail_at_the_node_limit() {
892 let mut b = GraphBuilder::new();
893 b.add_nodes(NODE_LIMIT);
894 assert!(
895 panic_message(|| {
896 b.add_node();
897 })
898 .starts_with("illegal state")
899 );
900 assert!(
901 panic_message(|| {
902 b.add_child(0);
903 })
904 .starts_with("illegal state")
905 );
906 assert!(
907 panic_message(|| {
908 b.add_parent(0);
909 })
910 .starts_with("illegal state")
911 );
912 assert_eq!(b.add_nodes(0), NODE_LIMIT);
913 assert_eq!(b.edge_capacity(), 0);
914 }
915
916 #[test]
917 fn count_methods_reject_a_count_beyond_the_node_limit() {
918 let mut b = GraphBuilder::new();
919 assert!(
920 panic_message(|| {
921 b.add_nodes(i32::MAX as u32);
922 })
923 .starts_with("invalid argument")
924 );
925 b.add_nodes(NODE_LIMIT - 2);
926 let message = panic_message(|| {
927 b.add_nodes(3);
928 });
929 assert!(message.starts_with("invalid argument") && message.contains("node limit"));
930 assert!(
931 panic_message(|| {
932 b.add_children(0, 3);
933 })
934 .starts_with("invalid argument")
935 );
936 assert!(
937 panic_message(|| {
938 b.add_parents(0, 3);
939 })
940 .starts_with("invalid argument")
941 );
942 assert_eq!(b.add_nodes(0), NODE_LIMIT - 2);
943 assert_eq!(b.edge_capacity(), 0);
944 assert_eq!(b.add_children(0, 2), NODE_LIMIT - 2);
945 assert_eq!(b.add_nodes(0), NODE_LIMIT);
946 }
947
948 #[test]
949 fn add_graph_rejects_a_graph_beyond_the_node_limit() {
950 let mut b = GraphBuilder::new();
951 b.add_nodes(NODE_LIMIT - 2);
952 assert!(
953 panic_message(|| {
954 b.add_graph(&path(3));
955 })
956 .starts_with("invalid argument")
957 );
958 assert_eq!(b.add_nodes(0), NODE_LIMIT - 2);
959 assert_eq!(b.edge_capacity(), 0);
960 assert_eq!(b.add_graph(&path(2)), NODE_LIMIT - 2);
961 assert_eq!(b.add_nodes(0), NODE_LIMIT);
962 }
963
964 #[test]
965 fn and_nodes_methods_reject_ids_at_the_node_limit() {
966 let mut b = GraphBuilder::new();
967 for f in [
968 &(|b: &mut GraphBuilder| b.add_edge_and_nodes(0, NODE_LIMIT))
969 as &dyn Fn(&mut GraphBuilder),
970 &|b| b.add_out_edges_and_nodes(NODE_LIMIT, &[0]),
971 &|b| b.add_in_edges_and_nodes(0, &[NODE_LIMIT]),
972 &|b| b.add_path_and_nodes(&[0, NODE_LIMIT]),
973 &|b| b.add_edge_pairs_and_nodes(&[NODE_LIMIT, 0]),
974 &|b| b.add_edges_and_nodes(&Edges::wrap(vec![0], vec![NODE_LIMIT], vec![0])),
975 ] {
976 assert!(panic_message(|| f(&mut b)).starts_with("index out of bounds"));
977 }
978 // Rejected before anything changed.
979 assert_eq!(b.add_nodes(0), 0);
980 assert_eq!(b.edge_capacity(), 0);
981 // The highest creatable ID fills the builder up to the limit.
982 b.add_edge_and_nodes(0, NODE_LIMIT - 1);
983 assert_eq!(b.add_nodes(0), NODE_LIMIT);
984 assert!(
985 panic_message(|| {
986 b.add_node();
987 })
988 .starts_with("illegal state")
989 );
990 }
991
992 #[test]
993 fn and_nodes_methods_reject_ids_negative_in_java_and_add_nothing() {
994 let mut b = GraphBuilder::new();
995 b.add_edge_and_nodes(0, 1);
996 let negative = u32::MAX; // -1 in Java
997 for f in [
998 &(|b: &mut GraphBuilder| b.add_edge_and_nodes(negative, 0))
999 as &dyn Fn(&mut GraphBuilder),
1000 &|b| b.add_out_edges_and_nodes(0, &[2, negative]),
1001 &|b| b.add_path_and_nodes(&[0, 3, negative]),
1002 &|b| {
1003 b.add_edges_and_nodes(&Edges::wrap(
1004 vec![0, 4],
1005 vec![5, i32::MAX as u32],
1006 vec![0, 0],
1007 ))
1008 },
1009 &|b| b.add_edges_and_nodes(&Edges::wrap(vec![0], vec![negative], vec![0])),
1010 ] {
1011 assert!(panic_message(|| f(&mut b)).starts_with("index out of bounds"));
1012 }
1013 assert_eq!(b.build(), {
1014 let mut expected = GraphBuilder::new();
1015 expected.add_nodes(2);
1016 expected.add_edge(0, 1);
1017 expected.build()
1018 });
1019 assert_eq!(isolated(2).node_count(), 2);
1020 }
1021
1022 #[test]
1023 fn ensure_edge_capacity_rejects_more_than_the_edge_limit() {
1024 let mut b = GraphBuilder::new();
1025 let message = panic_message(|| b.ensure_edge_capacity(i32::MAX as u32));
1026 assert!(message.starts_with("invalid argument") && message.contains("edge limit"));
1027 assert!(
1028 panic_message(|| b.ensure_edge_capacity(EDGE_LIMIT as u32 + 1))
1029 .starts_with("invalid argument")
1030 );
1031 assert!(panic_message(|| b.ensure_edge_capacity(u32::MAX)).starts_with("invalid argument"));
1032 b.ensure_edge_capacity(0);
1033 assert_eq!(b.edge_capacity(), 0);
1034 }
1035
1036 // ---- edge limit ----
1037
1038 #[test]
1039 fn count_methods_reject_edges_beyond_the_edge_limit_and_change_nothing() {
1040 // Three edges plus NODE_LIMIT - 1 new ones are one more than the edge limit; the node
1041 // count would still fit.
1042 let mut b = GraphBuilder::new();
1043 b.add_node();
1044 b.add_out_edges(0, &[0, 0, 0]);
1045 let message = panic_message(|| {
1046 b.add_children(0, NODE_LIMIT - 1);
1047 });
1048 assert!(message.starts_with("invalid argument") && message.contains("edge limit"));
1049 let message = panic_message(|| {
1050 b.add_parents(0, NODE_LIMIT - 1);
1051 });
1052 assert!(message.starts_with("invalid argument") && message.contains("edge limit"));
1053 assert_eq!(b.add_nodes(0), 1);
1054 assert_eq!(b.build(), self_loop());
1055 }
1056
1057 /// One node with a self-loop.
1058 fn self_loop() -> Graph {
1059 let mut b = GraphBuilder::new();
1060 b.add_node();
1061 b.add_edge(0, 0);
1062 b.build()
1063 }
1064
1065 #[test]
1066 fn batch_methods_reject_edges_beyond_the_edge_limit_before_creating_nodes() {
1067 // Java passes lists of EDGE_LIMIT zeros backed by no array; a slice that long takes
1068 // 8 GiB, so this thread's limit is lowered to 10. One edge plus 10 new ones exceed it.
1069 let limit = 10;
1070 THREAD_EDGE_LIMIT.with(|l| l.set(limit));
1071 let mut b = GraphBuilder::new();
1072 b.add_edge_and_nodes(0, 0);
1073 let zeros = vec![0u32; limit];
1074 let path = vec![0u32; limit + 1];
1075 let pairs = vec![0u32; 2 * limit];
1076 let edges = Edges::wrap(vec![0; limit], vec![7; limit], vec![0; limit]);
1077 let invalid = |f: &dyn Fn(&mut GraphBuilder)| {
1078 let mut copy = b.clone();
1079 let message = panic_message(move || f(&mut copy));
1080 assert!(
1081 message.starts_with("invalid argument") && message.contains("edge limit"),
1082 "{message}"
1083 );
1084 };
1085 invalid(&|b| b.add_out_edges(0, &zeros));
1086 invalid(&|b| b.add_in_edges(0, &zeros));
1087 invalid(&|b| b.add_path(&path));
1088 invalid(&|b| b.add_edge_pairs(&pairs));
1089 invalid(&|b| b.add_out_edges_and_nodes(5, &zeros));
1090 invalid(&|b| b.add_in_edges_and_nodes(5, &zeros));
1091 invalid(&|b| b.add_path_and_nodes(&[&path[..limit], &[5]].concat()));
1092 invalid(&|b| b.add_edge_pairs_and_nodes(&[&pairs[..], &[5, 5]].concat()));
1093 invalid(&|b| b.add_edges_and_nodes(&edges));
1094 invalid(&|b| {
1095 b.add_graph(&{
1096 let mut big = GraphBuilder::new();
1097 big.add_nodes(11);
1098 big.add_path(&(0..11).collect::<Vec<_>>());
1099 big.add_edge(10, 0);
1100 big.build()
1101 });
1102 });
1103 // Exactly up to the limit is fine.
1104 let mut full = b.clone();
1105 full.add_out_edges_and_nodes(5, &zeros[..limit - 1]);
1106 assert_eq!(full.add_nodes(0), 6);
1107 assert_eq!(b.add_nodes(0), 1);
1108 assert_eq!(b.build(), self_loop());
1109 THREAD_EDGE_LIMIT.with(|l| l.set(EDGE_LIMIT));
1110 }
1111
1112 #[test]
1113 fn build_rejects_more_edges_than_the_edge_limit() {
1114 // Only the single-edge methods get past the limit, and only with 16 GiB of edges, so the
1115 // check that build() runs is tested on its own.
1116 check_edge_limit(EDGE_LIMIT);
1117 assert_eq!(
1118 panic_message(|| check_edge_limit(EDGE_LIMIT + 1)),
1119 format!(
1120 "invalid argument: {} edges added exceed the edge limit of {EDGE_LIMIT}",
1121 EDGE_LIMIT + 1
1122 )
1123 );
1124 assert!(panic_message(|| check_edge_limit(u32::MAX as usize)).starts_with("invalid"));
1125 }
1126
1127 #[test]
1128 fn the_growth_step_stops_at_the_edge_limit() {
1129 let limit = 10;
1130 THREAD_EDGE_LIMIT.with(|l| l.set(limit));
1131 let mut b = GraphBuilder::new();
1132 b.add_nodes(1);
1133 b.add_out_edges(0, &[0; 8]);
1134 assert_eq!(b.edge_capacity(), 8);
1135 // Half a step more would be 12; the limit caps it at 10.
1136 b.add_out_edges(0, &[0]);
1137 assert_eq!(b.edge_capacity(), limit);
1138 THREAD_EDGE_LIMIT.with(|l| l.set(EDGE_LIMIT));
1139 }
1140}