graphity_core/graph.rs
1use std::fmt;
2use std::hash::{Hash, Hasher};
3use std::io;
4use std::ops::{Deref, Range};
5use std::sync::Arc;
6
7use crate::array_limits::{MAX_ARRAY_LENGTH, MAX_NODE_COUNT};
8use crate::csr_streams;
9use crate::error::check_index;
10use crate::sorted_int_view::{contains_in_range, index_of_in_range, union_of};
11use crate::{GraphError, SortedIntView};
12
13/// Most nodes the text form lists.
14const TO_STRING_NODES: u32 = 16;
15/// Most out-nodes the text form lists, over all listed nodes together.
16const TO_STRING_TARGETS: usize = 64;
17
18/// An array shared by reference count. The `Box` keeps the buffer of the vector it is made from,
19/// where an `Arc<[u32]>` would copy every element into a block of its own; the extra indirection is
20/// resolved once per call, since the algorithms take each array as a slice before their loops.
21pub(crate) type SharedArray = Arc<Box<[u32]>>;
22
23/// Shares `values` without copying them; spare capacity is released, as by
24/// [`Vec::into_boxed_slice`].
25pub(crate) fn share(values: Vec<u32>) -> SharedArray {
26 Arc::new(values.into_boxed_slice())
27}
28
29/// A directed graph, which is the input of the algorithms in this library.
30///
31/// Nodes are the `u32` IDs `0..node_count()`. Edges are numbered by edge index `0..edge_count()`,
32/// ordered by source and then by target. No two edges have the same source and target; self-loops
33/// are allowed. The graph holds nothing but this structure: names, weights and any other data live
34/// in arrays of the caller, indexed by node ID or by edge index.
35///
36/// [`GraphBuilder`](crate::GraphBuilder) builds a graph from edges in any order. [`Graph::of`]
37/// takes the two arrays of a CSR (compressed sparse row) layout. A graph keeps its edges in this
38/// form, and [`csr`](crate::csr) hands the arrays to algorithm code. [`write_to`](Self::write_to)
39/// and [`read_from`](Self::read_from) store a graph in a stream and load it again.
40///
41/// A `Graph` holds the out-nodes of every node, called its out-adjacency. Algorithms that also need
42/// the in-nodes take a [`BiAdjacentGraph`], which [`BiAdjacentGraph::of`] builds and which also
43/// gives the transposed graph. Algorithms are not methods of the graph but modules and types of
44/// their own, such as [`components`](crate::components), [`top_order`](crate::top_order) and
45/// [`Dominators`](crate::Dominators); the [crate documentation](crate) lists them by topic.
46///
47/// Instances are immutable and safe to share between threads (`Send` and `Sync`). The arrays of a
48/// graph are reference-counted, so a clone shares them in O(1). So do the results that keep their
49/// graph, such as a [`NodePartition`](crate::NodePartition).
50///
51/// **Memory:** 4 x (node_count + edge_count) bytes.
52///
53/// A graph has at most `2^31 - 10` nodes and `2^31 - 9` edges.
54#[derive(Clone)]
55pub struct Graph {
56 /// Start of each node's out-nodes in `out_adj`, with the sentinel `edge_count` at the end, so
57 /// that `out_start[v + 1]` is always valid.
58 out_start: SharedArray,
59 /// All out-adjacency lists, back to back.
60 out_adj: SharedArray,
61 /// The in-adjacency when this graph belongs to a [`BiAdjacentGraph`]. Plays the role of the
62 /// Java subclass: an algorithm handed a `&Graph` reuses it where Java tests `instanceof`.
63 in_adj: Option<InAdjacency>,
64}
65
66#[derive(Clone)]
67struct InAdjacency {
68 start: SharedArray,
69 adj: SharedArray,
70}
71
72impl Graph {
73 /// Returns a graph from the two arrays of its CSR layout, as [`csr`](crate::csr) returns them
74 /// and [`write_to`](Self::write_to) writes them.
75 ///
76 /// The out-nodes of node `v` are
77 /// `out_adjacency[out_adjacency_start[v]..out_adjacency_start[v + 1]]`, and the position of an
78 /// out-node in `out_adjacency` is the edge index of its edge. `out_adjacency_start` holds where
79 /// the out-nodes of each node start, followed by the edge count, so its length is
80 /// `node_count + 1`; `out_adjacency` holds the out-nodes of all nodes, node after node. For
81 /// example, the control flow of a method with a loop:
82 ///
83 /// <!-- example: building.rs#of -->
84 /// ```
85 /// # use graphity_core::Graph;
86 /// // blocks 0 to 5: entry, header, body, then, next, exit
87 /// let out_adjacency_start = [0, 1, 3, 5, 6, 7, 7];
88 /// let out_adjacency = [
89 /// 1, // entry -> header
90 /// 2, 5, // header -> body, exit
91 /// 3, 4, // body -> then, next
92 /// 4, // then -> next
93 /// 1, // next -> header
94 /// ];
95 /// let cfg = Graph::of(&out_adjacency_start, &out_adjacency)?;
96 /// # assert_eq!(graphity_core::graphs::adjacency_list_of(&cfg), "0 -> [1]\n1 -> [2, 5]\n2 -> [3, 4]\n3 -> [4]\n4 -> [1]\n5 -> []\n");
97 /// # Ok::<(), graphity_core::GraphError>(())
98 /// ```
99 ///
100 /// Both arrays are copied and checked: the offsets start at 0, never decrease and end at
101 /// `out_adjacency.len()`, and the out-nodes of each node are strictly ascending. For edges in
102 /// any order or with duplicates, use [`GraphBuilder`](crate::GraphBuilder).
103 /// [`from_csr`](Self::from_csr) takes `Vec`s over without the copy.
104 ///
105 /// **Time:** O(node_count + edge_count).
106 /// **Memory:** 4 x (node_count + edge_count) bytes for the copies, which the result keeps.
107 ///
108 /// # Errors
109 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if an out-node is not in
110 /// `0..node_count`; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if
111 /// `out_adjacency_start` is empty, does not start at 0, decreases or does not end at
112 /// `out_adjacency.len()`, the out-nodes of a node are not strictly ascending, or the arrays
113 /// hold more nodes or edges than a graph can have.
114 pub fn of(out_adjacency_start: &[u32], out_adjacency: &[u32]) -> Result<Graph, GraphError> {
115 validate_csr(out_adjacency_start, out_adjacency)?;
116 Ok(Self::from_csr_unchecked(
117 out_adjacency_start.to_vec(),
118 out_adjacency.to_vec(),
119 ))
120 }
121
122 /// Returns a graph from the two arrays of its CSR layout, which the caller hands over:
123 /// [`Graph::of`] without the copy.
124 ///
125 /// The arrays are checked as by [`Graph::of`], and the graph takes over the buffers of the
126 /// vectors. A vector with spare capacity is shrunk to its length first, as by
127 /// [`Vec::into_boxed_slice`]. Java's package-private `ofOwned`, public here for crates that
128 /// compute CSR arrays themselves, such as `graphity-controlflow`.
129 ///
130 /// **Time:** O(node_count + edge_count).
131 /// **Memory:** none beyond the vectors, unless one has spare capacity.
132 ///
133 /// # Errors
134 /// As for [`Graph::of`].
135 pub fn from_csr(
136 out_adjacency_start: Vec<u32>,
137 out_adjacency: Vec<u32>,
138 ) -> Result<Graph, GraphError> {
139 validate_csr(&out_adjacency_start, &out_adjacency)?;
140 Ok(Self::from_csr_unchecked(out_adjacency_start, out_adjacency))
141 }
142
143 /// Writes this graph to `out`, for [`read_from`](Self::read_from) to read back with the same
144 /// node IDs and edge indices.
145 ///
146 /// Only the structure is written. Data in arrays indexed by node ID or edge index stays valid
147 /// for the graph read back and can follow it in the same stream. Here, the names of the methods
148 /// of a program follow the calls between them:
149 ///
150 /// <!-- example: storing.rs#writeTo -->
151 /// ```
152 /// # use std::fs::File;
153 /// # use std::io::{BufWriter, Write};
154 /// # let calls = graphity_core::Graph::of(
155 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
156 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
157 /// # ).unwrap();
158 /// # let names: &[&str] = &[
159 /// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
160 /// # ];
161 /// # let path = std::env::temp_dir().join(format!("graphity-doc-write-to-{}.bin", std::process::id()));
162 /// # let file = path.as_path();
163 /// let mut out = BufWriter::new(File::create(file)?);
164 /// calls.write_to(&mut out)?;
165 /// for name in names {
166 /// writeln!(out, "{name}")?;
167 /// }
168 /// out.flush()?;
169 /// # drop(out);
170 /// # let bytes = std::fs::read(file)?;
171 /// # std::fs::remove_file(file)?;
172 /// # assert_eq!(graphity_core::Graph::read_from(bytes.as_slice())?, calls);
173 /// # assert!(bytes.ends_with(b"read\nwrite\n"));
174 /// # Ok::<(), std::io::Error>(())
175 /// ```
176 ///
177 /// A [`BiAdjacentGraph`] writes its out-adjacency only. `out` is taken by value: lend it with
178 /// `&mut out` to keep using it, and flush it yourself; this call neither flushes nor closes it.
179 /// Passed by value, it is dropped when the call returns, which closes a
180 /// [`File`](std::fs::File) and flushes a [`BufWriter`](std::io::BufWriter) without reporting an
181 /// error.
182 ///
183 /// The format is the two arrays that [`Graph::of`] takes, preceded by the node count and the
184 /// edge count. Every field is a signed 32-bit integer in little-endian byte order:
185 ///
186 /// ```text
187 /// offset in bytes size in bytes field
188 /// 0 4 node_count
189 /// 4 4 edge_count
190 /// 8 4 x (node_count + 1) out_adjacency_start
191 /// 8 + 4 x (node_count + 1) 4 x edge_count out_adjacency
192 /// ```
193 ///
194 /// The arrays follow the rules of [`Graph::of`]. Nothing else is written: no padding, checksum,
195 /// magic number or version. So a graph takes exactly 8 + 4 x (node_count + 1 + edge_count)
196 /// bytes, and [`read_from`](Self::read_from) recognizes foreign data only where it does not
197 /// form a valid graph. Every implementation of Graphity reads and writes this format, so a
198 /// graph written in one language can be read in another.
199 ///
200 /// Writes in blocks of up to 64 KiB, so `out` needs a [`BufWriter`](std::io::BufWriter) only if
201 /// other data shares it in small pieces, as in the example.
202 ///
203 /// ```
204 /// use graphity_core::{Graph, GraphBuilder};
205 ///
206 /// let mut b = GraphBuilder::new();
207 /// b.add_nodes(3);
208 /// b.add_path(&[0, 1, 2]);
209 /// let graph = b.build();
210 ///
211 /// let mut bytes = Vec::new();
212 /// graph.write_to(&mut bytes)?;
213 /// assert_eq!(bytes.len(), 8 + 4 * (3 + 1 + 2));
214 /// assert_eq!(Graph::read_from(bytes.as_slice())?, graph);
215 /// # Ok::<(), std::io::Error>(())
216 /// ```
217 ///
218 /// **Time:** O(node_count + edge_count).
219 /// **Memory:** a 64 KiB buffer.
220 ///
221 /// # Errors
222 /// Any error of `out`.
223 pub fn write_to<W: io::Write>(&self, mut out: W) -> io::Result<()> {
224 csr_streams::write(&self.out_start, &self.out_adj, &mut out)
225 }
226
227 /// Reads a graph that [`write_to`](Self::write_to) wrote, with the same node IDs and edge
228 /// indices.
229 ///
230 /// Reads exactly the bytes of the graph and leaves `input` right after them, where data written
231 /// after the graph follows. Here, that data is the names of the methods of a program:
232 ///
233 /// <!-- example: storing.rs#readFrom -->
234 /// ```
235 /// # use std::fs::File;
236 /// # use std::io::{BufRead, BufReader};
237 /// # use graphity_core::Graph;
238 /// # let calls = graphity_core::Graph::of(
239 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
240 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
241 /// # ).unwrap();
242 /// # let mut bytes = Vec::new();
243 /// # calls.write_to(&mut bytes)?;
244 /// # bytes.extend_from_slice(b"main\nparseArgs\nrun\nload\nsave\nshow\nparse\nformat\nread\nwrite\n");
245 /// # let path = std::env::temp_dir().join(format!("graphity-doc-read-from-{}.bin", std::process::id()));
246 /// # std::fs::write(&path, bytes)?;
247 /// # let file = path.as_path();
248 /// let mut input = BufReader::new(File::open(file)?);
249 /// // equal to the graph written, edge indices included
250 /// let calls = Graph::read_from(&mut input)?;
251 /// let mut names = Vec::with_capacity(calls.node_count() as usize);
252 /// for name in input.lines().take(calls.node_count() as usize) {
253 /// names.push(name?);
254 /// }
255 /// # std::fs::remove_file(file)?;
256 /// # assert_eq!(graphity_core::graphs::adjacency_list_of(&calls).lines().count(), 10);
257 /// # assert_eq!(names, ["main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write"]);
258 /// # Ok::<(), std::io::Error>(())
259 /// ```
260 ///
261 /// `input` is taken by value, so that `&mut input` lends it; `read_from` does not close it.
262 /// Passed by value, it is dropped when the call returns. The result has no in-adjacency, even
263 /// if the stream was written from a [`BiAdjacentGraph`]; [`BiAdjacentGraph::of`] builds it
264 /// again.
265 ///
266 /// The arrays are checked as by [`Graph::of`], but not copied. They grow with the data that
267 /// arrives, so a header that announces more than the stream holds ends in an
268 /// [`UnexpectedEof`](io::ErrorKind::UnexpectedEof) error, not in an allocation of the
269 /// announced size. Reads in blocks of up to 64 KiB, so `input` needs a
270 /// [`BufReader`](std::io::BufReader) only if other data shares it in small pieces.
271 ///
272 /// **Time:** O(node_count + edge_count).
273 /// **Memory:** 4 x (node_count + edge_count) bytes for the result and a 64 KiB buffer; while
274 /// an array grows, briefly up to 4 x max(node_count, edge_count) bytes more.
275 ///
276 /// # Errors
277 /// - [`UnexpectedEof`](io::ErrorKind::UnexpectedEof) if the stream ends before the graph does -
278 /// Java's `EOFException`;
279 /// - [`InvalidData`](io::ErrorKind::InvalidData) if a count in the header is negative or
280 /// larger than a graph can have, or the arrays do not form a graph that [`Graph::of`]
281 /// accepts, whose [`GraphError`] is then the [`source`](std::error::Error::source) of the
282 /// error;
283 /// - any other error of `input`.
284 pub fn read_from<R: io::Read>(mut input: R) -> io::Result<Graph> {
285 let (start, adjacency) = csr_streams::read(&mut input)?;
286 Graph::from_csr(start, adjacency).map_err(csr_streams::invalid_graph)
287 }
288
289 /// Takes the arrays as they are: not checked.
290 pub(crate) fn from_csr_unchecked(out_start: Vec<u32>, out_adj: Vec<u32>) -> Graph {
291 Self {
292 out_start: share(out_start),
293 out_adj: share(out_adj),
294 in_adj: None,
295 }
296 }
297
298 /// The graph without nodes.
299 pub(crate) fn empty() -> Graph {
300 Self::from_csr_unchecked(vec![0], Vec::new())
301 }
302
303 /// The offset array, for [`csr`](crate::csr) and the algorithms.
304 #[inline]
305 pub(crate) fn out_adjacency_start(&self) -> &[u32] {
306 &self.out_start
307 }
308
309 /// The target array, for [`csr`](crate::csr) and the algorithms.
310 #[inline]
311 pub(crate) fn out_adjacency(&self) -> &[u32] {
312 &self.out_adj
313 }
314
315 /// The in-adjacency offsets if this graph is bi-adjacent.
316 #[inline]
317 pub(crate) fn in_adjacency_start_if_present(&self) -> Option<&[u32]> {
318 self.in_adj.as_ref().map(|i| &**i.start)
319 }
320
321 /// Returns the number of nodes.
322 ///
323 /// **Time:** O(1).
324 #[inline]
325 pub fn node_count(&self) -> u32 {
326 (self.out_start.len() - 1) as u32
327 }
328
329 /// Returns the number of edges.
330 ///
331 /// **Time:** O(1).
332 #[inline]
333 pub fn edge_count(&self) -> u32 {
334 self.out_adj.len() as u32
335 }
336
337 /// Returns whether this graph has no nodes. Equivalent to `node_count() == 0`.
338 ///
339 /// **Time:** O(1).
340 #[inline]
341 pub fn is_empty(&self) -> bool {
342 self.node_count() == 0
343 }
344
345 /// Returns the out-degree of `node`. That is the number of edges with `node` as source.
346 ///
347 /// **Time:** O(1).
348 ///
349 /// # Panics
350 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
351 #[inline]
352 #[track_caller]
353 pub fn out_degree(&self, node: u32) -> u32 {
354 check_index(node, self.node_count());
355 let v = node as usize;
356 self.out_start[v + 1] - self.out_start[v]
357 }
358
359 /// Returns the out-nodes of `node` in ascending order. These are the targets of the edges with
360 /// `node` as source.
361 ///
362 /// The result is a view of this graph's own array, not a copy.
363 ///
364 /// **Time:** O(1).
365 ///
366 /// # Panics
367 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
368 #[inline]
369 #[track_caller]
370 pub fn out_nodes(&self, node: u32) -> SortedIntView<'_> {
371 check_index(node, self.node_count());
372 let v = node as usize;
373 SortedIntView::new(
374 &self.out_adj[self.out_start[v] as usize..self.out_start[v + 1] as usize],
375 )
376 }
377
378 /// Returns the start of the edge index range of the out-edges of `node`. The out-edges are the
379 /// edges with `node` as source.
380 ///
381 /// Their edge indices are `out_edge_start(node)..out_edge_end(node)`, in the order of
382 /// [`out_nodes`](Self::out_nodes); the range is empty if `node` has no out-edges. A loop over
383 /// the range reads the data of each edge from arrays indexed by edge index. Here, it lists the
384 /// methods that `run` calls, with the number of call sites of each call in `site_count`:
385 ///
386 /// <!-- example: edge_data.rs#outEdges -->
387 /// ```
388 /// # use std::io::Write;
389 /// # let calls = graphity_core::Graph::of(
390 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
391 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
392 /// # ).unwrap();
393 /// # let names: &[&str] = &[
394 /// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
395 /// # ];
396 /// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
397 /// # let run = 2;
398 /// # let mut out = Vec::new();
399 /// for edge in calls.out_edge_start(run)..calls.out_edge_end(run) {
400 /// writeln!(
401 /// out,
402 /// "{}: {}",
403 /// names[calls.edge_target(edge) as usize],
404 /// site_count[edge as usize]
405 /// )?;
406 /// }
407 /// // load: 1
408 /// // save: 1
409 /// // show: 2
410 /// # assert_eq!(String::from_utf8(out).unwrap(), "load: 1\nsave: 1\nshow: 2\n");
411 /// # Ok::<(), std::io::Error>(())
412 /// ```
413 ///
414 /// **Time:** O(1).
415 ///
416 /// # Panics
417 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
418 #[inline]
419 #[track_caller]
420 pub fn out_edge_start(&self, node: u32) -> u32 {
421 check_index(node, self.node_count());
422 self.out_start[node as usize]
423 }
424
425 /// Returns the end, exclusive, of the edge index range of the out-edges of `node`; see
426 /// [`out_edge_start`](Self::out_edge_start).
427 ///
428 /// **Time:** O(1).
429 ///
430 /// # Panics
431 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
432 #[inline]
433 #[track_caller]
434 pub fn out_edge_end(&self, node: u32) -> u32 {
435 check_index(node, self.node_count());
436 self.out_start[node as usize + 1]
437 }
438
439 /// Returns the node IDs `0..node_count()`, in ascending order - Java's `IntStream`, as a
440 /// range.
441 ///
442 /// **Time:** O(1) to create the range.
443 #[inline]
444 pub fn nodes(&self) -> Range<u32> {
445 0..self.node_count()
446 }
447
448 /// Calls `action` for every edge with its source, target and edge index, in edge index order -
449 /// Java's `EdgeConsumer` is a closure here.
450 ///
451 /// The source comes with each edge at no cost, whereas [`edge_source`](Self::edge_source)
452 /// searches for it.
453 ///
454 /// ```
455 /// # use graphity_core::GraphBuilder;
456 /// # let mut b = GraphBuilder::new();
457 /// # b.add_nodes(2);
458 /// # b.add_edge(0, 1);
459 /// # let graph = b.build();
460 /// let weights = vec![1.5; graph.edge_count() as usize];
461 /// let mut total = 0.0;
462 /// graph.for_each_edge(|_source, _target, edge_index| total += weights[edge_index as usize]);
463 /// assert_eq!(total, 1.5);
464 /// ```
465 ///
466 /// **Time:** O(node_count + edge_count).
467 pub fn for_each_edge(&self, mut action: impl FnMut(u32, u32, u32)) {
468 let start = &*self.out_start;
469 let adj = &*self.out_adj;
470 for source in 0..start.len() - 1 {
471 for e in start[source]..start[source + 1] {
472 action(source as u32, adj[e as usize], e);
473 }
474 }
475 }
476
477 /// Returns the target of edge `edge_index`.
478 ///
479 /// **Time:** O(1).
480 ///
481 /// # Panics
482 /// With an `index out of bounds` message if `edge_index` is not in `0..edge_count()`.
483 #[inline]
484 #[track_caller]
485 pub fn edge_target(&self, edge_index: u32) -> u32 {
486 check_index(edge_index, self.edge_count());
487 self.out_adj[edge_index as usize]
488 }
489
490 /// Returns the source of edge `edge_index`.
491 ///
492 /// Unlike the target, the source is searched for; [`for_each_edge`](Self::for_each_edge)
493 /// gives every edge with its source without a search.
494 ///
495 /// **Time:** O(log node_count).
496 ///
497 /// # Panics
498 /// With an `index out of bounds` message if `edge_index` is not in `0..edge_count()`.
499 #[track_caller]
500 pub fn edge_source(&self, edge_index: u32) -> u32 {
501 check_index(edge_index, self.edge_count());
502 // The largest node whose offset is <= edge_index: a node without out-edges shares its
503 // offset with the next one.
504 let (mut lo, mut hi) = (0usize, self.node_count() as usize - 1);
505 while lo < hi {
506 let mid = (lo + hi).div_ceil(2);
507 if self.out_start[mid] <= edge_index {
508 lo = mid;
509 } else {
510 hi = mid - 1;
511 }
512 }
513 lo as u32
514 }
515
516 /// Returns whether the edge `node -> out_node` exists; an `out_node` out of range yields
517 /// `false`.
518 ///
519 /// **Time:** O(log out_degree(node)).
520 ///
521 /// # Panics
522 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
523 #[inline]
524 #[track_caller]
525 pub fn has_out_node(&self, node: u32, out_node: u32) -> bool {
526 check_index(node, self.node_count());
527 let v = node as usize;
528 contains_in_range(
529 &self.out_adj,
530 self.out_start[v] as usize,
531 self.out_start[v + 1] as usize,
532 out_node,
533 )
534 }
535
536 /// Returns the edge index of the edge `source -> target`, or `None` if there is none - Java's
537 /// `-1`; a `target` out of range yields `None`.
538 ///
539 /// [`GraphBuilder`](crate::GraphBuilder) sorts the edges and merges duplicates, so an edge
540 /// does not keep the position at which it was added; this method finds where it went. Here,
541 /// `calls` was built with one edge per call site, and the call sites of each call are counted:
542 ///
543 /// <!-- example: edge_data.rs#edgeIndexOf -->
544 /// ```
545 /// # let calls = graphity_core::Graph::of(
546 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
547 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
548 /// # ).unwrap();
549 /// # struct CallSite {
550 /// # caller: u32,
551 /// # callee: u32,
552 /// # }
553 /// # let call_sites: Vec<CallSite> = [
554 /// # (0, 1), (0, 2), (2, 3), (2, 5), (2, 4), (2, 5), (3, 8),
555 /// # (3, 6), (4, 7), (4, 9), (5, 7), (6, 6), (6, 6), (7, 7),
556 /// # ]
557 /// # .into_iter()
558 /// # .map(|(caller, callee)| CallSite { caller, callee })
559 /// # .collect();
560 /// let mut site_count = vec![0; calls.edge_count() as usize];
561 /// for site in &call_sites {
562 /// site_count[calls.edge_index_of(site.caller, site.callee).unwrap() as usize] += 1;
563 /// }
564 /// // 2 for run -> show and for parse -> parse, 1 for every other edge
565 /// # assert_eq!(site_count, [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1]);
566 /// ```
567 ///
568 /// **Time:** O(log out_degree(source)).
569 ///
570 /// # Panics
571 /// With an `index out of bounds` message if `source` is not in `0..node_count()`.
572 #[inline]
573 #[track_caller]
574 pub fn edge_index_of(&self, source: u32, target: u32) -> Option<u32> {
575 check_index(source, self.node_count());
576 let v = source as usize;
577 index_of_in_range(
578 &self.out_adj,
579 self.out_start[v] as usize,
580 self.out_start[v + 1] as usize,
581 target,
582 )
583 }
584
585 /// Returns whether `node` has an edge to itself, called a self-loop. Equivalent to
586 /// [`has_out_node(node, node)`](Self::has_out_node).
587 ///
588 /// **Time:** O(log out_degree(node)).
589 ///
590 /// # Panics
591 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
592 #[inline]
593 #[track_caller]
594 pub fn contains_self_loop(&self, node: u32) -> bool {
595 self.has_out_node(node, node)
596 }
597
598 /// Returns a graph with the same nodes and edges, without in-adjacency. A plain `Graph` returns
599 /// a clone, and the graph of a [`BiAdjacentGraph`] returns a `Graph` over its out-adjacency.
600 ///
601 /// The result shares the out-adjacency of this graph; nothing is copied. Once only the result
602 /// is kept, the in-adjacency is freed.
603 ///
604 /// **Time:** O(1).
605 pub fn uni_adjacent_graph(&self) -> Graph {
606 Graph {
607 out_start: Arc::clone(&self.out_start),
608 out_adj: Arc::clone(&self.out_adj),
609 in_adj: None,
610 }
611 }
612
613 fn type_name(&self) -> &'static str {
614 if self.in_adj.is_some() {
615 "BiAdjacentGraph"
616 } else {
617 "Graph"
618 }
619 }
620}
621
622/// Two graphs are equal if they have the same nodes and edges.
623///
624/// The in-adjacency does not count: the graph of a [`BiAdjacentGraph`] equals a `Graph` with the
625/// same nodes and edges.
626///
627/// **Time:** O(node_count + edge_count).
628impl PartialEq for Graph {
629 fn eq(&self, other: &Graph) -> bool {
630 self.out_start == other.out_start && self.out_adj == other.out_adj
631 }
632}
633
634impl Eq for Graph {}
635
636/// Hashes the nodes and edges, consistent with equality.
637///
638/// The hash is computed on every call, so each lookup of a graph in a hash-based collection walks
639/// the whole graph. [`graphs::topology_hash`](crate::graphs::topology_hash) gives a 64-bit hash to
640/// compute once and keep.
641///
642/// **Time:** O(node_count + edge_count).
643impl Hash for Graph {
644 fn hash<H: Hasher>(&self, state: &mut H) {
645 self.out_start.hash(state);
646 self.out_adj.hash(state);
647 }
648}
649
650/// Writes the node and edge counts and the out-nodes of the first nodes, for debuggers and logs -
651/// Java's `toString`. For the control flow of a method with a loop:
652///
653/// <!-- example: building.rs#toString -->
654/// ```
655/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
656/// let text = cfg.to_string();
657/// // Graph[nodes=6, edges=7] {0 -> [1], 1 -> [2, 5], 2 -> [3, 4], 3 -> [4], 4 -> [1],
658/// // 5 -> []}
659/// # assert_eq!(text, "Graph[nodes=6, edges=7] {0 -> [1], 1 -> [2, 5], 2 -> [3, 4], 3 -> [4], 4 -> [1], 5 -> []}");
660/// ```
661///
662/// The text stays short however large the graph: it lists at most 16 nodes and 64 out-nodes in
663/// total. `...` marks where it is cut - after the 16th node, or inside the list that would go
664/// beyond 64 out-nodes. The graph of a [`BiAdjacentGraph`] is named as such and lists its
665/// out-nodes. [`graphs::adjacency_list_of`](crate::graphs::adjacency_list_of) gives the whole graph
666/// as text.
667///
668/// **Time:** O(1), as the text is bounded.
669impl fmt::Display for Graph {
670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671 let n = self.node_count();
672 write!(
673 f,
674 "{}[nodes={n}, edges={}] {{",
675 self.type_name(),
676 self.edge_count()
677 )?;
678 let mut budget = TO_STRING_TARGETS;
679 let listed = n.min(TO_STRING_NODES);
680 for v in 0..listed {
681 if v > 0 {
682 f.write_str(", ")?;
683 }
684 write!(f, "{v} -> [")?;
685 let start = self.out_start[v as usize] as usize;
686 let end = self.out_start[v as usize + 1] as usize;
687 let shown = (end - start).min(budget);
688 for (i, target) in self.out_adj[start..start + shown].iter().enumerate() {
689 if i > 0 {
690 f.write_str(", ")?;
691 }
692 write!(f, "{target}")?;
693 }
694 budget -= shown;
695 if shown < end - start {
696 f.write_str(if shown > 0 { ", ...]" } else { "...]" })?;
697 if v + 1 < n {
698 f.write_str(", ...")?;
699 }
700 return f.write_str("}");
701 }
702 f.write_str("]")?;
703 }
704 if listed < n {
705 f.write_str(", ...")?;
706 }
707 f.write_str("}")
708 }
709}
710
711/// The same bounded text as [`Display`](fmt::Display).
712impl fmt::Debug for Graph {
713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714 fmt::Display::fmt(self, f)
715 }
716}
717
718fn validate_csr(start: &[u32], adj: &[u32]) -> Result<(), GraphError> {
719 if start.is_empty() {
720 return Err(GraphError::invalid_argument(
721 "out_adjacency_start must hold node_count + 1 offsets, but is empty",
722 ));
723 }
724 let n = start.len() - 1;
725 let m = adj.len();
726 if n > MAX_NODE_COUNT as usize || m > MAX_ARRAY_LENGTH as usize {
727 return Err(GraphError::invalid_argument(format!(
728 "a graph holds at most {MAX_NODE_COUNT} nodes and {MAX_ARRAY_LENGTH} edges, but these \
729 arrays hold {n} and {m}"
730 )));
731 }
732 if start[0] != 0 {
733 return Err(GraphError::invalid_argument(format!(
734 "out_adjacency_start[0] must be 0, but was {}",
735 start[0]
736 )));
737 }
738 // Offsets first: once they rise from 0 to m, every list below lies inside out_adjacency.
739 if let Some(v) = start.windows(2).position(|w| w[1] < w[0]) {
740 return Err(GraphError::invalid_argument(format!(
741 "out_adjacency_start decreases after node {v}: {} > {}",
742 start[v],
743 start[v + 1]
744 )));
745 }
746 if start[n] as usize != m {
747 return Err(GraphError::invalid_argument(format!(
748 "out_adjacency_start[{n}] must be out_adjacency.len() {m}, but was {}",
749 start[n]
750 )));
751 }
752 for v in 0..n {
753 let from = start[v] as usize;
754 let mut previous: Option<u32> = None;
755 for (e, &target) in adj[from..start[v + 1] as usize].iter().enumerate() {
756 if target as usize >= n {
757 return Err(GraphError::index_out_of_bounds(format!(
758 "out-node {target} of node {v} at position {} is not in 0..{n}",
759 from + e
760 )));
761 }
762 if let Some(p) = previous.filter(|&p| target <= p) {
763 return Err(GraphError::invalid_argument(format!(
764 "the out-nodes of node {v} must be strictly ascending, but {target} follows \
765 {p}"
766 )));
767 }
768 previous = Some(target);
769 }
770 }
771 Ok(())
772}
773
774/// A [`Graph`] that also holds the in-nodes of every node, for algorithms that follow edges
775/// against their direction.
776///
777/// [`BiAdjacentGraph::of`] builds the in-adjacency of a graph - the in-nodes of every node. The
778/// result has the node IDs and edge indices of the graph and shares the out-nodes of every node,
779/// called its out-adjacency. Algorithms that need in-nodes, such as
780/// [`Dominators`](crate::Dominators), take a `BiAdjacentGraph`, so that the in-adjacency is built
781/// once and serves all of them. [`transposed`](Self::transposed) reverses every edge without
782/// copying, and [`uni_adjacent_graph`](Graph::uni_adjacent_graph) drops the in-adjacency again.
783///
784/// Java's `BiAdjacentGraph` extends `Graph`; this type dereferences to its [`Graph`] instead. So
785/// every method of a graph applies, and a `&BiAdjacentGraph` is accepted where a `&Graph` is. The
786/// graph remembers its in-adjacency, so [`BiAdjacentGraph::of`] on it takes the in-adjacency over
787/// in O(1).
788///
789/// The in-nodes of a node are in ascending order, like its out-nodes. A `BiAdjacentGraph` equals a
790/// `Graph` with the same nodes and edges. Instances are immutable and safe to share between threads
791/// (`Send` and `Sync`).
792///
793/// ```
794/// use graphity_core::{BiAdjacentGraph, GraphBuilder};
795///
796/// let mut b = GraphBuilder::new();
797/// b.add_nodes(3);
798/// b.add_edge_pairs(&[0, 2, 1, 2]);
799/// let graph = BiAdjacentGraph::of(&b.build());
800/// assert_eq!(graph.in_nodes(2), [0, 1]);
801/// assert_eq!(graph.out_nodes(0), [2]);
802/// assert_eq!(graph.transposed().out_nodes(2), [0, 1]);
803/// ```
804///
805/// **Memory:** 8 x (node_count + edge_count) bytes, half of it for the out-adjacency, which is
806/// shared with the graph it was built from.
807#[derive(Clone)]
808pub struct BiAdjacentGraph {
809 /// The graph, carrying the in-adjacency as well.
810 graph: Graph,
811 /// The same arrays as `graph.in_adj`, held directly so that lookups need no unwrap.
812 in_start: SharedArray,
813 in_adj: SharedArray,
814}
815
816impl BiAdjacentGraph {
817 fn from_parts(
818 out_start: SharedArray,
819 out_adj: SharedArray,
820 in_start: SharedArray,
821 in_adj: SharedArray,
822 ) -> Self {
823 Self {
824 graph: Graph {
825 out_start,
826 out_adj,
827 in_adj: Some(InAdjacency {
828 start: Arc::clone(&in_start),
829 adj: Arc::clone(&in_adj),
830 }),
831 },
832 in_start,
833 in_adj,
834 }
835 }
836
837 /// Returns a `BiAdjacentGraph` with the nodes and edges of `graph`, building its
838 /// in-adjacency.
839 ///
840 /// Node IDs and edge indices stay the same, and the out-adjacency is shared with `graph`, not
841 /// copied. The in-adjacency is built anew on every call, not cached: keep the result to use it
842 /// more than once. If `graph` already is bi-adjacent, that is, the graph of a
843 /// `BiAdjacentGraph`, the result shares its in-adjacency.
844 ///
845 /// **Time:** O(node_count + edge_count), or O(1) if already bi-adjacent.
846 /// **Memory:** +4 x (node_count + edge_count) bytes, or none if already bi-adjacent.
847 pub fn of(graph: &Graph) -> BiAdjacentGraph {
848 match &graph.in_adj {
849 Some(in_adj) => Self::from_parts(
850 Arc::clone(&graph.out_start),
851 Arc::clone(&graph.out_adj),
852 Arc::clone(&in_adj.start),
853 Arc::clone(&in_adj.adj),
854 ),
855 None => Self::with_in_adjacency(graph),
856 }
857 }
858
859 /// The body of [`BiAdjacentGraph::of`] for a graph without in-adjacency.
860 fn with_in_adjacency(graph: &Graph) -> BiAdjacentGraph {
861 let n = graph.node_count() as usize;
862 let m = graph.edge_count() as usize;
863 let out_start = &*graph.out_start;
864 let out_adj = &*graph.out_adj;
865 let mut in_start = vec![0u32; n + 1];
866 let mut in_adj = vec![0u32; m];
867
868 // 1) Count in-degrees.
869 for &target in out_adj {
870 in_start[target as usize] += 1;
871 }
872 // 2) Prefix sum: in-degrees to start offsets.
873 let mut next_start = 0u32;
874 for slot in &mut in_start[..n] {
875 let in_degree = *slot;
876 *slot = next_start;
877 next_start += in_degree;
878 }
879 // 3) Fill; in_start[target] doubles as write pointer. The ascending node scan leaves each
880 // in-list sorted.
881 for v in 0..n {
882 for &target in &out_adj[out_start[v] as usize..out_start[v + 1] as usize] {
883 let slot = &mut in_start[target as usize];
884 in_adj[*slot as usize] = v as u32;
885 *slot += 1;
886 }
887 }
888 // 4) Repair: step 3 shifted the offsets left by one; a right shift restores them, the
889 // sentinel included.
890 for v in (1..=n).rev() {
891 in_start[v] = in_start[v - 1];
892 }
893 in_start[0] = 0;
894
895 Self::from_parts(
896 Arc::clone(&graph.out_start),
897 Arc::clone(&graph.out_adj),
898 share(in_start),
899 share(in_adj),
900 )
901 }
902
903 /// Returns this graph as a plain `&Graph`; the same as dereferencing.
904 ///
905 /// **Time:** O(1).
906 #[inline]
907 pub fn as_graph(&self) -> &Graph {
908 &self.graph
909 }
910
911 /// The in-adjacency offsets, for [`csr`](crate::csr) and the algorithms.
912 #[inline]
913 pub(crate) fn in_adjacency_start(&self) -> &[u32] {
914 &self.in_start
915 }
916
917 /// The in-adjacency sources, for [`csr`](crate::csr) and the algorithms.
918 #[inline]
919 pub(crate) fn in_adjacency(&self) -> &[u32] {
920 &self.in_adj
921 }
922
923 /// Returns the in-degree of `node`. That is the number of edges with `node` as target.
924 ///
925 /// **Time:** O(1).
926 ///
927 /// # Panics
928 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
929 #[inline]
930 #[track_caller]
931 pub fn in_degree(&self, node: u32) -> u32 {
932 check_index(node, self.node_count());
933 let v = node as usize;
934 self.in_start[v + 1] - self.in_start[v]
935 }
936
937 /// Returns the in-nodes of `node` in ascending order. These are the sources of the edges with
938 /// `node` as target.
939 ///
940 /// The result is a view of this graph's own array, not a copy.
941 ///
942 /// **Time:** O(1).
943 ///
944 /// # Panics
945 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
946 #[inline]
947 #[track_caller]
948 pub fn in_nodes(&self, node: u32) -> SortedIntView<'_> {
949 check_index(node, self.node_count());
950 let v = node as usize;
951 SortedIntView::new(&self.in_adj[self.in_start[v] as usize..self.in_start[v + 1] as usize])
952 }
953
954 /// Returns whether the edge `in_node -> node` exists; an `in_node` out of range yields
955 /// `false`.
956 ///
957 /// **Time:** O(log in_degree(node)).
958 ///
959 /// # Panics
960 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
961 #[inline]
962 #[track_caller]
963 pub fn has_in_node(&self, node: u32, in_node: u32) -> bool {
964 check_index(node, self.node_count());
965 let v = node as usize;
966 contains_in_range(
967 &self.in_adj,
968 self.in_start[v] as usize,
969 self.in_start[v + 1] as usize,
970 in_node,
971 )
972 }
973
974 /// Returns the transposed graph as a view of this graph's arrays. The transposed graph has
975 /// every edge reversed.
976 ///
977 /// Node IDs stay the same, edge indices do not: edge `e` of the transposed graph is in general
978 /// not the reverse of edge `e` of this graph.
979 /// [`transposed_edge_index`](Self::transposed_edge_index) translates one edge index, and
980 /// [`graphs::transposed_edge_mapping`](crate::graphs::transposed_edge_mapping) translates all
981 /// of them.
982 ///
983 /// A plain [`Graph`] needs its in-adjacency first: `BiAdjacentGraph::of(&graph).transposed()`.
984 /// Here, the packages of a program that depend on `model`, directly or indirectly, are the ones
985 /// reachable from it against the direction of the dependencies:
986 ///
987 /// <!-- example: transposing.rs#transposed -->
988 /// ```
989 /// # use graphity_core::{BiAdjacentGraph, graphs};
990 /// # let dependencies = graphity_core::Graph::of(
991 /// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
992 /// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
993 /// # ).unwrap();
994 /// let model = 4;
995 /// let used_by = BiAdjacentGraph::of(&dependencies).transposed();
996 /// let affected = graphs::reachable_from(&used_by, model);
997 /// // affected: [0, 2, 3, 4, 5] - app, ui, service, model and storage
998 /// # assert_eq!(affected, [0, 2, 3, 4, 5]);
999 /// ```
1000 ///
1001 /// **Time:** O(1).
1002 pub fn transposed(&self) -> BiAdjacentGraph {
1003 Self::from_parts(
1004 Arc::clone(&self.in_start),
1005 Arc::clone(&self.in_adj),
1006 Arc::clone(&self.graph.out_start),
1007 Arc::clone(&self.graph.out_adj),
1008 )
1009 }
1010
1011 /// Returns the edge index that edge `edge_index` has in the transposed graph.
1012 ///
1013 /// Called on [`transposed`](Self::transposed), it translates back:
1014 /// `transposed().transposed_edge_index(transposed_edge_index(e)) == e`. To translate every
1015 /// edge, [`graphs::transposed_edge_mapping`](crate::graphs::transposed_edge_mapping) needs one
1016 /// pass instead of a search per edge; it maps from the transposed graph to this one.
1017 ///
1018 /// **Time:** O(log node_count).
1019 ///
1020 /// # Panics
1021 /// With an `index out of bounds` message if `edge_index` is not in `0..edge_count()`.
1022 #[track_caller]
1023 pub fn transposed_edge_index(&self, edge_index: u32) -> u32 {
1024 check_index(edge_index, self.edge_count());
1025 let source = self.edge_source(edge_index);
1026 let target = self.graph.out_adj[edge_index as usize] as usize;
1027 index_of_in_range(
1028 &self.in_adj,
1029 self.in_start[target] as usize,
1030 self.in_start[target + 1] as usize,
1031 source,
1032 )
1033 .expect("the in-adjacency holds every edge")
1034 }
1035
1036 /// Returns the degree of `node`. Equivalent to `in_degree(node) + out_degree(node)`.
1037 ///
1038 /// It counts edges, not neighbors: a self-loop counts twice, and so do the edges `node -> v`
1039 /// and `v -> node`, although `v` is one neighbor.
1040 ///
1041 /// **Time:** O(1).
1042 ///
1043 /// # Panics
1044 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
1045 #[inline]
1046 #[track_caller]
1047 pub fn degree(&self, node: u32) -> u32 {
1048 self.in_degree(node) + self.out_degree(node)
1049 }
1050
1051 /// Returns the neighbors of `node` in ascending order and without duplicates. These are its
1052 /// in-nodes and out-nodes.
1053 ///
1054 /// Unlike [`in_nodes`](Self::in_nodes) and [`out_nodes`](Graph::out_nodes), which are views,
1055 /// the result is a copy, merged on every call.
1056 ///
1057 /// **Time:** O(in_degree(node) + out_degree(node)).
1058 /// **Memory:** up to 4 x (in_degree(node) + out_degree(node)) bytes for the result; while it
1059 /// runs, up to as much again if a neighbor is both an in-node and an out-node.
1060 ///
1061 /// # Panics
1062 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
1063 #[track_caller]
1064 pub fn neighbors(&self, node: u32) -> SortedIntView<'static> {
1065 check_index(node, self.node_count());
1066 let v = node as usize;
1067 let out_start = &self.graph.out_start;
1068 SortedIntView::owned(union_of(
1069 &self.graph.out_adj[out_start[v] as usize..out_start[v + 1] as usize],
1070 &self.in_adj[self.in_start[v] as usize..self.in_start[v + 1] as usize],
1071 ))
1072 }
1073
1074 /// Returns whether `neighbor` is a neighbor of `node`; a `neighbor` out of range yields
1075 /// `false`. Equivalent to `has_out_node(node, neighbor) || has_in_node(node, neighbor)`.
1076 ///
1077 /// **Time:** O(log out_degree(node) + log in_degree(node)).
1078 ///
1079 /// # Panics
1080 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
1081 #[inline]
1082 #[track_caller]
1083 pub fn has_neighbor(&self, node: u32, neighbor: u32) -> bool {
1084 self.has_out_node(node, neighbor) || self.has_in_node(node, neighbor)
1085 }
1086
1087 /// Returns whether `node` is a root node. Equivalent to `in_degree(node) == 0`.
1088 ///
1089 /// [`graphs::root_nodes`](crate::graphs::root_nodes) returns all root nodes.
1090 ///
1091 /// **Time:** O(1).
1092 ///
1093 /// # Panics
1094 /// With an `index out of bounds` message if `node` is not in `0..node_count()`.
1095 #[inline]
1096 #[track_caller]
1097 pub fn is_root_node(&self, node: u32) -> bool {
1098 self.in_degree(node) == 0
1099 }
1100}
1101
1102impl Deref for BiAdjacentGraph {
1103 type Target = Graph;
1104
1105 #[inline]
1106 fn deref(&self) -> &Graph {
1107 &self.graph
1108 }
1109}
1110
1111impl AsRef<Graph> for BiAdjacentGraph {
1112 fn as_ref(&self) -> &Graph {
1113 &self.graph
1114 }
1115}
1116
1117impl From<Graph> for BiAdjacentGraph {
1118 /// [`BiAdjacentGraph::of`] for a graph that is handed over.
1119 fn from(graph: Graph) -> Self {
1120 Self::of(&graph)
1121 }
1122}
1123
1124impl PartialEq for BiAdjacentGraph {
1125 fn eq(&self, other: &BiAdjacentGraph) -> bool {
1126 self.graph == other.graph
1127 }
1128}
1129
1130impl Eq for BiAdjacentGraph {}
1131
1132impl PartialEq<Graph> for BiAdjacentGraph {
1133 fn eq(&self, other: &Graph) -> bool {
1134 self.graph == *other
1135 }
1136}
1137
1138impl PartialEq<BiAdjacentGraph> for Graph {
1139 fn eq(&self, other: &BiAdjacentGraph) -> bool {
1140 *self == other.graph
1141 }
1142}
1143
1144impl Hash for BiAdjacentGraph {
1145 fn hash<H: Hasher>(&self, state: &mut H) {
1146 self.graph.hash(state);
1147 }
1148}
1149
1150impl fmt::Display for BiAdjacentGraph {
1151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152 fmt::Display::fmt(&self.graph, f)
1153 }
1154}
1155
1156impl fmt::Debug for BiAdjacentGraph {
1157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158 fmt::Display::fmt(&self.graph, f)
1159 }
1160}