Skip to main content

nsh_core/
list_diff.rs

1//! How a keyed list's rows changed: which rows stayed, which moved, which
2//! came and which went, from the rows' keys before and after.
3//!
4//! With it a virtualized list keeps each row's measured size, and each
5//! rendered row's cell and content, wherever the row goes: a row that
6//! changes place keeps its cell (and the state inside it: a focus, an open
7//! menu), and so do the rows it passes. Only rows whose key is new need a
8//! cell, and only rows whose key is gone give theirs back.
9//!
10//! [`ListDiff::new`] pairs rows by key (repeated keys pair up in order, a
11//! row without a key pairs with none); of the rows paired, those that kept
12//! their order are [`DiffRun::Kept`] and the others [`DiffRun::Moved`].
13
14use std::hash::Hash;
15
16use rustc_hash::FxHashMap;
17
18const NONE: u32 = u32::MAX;
19
20/// A stretch of a list's new rows ([`ListDiff::runs`]).
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum DiffRun {
23    /// `len` rows that were at `from..from + len`, in the order the rows
24    /// around them kept.
25    Kept {
26        /// The first row's index before.
27        from: u32,
28        /// How many rows.
29        len: u32,
30    },
31    /// `len` rows that were at `from..from + len` and changed place among
32    /// the kept rows.
33    Moved {
34        /// The first row's index before.
35        from: u32,
36        /// How many rows.
37        len: u32,
38    },
39    /// `len` rows whose keys are new.
40    Inserted {
41        /// How many rows.
42        len: u32,
43    },
44}
45
46impl DiffRun {
47    /// How many new rows the run covers.
48    pub fn len(&self) -> u32 {
49        match *self {
50            Self::Kept { len, .. } | Self::Moved { len, .. } | Self::Inserted { len } => len,
51        }
52    }
53
54    /// Whether the run covers no rows.
55    pub fn is_empty(&self) -> bool {
56        self.len() == 0
57    }
58
59    /// The old index of the run's first row, unless the rows are new.
60    pub fn from(&self) -> Option<u32> {
61        match *self {
62            Self::Kept { from, .. } | Self::Moved { from, .. } => Some(from),
63            Self::Inserted { .. } => None,
64        }
65    }
66}
67
68/// How a list's rows changed, by key: its new rows in order, as runs of
69/// rows kept, moved or inserted. Old rows no run covers were removed.
70#[derive(Debug, Clone, PartialEq, Eq, Default)]
71#[non_exhaustive]
72pub struct ListDiff {
73    /// How many rows there were.
74    pub old_len: u32,
75    /// How many rows there are.
76    pub new_len: u32,
77    /// The new rows in order.
78    pub runs: Vec<DiffRun>,
79}
80
81impl ListDiff {
82    /// How the rows with keys `old` became the rows with keys `new`;
83    /// `None` when they are the same.
84    pub fn new<K: Copy + Eq + Hash>(old: &[K], new: &[K]) -> Option<Self> {
85        Self::diff(old, new, |k| Some(*k))
86    }
87
88    /// [`ListDiff::new`] for rows that may have no key (`None`): such a row
89    /// matches no other.
90    pub fn new_partial<K: Copy + Eq + Hash>(old: &[Option<K>], new: &[Option<K>]) -> Option<Self> {
91        Self::diff(old, new, |k| *k)
92    }
93
94    fn diff<T, K: Copy + Eq + Hash>(
95        old: &[T],
96        new: &[T],
97        key: impl Fn(&T) -> Option<K> + Copy,
98    ) -> Option<Self> {
99        let same = |a: &T, b: &T| key(a).is_some_and(|a| Some(a) == key(b));
100        let start = old.iter().zip(new).take_while(|(a, b)| same(a, b)).count();
101        let end = old[start..]
102            .iter()
103            .rev()
104            .zip(new[start..].iter().rev())
105            .take_while(|(a, b)| same(a, b))
106            .count();
107        if start + end == old.len() && start + end == new.len() {
108            return None;
109        }
110        let (middle_old, middle_new) = (&old[start..old.len() - end], &new[start..new.len() - end]);
111        let mut diff = Self {
112            old_len: old.len() as u32,
113            new_len: new.len() as u32,
114            runs: Vec::new(),
115        };
116        diff.push(DiffRun::Kept {
117            from: 0,
118            len: start as u32,
119        });
120        // The old row each new one is (by its key's occurrence), and which
121        // of them keep their order: the longest increasing run of old rows.
122        let sources = match_keys(middle_old, middle_new, key);
123        let kept = longest_increasing(&sources);
124        let offset = start as u32;
125        for (j, &i) in sources.iter().enumerate() {
126            diff.push(if i == NONE {
127                DiffRun::Inserted { len: 1 }
128            } else if kept[j] {
129                DiffRun::Kept {
130                    from: offset + i,
131                    len: 1,
132                }
133            } else {
134                DiffRun::Moved {
135                    from: offset + i,
136                    len: 1,
137                }
138            });
139        }
140        diff.push(DiffRun::Kept {
141            from: (old.len() - end) as u32,
142            len: end as u32,
143        });
144        Some(diff)
145    }
146
147    /// A diff that removes `removed` rows at `at` of `old_len` and inserts
148    /// `inserted` there.
149    pub fn splice(old_len: u32, at: u32, removed: u32, inserted: u32) -> Self {
150        let at = at.min(old_len);
151        let removed = removed.min(old_len - at);
152        let mut diff = Self {
153            old_len,
154            new_len: old_len - removed + inserted,
155            runs: Vec::new(),
156        };
157        diff.push(DiffRun::Kept { from: 0, len: at });
158        diff.push(DiffRun::Inserted { len: inserted });
159        diff.push(DiffRun::Kept {
160            from: at + removed,
161            len: old_len - at - removed,
162        });
163        diff
164    }
165
166    /// The diff of rows inside a list: `before` rows before them and
167    /// `after` rows after them stayed as they were.
168    pub fn widened(self, before: u32, after: u32) -> Self {
169        let mut diff = Self {
170            old_len: before + self.old_len + after,
171            new_len: before + self.new_len + after,
172            runs: Vec::with_capacity(self.runs.len() + 2),
173        };
174        diff.push(DiffRun::Kept {
175            from: 0,
176            len: before,
177        });
178        for run in self.runs {
179            diff.push(match run {
180                DiffRun::Kept { from, len } => DiffRun::Kept {
181                    from: from + before,
182                    len,
183                },
184                DiffRun::Moved { from, len } => DiffRun::Moved {
185                    from: from + before,
186                    len,
187                },
188                DiffRun::Inserted { len } => DiffRun::Inserted { len },
189            });
190        }
191        diff.push(DiffRun::Kept {
192            from: before + self.old_len,
193            len: after,
194        });
195        diff
196    }
197
198    /// Appends `run`, merged into the last one when it continues it.
199    fn push(&mut self, run: DiffRun) {
200        if run.is_empty() {
201            return;
202        }
203        let merged = match (self.runs.last_mut(), run) {
204            (Some(DiffRun::Inserted { len }), DiffRun::Inserted { len: more }) => {
205                *len += more;
206                true
207            }
208            (
209                Some(DiffRun::Kept { from, len }),
210                DiffRun::Kept {
211                    from: next,
212                    len: more,
213                },
214            )
215            | (
216                Some(DiffRun::Moved { from, len }),
217                DiffRun::Moved {
218                    from: next,
219                    len: more,
220                },
221            ) if *from + *len == next => {
222                *len += more;
223                true
224            }
225            _ => false,
226        };
227        if !merged {
228            self.runs.push(run);
229        }
230    }
231
232    /// The change as one splice, `(at, removed, inserted)`, when it is one
233    /// (no row moved, and one stretch of rows changed).
234    pub fn as_splice(&self) -> Option<(u32, u32, u32)> {
235        let mut runs = self.runs.as_slice();
236        let mut at = 0;
237        if let [DiffRun::Kept { from: 0, len }, rest @ ..] = runs {
238            at = *len;
239            runs = rest;
240        }
241        let mut inserted = 0;
242        if let [DiffRun::Inserted { len }, rest @ ..] = runs {
243            inserted = *len;
244            runs = rest;
245        }
246        let resume = match runs {
247            [] => self.old_len,
248            [DiffRun::Kept { from, len }] if from + len == self.old_len => *from,
249            _ => return None,
250        };
251        (resume >= at).then_some((at, resume - at, inserted))
252    }
253
254    /// Each old row's new index, `None` for the rows removed.
255    pub fn new_indices(&self) -> Vec<Option<u32>> {
256        let mut out = vec![None; self.old_len as usize];
257        let mut at = 0;
258        for run in &self.runs {
259            if let Some(from) = run.from() {
260                for k in 0..run.len() {
261                    if let Some(slot) = out.get_mut((from + k) as usize) {
262                        *slot = Some(at + k);
263                    }
264                }
265            }
266            at += run.len();
267        }
268        out
269    }
270
271    /// Old row `old`'s new index, and whether it moved; `None` when it was
272    /// removed. O(runs): for a few rows (the cells), not every row.
273    pub fn new_index(&self, old: u32) -> Option<(u32, bool)> {
274        let mut at = 0;
275        for run in &self.runs {
276            if let Some(from) = run.from()
277                && (from..from + run.len()).contains(&old)
278            {
279                return Some((at + old - from, matches!(run, DiffRun::Moved { .. })));
280            }
281            at += run.len();
282        }
283        None
284    }
285}
286
287/// For each of `new`'s rows, the index in `old` of the row with its key
288/// (the n-th occurrence of a key in `new` is its n-th in `old`), or
289/// [`NONE`].
290fn match_keys<T, K: Copy + Eq + Hash>(
291    old: &[T],
292    new: &[T],
293    key: impl Fn(&T) -> Option<K>,
294) -> Vec<u32> {
295    // The first unmatched old row of each key, and the next of the same
296    // key after each row.
297    let mut head: FxHashMap<K, u32> = FxHashMap::default();
298    head.reserve(old.len());
299    let mut next = vec![NONE; old.len()];
300    for (i, row) in old.iter().enumerate().rev() {
301        if let Some(k) = key(row) {
302            next[i] = head.insert(k, i as u32).unwrap_or(NONE);
303        }
304    }
305    new.iter()
306        .map(|row| {
307            let Some(first) = key(row).and_then(|k| head.get_mut(&k)) else {
308                return NONE;
309            };
310            let i = *first;
311            if i != NONE {
312                *first = next[i as usize];
313            }
314            i
315        })
316        .collect()
317}
318
319/// Which of `sources` (old indices, [`NONE`] skipped) form a longest
320/// strictly increasing subsequence: the rows that keep their order.
321fn longest_increasing(sources: &[u32]) -> Vec<bool> {
322    // `tails[k]`: the position of the smallest last value of an increasing
323    // run of length k + 1; `prev`: each position's predecessor in its run.
324    let mut tails: Vec<u32> = Vec::new();
325    let mut prev = vec![NONE; sources.len()];
326    for (j, &value) in sources.iter().enumerate() {
327        if value == NONE {
328            continue;
329        }
330        let k = tails.partition_point(|&t| sources[t as usize] < value);
331        if k > 0 {
332            prev[j] = tails[k - 1];
333        }
334        if k == tails.len() {
335            tails.push(j as u32);
336        } else {
337            tails[k] = j as u32;
338        }
339    }
340    let mut kept = vec![false; sources.len()];
341    let mut at = tails.last().copied().unwrap_or(NONE);
342    while at != NONE {
343        kept[at as usize] = true;
344        at = prev[at as usize];
345    }
346    kept
347}
348
349#[cfg(test)]
350mod tests {
351    use super::{DiffRun, ListDiff};
352
353    fn diff(old: &[u32], new: &[u32]) -> Option<ListDiff> {
354        ListDiff::new(old, new)
355    }
356
357    /// The new rows the diff makes of `old`, new rows taken from `new`.
358    fn apply(old: &[u32], new: &[u32], diff: &ListDiff) -> Vec<u32> {
359        let mut out = Vec::new();
360        for run in &diff.runs {
361            match run.from() {
362                Some(from) => {
363                    out.extend_from_slice(&old[from as usize..(from + run.len()) as usize])
364                }
365                None => out.extend_from_slice(&new[out.len()..out.len() + run.len() as usize]),
366            }
367        }
368        out
369    }
370
371    fn moved(diff: &ListDiff) -> u32 {
372        diff.runs
373            .iter()
374            .filter(|r| matches!(r, DiffRun::Moved { .. }))
375            .map(DiffRun::len)
376            .sum()
377    }
378
379    #[test]
380    fn the_same_rows_are_no_change() {
381        assert_eq!(diff(&[1, 2, 3], &[1, 2, 3]), None);
382        assert_eq!(diff(&[], &[]), None);
383    }
384
385    #[test]
386    fn a_change_in_one_place_is_a_splice() {
387        let splice = |old: &[u32], new: &[u32]| diff(old, new).and_then(|d| d.as_splice());
388        assert_eq!(splice(&[1, 2, 3], &[0, 1, 2, 3]), Some((0, 0, 1)));
389        assert_eq!(splice(&[1, 2, 3], &[1, 3]), Some((1, 1, 0)));
390        assert_eq!(splice(&[1, 2, 3], &[1, 2, 3, 4]), Some((3, 0, 1)));
391        assert_eq!(splice(&[1, 2, 3], &[1, 9, 3]), Some((1, 1, 1)));
392        assert_eq!(splice(&[1, 2, 3], &[]), Some((0, 3, 0)));
393        assert_eq!(splice(&[], &[1, 2]), Some((0, 0, 2)));
394        // A sliding window is two changes.
395        assert_eq!(splice(&[1, 2, 3], &[2, 3, 4]), None);
396        for (at, removed, inserted) in [(0, 0, 1), (1, 1, 0), (3, 0, 2), (1, 2, 1)] {
397            let d = ListDiff::splice(3, at, removed, inserted);
398            assert_eq!(d.as_splice(), Some((at, removed, inserted)), "{d:?}");
399        }
400    }
401
402    #[test]
403    fn repeated_keys_pair_up_in_order() {
404        assert_eq!(diff(&[1, 1], &[1]).unwrap().as_splice(), Some((1, 1, 0)));
405        let d = diff(&[1, 2, 1], &[1, 1, 2]).unwrap();
406        assert_eq!(apply(&[1, 2, 1], &[1, 1, 2], &d), [1, 1, 2]);
407        assert_eq!(moved(&d), 1);
408        // Rows without a key match nothing.
409        let d = ListDiff::new_partial(&[None, Some(1)], &[None, Some(1)]).unwrap();
410        assert_eq!(d.as_splice(), Some((0, 1, 1)));
411    }
412
413    #[test]
414    fn a_row_moved_up_moves_alone() {
415        let old: Vec<u32> = (0..12).collect();
416        let mut new = old.clone();
417        let row = new.remove(10);
418        new.insert(2, row);
419        let d = diff(&old, &new).unwrap();
420        assert_eq!(
421            d.runs,
422            [
423                DiffRun::Kept { from: 0, len: 2 },
424                DiffRun::Moved { from: 10, len: 1 },
425                DiffRun::Kept { from: 2, len: 8 },
426                DiffRun::Kept { from: 11, len: 1 },
427            ]
428        );
429        assert_eq!(d.new_index(10), Some((2, true)));
430        assert_eq!(d.new_index(2), Some((3, false)));
431        assert_eq!(d.new_index(11), Some((11, false)));
432        assert_eq!(d.as_splice(), None);
433    }
434
435    #[test]
436    fn moves_inserts_and_removes_mix() {
437        let old = [1, 2, 3, 4, 5, 6, 7, 8];
438        let new = [9, 6, 1, 2, 4, 5, 10, 8, 3];
439        let d = diff(&old, &new).unwrap();
440        assert_eq!(apply(&old, &new, &d), new);
441        assert_eq!(d.new_len, 9);
442        // 7 went; 6 and 3 moved; 1, 2, 4, 5, 8 kept their order.
443        assert_eq!(moved(&d), 2);
444        let indices = d.new_indices();
445        assert_eq!(indices[6], None);
446        assert_eq!(indices[5], Some(1));
447        assert_eq!(indices[2], Some(8));
448        for (i, n) in indices.iter().enumerate() {
449            assert_eq!(*n, d.new_index(i as u32).map(|(n, _)| n));
450        }
451    }
452
453    #[test]
454    fn a_diff_inside_a_list_widens_to_it() {
455        let d = diff(&[3, 4, 5], &[5, 3, 9]).unwrap().widened(2, 1);
456        let (old, new) = ([1, 2, 3, 4, 5, 6], [1, 2, 5, 3, 9, 6]);
457        assert_eq!(d, diff(&old, &new).unwrap());
458        assert_eq!(apply(&old, &new, &d), new);
459    }
460
461    #[test]
462    fn reversing_keeps_one_row_and_moves_the_rest() {
463        let old: Vec<u32> = (0..6).collect();
464        let new: Vec<u32> = (0..6).rev().collect();
465        let d = diff(&old, &new).unwrap();
466        assert_eq!(apply(&old, &new, &d), new);
467        assert_eq!(moved(&d), 5);
468    }
469
470    #[test]
471    fn large_lists_diff_quickly() {
472        // 100 000 rows, every other one moved by a rotation of pairs: well
473        // within a test's time only if the diff is not quadratic.
474        let old: Vec<u32> = (0..100_000).collect();
475        let mut new = old.clone();
476        new.rotate_left(1);
477        for pair in new.chunks_mut(2) {
478            pair.swap(0, pair.len() - 1);
479        }
480        let start = std::time::Instant::now();
481        let d = diff(&old, &new).unwrap();
482        assert_eq!(apply(&old, &new, &d), new);
483        assert!(start.elapsed().as_secs_f32() < 2.0, "{:?}", start.elapsed());
484    }
485}