Skip to main content

graphity_core/
graph_diff.rs

1use std::fmt;
2
3use crate::Edges;
4
5/// The edges added and removed between two graphs over the same nodes, as
6/// [`graphs::diff`](crate::graphs::diff) returns them.
7///
8/// Each edge comes with its edge index in the graph it belongs to: an added edge with its edge index
9/// in the newer graph, a removed edge with its edge index in the older one. With these edge indices,
10/// the caller can look up data on the edges of either graph in arrays indexed by edge index. Both
11/// lists are in edge index order. To see whether a graph changed without keeping the older one,
12/// compare hashes from [`graphs::topology_hash`](crate::graphs::topology_hash) instead.
13///
14/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
15///
16/// **Memory:** 12 bytes per added or removed edge.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct GraphDiff {
19    added_edges: Edges,
20    removed_edges: Edges,
21}
22
23impl GraphDiff {
24    pub(crate) fn new(added_edges: Edges, removed_edges: Edges) -> Self {
25        Self {
26            added_edges,
27            removed_edges,
28        }
29    }
30
31    /// Returns the edges of the newer graph that the older one does not have, with their edge indices in
32    /// the newer graph, in edge index order.
33    ///
34    /// **Time:** O(1).
35    pub fn added_edges(&self) -> &Edges {
36        &self.added_edges
37    }
38
39    /// Returns the edges of the older graph that the newer one does not have, with their edge indices in
40    /// the older graph, in edge index order.
41    ///
42    /// **Time:** O(1).
43    pub fn removed_edges(&self) -> &Edges {
44        &self.removed_edges
45    }
46
47    /// Returns whether no edge was added or removed, that is, whether the two graphs are equal.
48    /// Equivalent to `added_edges().is_empty() && removed_edges().is_empty()`.
49    ///
50    /// **Time:** O(1).
51    pub fn is_empty(&self) -> bool {
52        self.added_edges.is_empty() && self.removed_edges.is_empty()
53    }
54}
55
56/// Writes the numbers of added and removed edges, for debuggers and logs.
57///
58/// **Time:** O(1).
59impl fmt::Display for GraphDiff {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(
62            f,
63            "GraphDiff[added={}, removed={}]",
64            self.added_edges.count(),
65            self.removed_edges.count()
66        )
67    }
68}