Skip to main content

tilo_actions/
text.rs

1//! The smallest change between two texts.
2
3/// How long a run `a` and `b` share at their start, and how long a run they
4/// share at their end after it (the two never overlap).
5#[must_use]
6pub fn common_ends<T: PartialEq>(a: &[T], b: &[T]) -> (usize, usize) {
7    let prefix = a
8        .iter()
9        .zip(b)
10        .take_while(|(left, right)| left == right)
11        .count();
12    let room = a.len().min(b.len()).saturating_sub(prefix);
13    let suffix = a
14        .iter()
15        .rev()
16        .zip(b.iter().rev())
17        .take(room)
18        .take_while(|(left, right)| left == right)
19        .count();
20    (prefix, suffix)
21}
22
23/// [`common_ends`] of two texts, in bytes, on character boundaries: the
24/// texts are compared byte by byte, never decoded into characters.
25#[must_use]
26pub fn common_text_ends(a: &str, b: &str) -> (usize, usize) {
27    let mut prefix = a
28        .bytes()
29        .zip(b.bytes())
30        .take_while(|(left, right)| left == right)
31        .count();
32    while !(a.is_char_boundary(prefix) && b.is_char_boundary(prefix)) {
33        prefix = prefix.saturating_sub(1);
34    }
35    let ((_, a), (_, b)) = (a.split_at(prefix), b.split_at(prefix));
36    let mut suffix = a
37        .bytes()
38        .rev()
39        .zip(b.bytes().rev())
40        .take_while(|(left, right)| left == right)
41        .count();
42    while !(a.is_char_boundary(a.len().saturating_sub(suffix))
43        && b.is_char_boundary(b.len().saturating_sub(suffix)))
44    {
45        suffix = suffix.saturating_sub(1);
46    }
47    (prefix, suffix)
48}
49
50/// A splice in characters: at `at`, `delete` characters give way to `insert`.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Splice {
53    pub at: usize,
54    pub delete: usize,
55    pub insert: String,
56}
57
58/// The smallest splice, in characters, that turns `before` into `after`:
59/// what the two share at their start and end is kept.
60#[must_use]
61pub fn splice_between(before: &str, after: &str) -> Option<Splice> {
62    if before == after {
63        return None;
64    }
65    let (start, end) = common_text_ends(before, after);
66    let (kept, deleted) = before.split_at(start);
67    let (deleted, _) = deleted.split_at(deleted.len().saturating_sub(end));
68    let (_, inserted) = after.split_at(start);
69    let (inserted, _) = inserted.split_at(inserted.len().saturating_sub(end));
70    Some(Splice {
71        at: kept.chars().count(),
72        delete: deleted.chars().count(),
73        insert: inserted.to_owned(),
74    })
75}