link_cli/changes_simplifier.rs
1//! Simplifies the raw changes of one query to the net change of every link.
2//!
3//! Corresponds to `ChangesSimplifier.cs` in C#.
4
5use crate::link::{GenericLink, Link};
6use doublets::data::LinkReference;
7use std::collections::HashMap;
8
9/// Reduces the raw `(before, after)` steps a store reports to one change per
10/// link address: from its state before the query to its state after it.
11///
12/// The store reports every step it takes — a link is emptied to `(i: 0 0)`
13/// before it is deleted and created as `(i: 0 0)` before it is set — and the
14/// null link `(0: 0 0)` stands for "no link", before a creation and after a
15/// deletion. The steps of one address form a chain, so its net change is the
16/// `before` of its first step and the `after` of its last:
17///
18/// - a link created and deleted again within the query is not reported;
19/// - a link that ends where it started is reported unchanged, like a link the
20/// query only matched.
21///
22/// The changes are ordered by their `after` state, so deletions come first;
23/// changes with equal `after` states keep the order of their first step.
24pub fn simplify_changes(changes: Vec<(Link, Link)>) -> Vec<(Link, Link)> {
25 simplify_generic_changes(changes)
26}
27
28/// Net changes without narrowing the caller's chosen address type.
29pub fn simplify_generic_changes<T: LinkReference>(
30 changes: Vec<(GenericLink<T>, GenericLink<T>)>,
31) -> Vec<(GenericLink<T>, GenericLink<T>)> {
32 let mut net_changes: Vec<(GenericLink<T>, GenericLink<T>)> = Vec::new();
33 let mut position_of_address: HashMap<T, usize> = HashMap::new();
34 for (before, after) in changes {
35 let address = if before.index != T::from_byte(0) {
36 before.index
37 } else {
38 after.index
39 };
40 if address == T::from_byte(0) {
41 continue;
42 }
43 match position_of_address.get(&address) {
44 Some(&position) => net_changes[position].1 = after,
45 None => {
46 position_of_address.insert(address, net_changes.len());
47 net_changes.push((before, after));
48 }
49 }
50 }
51 net_changes.retain(|(before, after)| !(before.is_null() && after.is_null()));
52 net_changes.sort_by_key(|(_, after)| (after.index, after.source, after.target));
53 net_changes
54}