Skip to main content

tilo_resource/
diff.rs

1//! Structural diffs between two versions of the same resource.
2//!
3//! Items in a resource keep their identity across every edit, so two versions
4//! align by id rather than by fuzzy content matching: [`align`] pairs the
5//! items both versions hold and names the ones only one side has. Text within
6//! a paired item diffs by character ([`text_runs`]).
7
8use std::collections::HashMap;
9use std::hash::Hash;
10
11use serde::{Deserialize, Serialize};
12
13/// One step of an alignment of two keyed sequences, in reading order.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Step<'a, K> {
16    /// Present in both versions, in the same relative order.
17    Both(&'a K),
18    /// Only in the old version (removed, or moved out of order).
19    OldOnly(&'a K),
20    /// Only in the new version (added, or moved out of order).
21    NewOnly(&'a K),
22}
23
24/// Align two sequences of item ids: the longest run of ids both keep in the
25/// same order is [`Step::Both`], the rest is removed or added. Between two
26/// kept ids, the removed ones come first.
27///
28/// Ids are expected to be unique within each sequence (a repeated id pairs
29/// once). Common leading and trailing runs are paired directly, so the usual
30/// local edit costs as much as the edit; the middle aligns in
31/// `O(n log n)` as the longest increasing run of new positions.
32pub fn align<'a, K: Eq + Hash>(old: &'a [K], new: &'a [K]) -> Vec<Step<'a, K>> {
33    let (prefix, suffix) = crate::text::common_ends(old, new);
34    let (old_rest, new_rest) = (
35        old.get(prefix..).unwrap_or(&[]),
36        new.get(prefix..).unwrap_or(&[]),
37    );
38    let old_mid = old_rest
39        .get(..old_rest.len().saturating_sub(suffix))
40        .unwrap_or(&[]);
41    let new_mid = new_rest
42        .get(..new_rest.len().saturating_sub(suffix))
43        .unwrap_or(&[]);
44
45    let mut steps = Vec::with_capacity(old.len().max(new.len()));
46    steps.extend(old.get(..prefix).unwrap_or(&[]).iter().map(Step::Both));
47
48    let mut position: HashMap<&K, usize> = HashMap::with_capacity(new_mid.len());
49    for (index, key) in new_mid.iter().enumerate() {
50        position.entry(key).or_insert(index);
51    }
52    let targets: Vec<Option<usize>> = old_mid
53        .iter()
54        .map(|key| position.get(key).copied())
55        .collect();
56    let pairs = increasing_pairs(&targets);
57    let (mut next_old, mut next_new) = (0usize, 0usize);
58    for (old_index, new_index) in pairs {
59        steps.extend(
60            old_mid
61                .get(next_old..old_index)
62                .unwrap_or(&[])
63                .iter()
64                .map(Step::OldOnly),
65        );
66        steps.extend(
67            new_mid
68                .get(next_new..new_index)
69                .unwrap_or(&[])
70                .iter()
71                .map(Step::NewOnly),
72        );
73        if let Some(key) = new_mid.get(new_index) {
74            steps.push(Step::Both(key));
75        }
76        next_old = old_index.saturating_add(1);
77        next_new = new_index.saturating_add(1);
78    }
79    steps.extend(
80        old_mid
81            .get(next_old..)
82            .unwrap_or(&[])
83            .iter()
84            .map(Step::OldOnly),
85    );
86    steps.extend(
87        new_mid
88            .get(next_new..)
89            .unwrap_or(&[])
90            .iter()
91            .map(Step::NewOnly),
92    );
93    steps.extend(
94        old_rest
95            .get(old_rest.len().saturating_sub(suffix)..)
96            .unwrap_or(&[])
97            .iter()
98            .map(Step::Both),
99    );
100    steps
101}
102
103/// `(old index, new index)` of one longest strictly increasing run of the
104/// present `targets`, in order.
105fn increasing_pairs(targets: &[Option<usize>]) -> Vec<(usize, usize)> {
106    let mut tails: Vec<usize> = Vec::new();
107    let mut previous: Vec<Option<usize>> = vec![None; targets.len()];
108    for (index, target) in targets.iter().enumerate() {
109        let Some(target) = *target else { continue };
110        let slot = tails.partition_point(|&tail| {
111            targets
112                .get(tail)
113                .copied()
114                .flatten()
115                .is_some_and(|t| t < target)
116        });
117        if let Some(before) = slot.checked_sub(1)
118            && let Some(link) = previous.get_mut(index)
119        {
120            *link = tails.get(before).copied();
121        }
122        if slot == tails.len() {
123            tails.push(index);
124        } else if let Some(tail) = tails.get_mut(slot) {
125            *tail = index;
126        }
127    }
128    let mut chain = Vec::with_capacity(tails.len());
129    let mut cursor = tails.last().copied();
130    while let Some(index) = cursor {
131        if let Some(Some(target)) = targets.get(index) {
132            chain.push((index, *target));
133        }
134        cursor = previous.get(index).copied().flatten();
135    }
136    chain.reverse();
137    chain
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct TextRun {
142    pub op: RunOp,
143    pub text: String,
144}
145
146/// The kind of a [`TextRun`].
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148pub enum RunOp {
149    Equal,
150    Insert,
151    Delete,
152}
153
154/// Above this many differing characters a text diff falls back to a coarse
155/// whole-span replace, so a pathologically long edit can't drive the
156/// quadratic character alignment.
157const RUN_DIFF_CHAR_CAP: usize = 8_192;
158
159/// Character-level diff of two texts into `Equal`/`Insert`/`Delete` runs: the
160/// common start and end are equal, the span between them aligns by longest
161/// common subsequence (or, past a size cap, is replaced whole).
162pub fn text_runs(old: &str, new: &str) -> Vec<TextRun> {
163    let a: Vec<char> = old.chars().collect();
164    let b: Vec<char> = new.chars().collect();
165    let (prefix, suffix) = crate::text::common_ends(&a, &b);
166    let a_mid = a.get(prefix..a.len().saturating_sub(suffix)).unwrap_or(&[]);
167    let b_mid = b.get(prefix..b.len().saturating_sub(suffix)).unwrap_or(&[]);
168
169    let mut ops: Vec<(RunOp, char)> = Vec::with_capacity(a.len().max(b.len()));
170    ops.extend(
171        a.get(..prefix)
172            .unwrap_or(&[])
173            .iter()
174            .map(|c| (RunOp::Equal, *c)),
175    );
176    if a_mid.len() > RUN_DIFF_CHAR_CAP || b_mid.len() > RUN_DIFF_CHAR_CAP {
177        ops.extend(a_mid.iter().map(|c| (RunOp::Delete, *c)));
178        ops.extend(b_mid.iter().map(|c| (RunOp::Insert, *c)));
179    } else {
180        ops.extend(lcs_char_ops(a_mid, b_mid));
181    }
182    ops.extend(
183        a.get(a.len().saturating_sub(suffix)..)
184            .unwrap_or(&[])
185            .iter()
186            .map(|c| (RunOp::Equal, *c)),
187    );
188    coalesce(ops)
189}
190
191/// `dp[i][j]`, or `0` past either edge.
192fn dp_at(dp: &[Vec<u32>], i: usize, j: usize) -> u32 {
193    dp.get(i).and_then(|row| row.get(j)).copied().unwrap_or(0)
194}
195
196/// Per-character LCS edit script over two char slices.
197fn lcs_char_ops(old: &[char], new: &[char]) -> Vec<(RunOp, char)> {
198    let n = old.len();
199    let m = new.len();
200    let mut dp = vec![vec![0u32; m.saturating_add(1)]; n.saturating_add(1)];
201    for i in (0..n).rev() {
202        for j in (0..m).rev() {
203            let value = match (old.get(i).copied(), new.get(j).copied()) {
204                (Some(oi), Some(nj)) if oi == nj => {
205                    dp_at(&dp, i.saturating_add(1), j.saturating_add(1)).saturating_add(1)
206                }
207                _ => dp_at(&dp, i.saturating_add(1), j).max(dp_at(&dp, i, j.saturating_add(1))),
208            };
209            if let Some(cell) = dp.get_mut(i).and_then(|row| row.get_mut(j)) {
210                *cell = value;
211            }
212        }
213    }
214    let mut ops = Vec::new();
215    let (mut i, mut j) = (0, 0);
216    while i < n && j < m {
217        let (Some(oi), Some(nj)) = (old.get(i).copied(), new.get(j).copied()) else {
218            break;
219        };
220        if oi == nj {
221            ops.push((RunOp::Equal, oi));
222            i = i.saturating_add(1);
223            j = j.saturating_add(1);
224        } else if dp_at(&dp, i.saturating_add(1), j) >= dp_at(&dp, i, j.saturating_add(1)) {
225            ops.push((RunOp::Delete, oi));
226            i = i.saturating_add(1);
227        } else {
228            ops.push((RunOp::Insert, nj));
229            j = j.saturating_add(1);
230        }
231    }
232    ops.extend(
233        old.get(i..)
234            .unwrap_or(&[])
235            .iter()
236            .map(|c| (RunOp::Delete, *c)),
237    );
238    ops.extend(
239        new.get(j..)
240            .unwrap_or(&[])
241            .iter()
242            .map(|c| (RunOp::Insert, *c)),
243    );
244    ops
245}
246
247/// Merge a per-character op stream into contiguous runs.
248fn coalesce(ops: Vec<(RunOp, char)>) -> Vec<TextRun> {
249    let mut runs: Vec<TextRun> = Vec::new();
250    for (op, ch) in ops {
251        match runs.last_mut() {
252            Some(run) if run.op == op => run.text.push(ch),
253            _ => runs.push(TextRun {
254                op,
255                text: ch.to_string(),
256            }),
257        }
258    }
259    runs
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    fn render(steps: &[Step<'_, &str>]) -> String {
267        steps
268            .iter()
269            .map(|step| match step {
270                Step::Both(k) => format!("={k}"),
271                Step::OldOnly(k) => format!("-{k}"),
272                Step::NewOnly(k) => format!("+{k}"),
273            })
274            .collect::<Vec<_>>()
275            .join(" ")
276    }
277
278    tilo_test_env::scenario! {
279        fn an_alignment_keeps_what_both_sides_share;
280
281        phase a_local_edit_aligns_everything_else;
282        {
283            let old = ["a", "b", "c", "d", "e"];
284            let new = ["a", "b", "x", "d", "e"];
285            assert_eq!(render(&align(&old, &new)), "=a =b -c +x =d =e");
286            let new = ["a", "d", "b", "c", "e"];
287            assert_eq!(render(&align(&old, &new)), "=a +d =b =c -d =e");
288        }
289
290        phase disjoint_and_empty_sides;
291        {
292            let none: [&str; 0] = [];
293            assert_eq!(render(&align(&["a", "b"], &none)), "-a -b");
294            assert_eq!(render(&align(&none, &["a"])), "+a");
295            assert_eq!(render(&align(&["a"], &["b"])), "-a +b");
296        }
297
298        phase alignment_keeps_a_longest_common_order_on_large_inputs;
299        {
300            let old: Vec<String> = (0..20_000).map(|n| format!("id{n}")).collect();
301            let mut new = old.clone();
302            new.remove(5_000);
303            new.insert(15_000, "fresh".into());
304            let moved = new.remove(100);
305            new.push(moved);
306            let steps = align(&old, &new);
307            let both = steps.iter().filter(|s| matches!(s, Step::Both(_))).count();
308            assert_eq!(both, 20_000 - 2);
309            let added = steps
310                .iter()
311                .filter(|s| matches!(s, Step::NewOnly(_)))
312                .count();
313            assert_eq!(added, 2);
314        }
315
316        phase text_runs_keep_the_common_start_and_end;
317        {
318            let runs = text_runs("the quick fox", "the quick brown fox");
319            assert_eq!(
320                runs,
321                [
322                    TextRun {
323                        op: RunOp::Equal,
324                        text: "the quick ".into()
325                    },
326                    TextRun {
327                        op: RunOp::Insert,
328                        text: "brown ".into()
329                    },
330                    TextRun {
331                        op: RunOp::Equal,
332                        text: "fox".into()
333                    },
334                ]
335            );
336            assert!(text_runs("", "").is_empty());
337            assert_eq!(
338                text_runs("ab", "b").first().map(|r| r.op),
339                Some(RunOp::Delete)
340            );
341        }
342    }
343}