Cotton code
251 lines · 12.1 KB · RustRaw
//! THREE TEXTS MADE ONE (owner's lost edit, 21 Nov 2026): a note saved from//! a writer that opened it at 17:50 replaced the bodies the assistant wrote at//! 19:05 and 20:05, whole, and nothing said so. A save whose base is older//! than what the copy holds is merged, line by line, over that base: what only//! one side changed is taken from it, and where both changed the same lines//! both are kept — the writer's first, then the other's — so no words are//! ever dropped without the person seeing them./// The merge of `mine` and `theirs`, both changed from `base`.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Merged {    pub text: String,    /// Some lines both changed: both are in `text`, the writer's first.    pub both_kept: bool,}/// Above this many cells (lines × lines, once the common start and end are/// set aside) the lines are not matched one by one: both texts are kept/// whole, the writer's, then the other's lines it does not hold.const MOST_CELLS: usize = 4_000_000;/// `mine` and `theirs` made one over `base` (a diff3 by lines). Equal sides/// answer `mine`; a side equal to `base` answers the other.////// Each side's changes are hunks of `base` lines replaced (an insertion/// replaces none). Hunks of the two sides that replace the same lines, or/// insert at one place, are one place both changed: both are kept there./// Lines one side inserts just before or after lines the other changed are/// laid in order, never a conflict, so ticking a box in an old copy ticks the/// box even when the newer text added a paragraph just above it (the owner's/// case, STALE, 21 Nov 2026).////// Lines are split on `\n`, so a last line with no line end matches the same/// line with one.pub fn merge(base: &str, mine: &str, theirs: &str) -> Merged {    if mine == theirs || theirs == base {        return Merged { text: mine.to_string(), both_kept: false };    }    if mine == base {        return Merged { text: theirs.to_string(), both_kept: false };    }    let (b, m, t): (Vec<&str>, Vec<&str>, Vec<&str>) = (base.split('\n').collect(), mine.split('\n').collect(), theirs.split('\n').collect());    let (Some(mine_hunks), Some(theirs_hunks)) = (hunks(&b, &m), hunks(&b, &t)) else {        return whole(&m, &t);    };    let mut all: Vec<(Side, &Hunk)> = mine_hunks.iter().map(|h| (Side::Mine, h)).chain(theirs_hunks.iter().map(|h| (Side::Theirs, h))).collect();    all.sort_by_key(|(side, h)| (h.start, h.end, *side == Side::Theirs));    let mut out: Vec<&str> = Vec::new();    let mut both_kept = false;    let (mut at, mut i) = (0, 0);    while i < all.len() {        let (group_start, mut group_end) = (all[i].1.start, all[i].1.end);        let mut j = i + 1;        while j < all.len() && (all[j].1.start < group_end || (group_start == group_end && all[j].1.start == group_start && all[j].1.end == group_start)) {            group_end = group_end.max(all[j].1.end);            j += 1;        }        let group = &all[i..j];        out.extend_from_slice(&b[at..group_start]);        let version = |side: Side| -> Option<Vec<&str>> {            let own: Vec<&Hunk> = group.iter().filter(|(s, _)| *s == side).map(|(_, h)| *h).collect();            if own.is_empty() {                return None;            }            let mut lines = Vec::new();            let mut cursor = group_start;            for hunk in own {                lines.extend_from_slice(&b[cursor..hunk.start]);                lines.extend(hunk.lines.iter().copied());                cursor = hunk.end;            }            lines.extend_from_slice(&b[cursor..group_end]);            Some(lines)        };        match (version(Side::Mine), version(Side::Theirs)) {            (Some(lines), None) | (None, Some(lines)) => out.extend(lines),            (Some(mc), Some(tc)) if mc == tc => out.extend(mc),            (Some(mc), Some(tc)) => {                both_kept = true;                let held: std::collections::BTreeSet<&str> = mc.iter().copied().collect();                out.extend(mc.iter().copied());                out.extend(tc.into_iter().filter(|line| !held.contains(line)));            }            (None, None) => out.extend_from_slice(&b[group_start..group_end]),        }        at = group_end;        i = j;    }    out.extend_from_slice(&b[at..]);    Merged { text: out.join("\n"), both_kept }}/// Both texts kept whole: the writer's, then the other's lines it lacks.fn whole(m: &[&str], t: &[&str]) -> Merged {    let held: std::collections::BTreeSet<&str> = m.iter().copied().collect();    let mut out: Vec<&str> = m.to_vec();    if out.last() == Some(&"") {        out.pop();    }    out.extend(t.iter().copied().filter(|line| !held.contains(line) || line.is_empty()));    Merged { text: out.join("\n"), both_kept: true }}#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Side {    Mine,    Theirs,}/// `base[start..end]` replaced by `lines` (an insertion when `start == end`).#[derive(Debug)]struct Hunk<'a> {    start: usize,    end: usize,    lines: Vec<&'a str>,}/// The changes that make `other` of `base`. `None` when too long to match.fn hunks<'a>(base: &[&'a str], other: &[&'a str]) -> Option<Vec<Hunk<'a>>> {    let pairs = matched(base, other)?;    let mut out = Vec::new();    let (mut bi, mut oi) = (0, 0);    for (mb, mo) in pairs.into_iter().chain(std::iter::once((base.len(), other.len()))) {        if mb > bi || mo > oi {            out.push(Hunk { start: bi, end: mb, lines: other[oi..mo].to_vec() });        }        bi = mb + 1;        oi = mo + 1;    }    Some(out)}/// The pairs of line indices `a` and `b` share in order: the common start and/// end, and a longest common run of lines between them.fn matched(a: &[&str], b: &[&str]) -> Option<Vec<(usize, usize)>> {    let head = a.iter().zip(b).take_while(|(x, y)| x == y).count();    let tail = a[head..].iter().rev().zip(b[head..].iter().rev()).take_while(|(x, y)| x == y).count();    let (am, bm) = (&a[head..a.len() - tail], &b[head..b.len() - tail]);    let (n, m) = (am.len(), bm.len());    if n.saturating_mul(m) > MOST_CELLS {        return None;    }    let mut longest = vec![0u32; (n + 1) * (m + 1)];    let at = |i: usize, j: usize| i * (m + 1) + j;    for i in (0..n).rev() {        for j in (0..m).rev() {            longest[at(i, j)] = if am[i] == bm[j] { longest[at(i + 1, j + 1)] + 1 } else { longest[at(i + 1, j)].max(longest[at(i, j + 1)]) };        }    }    let mut pairs: Vec<(usize, usize)> = (0..head).map(|k| (k, k)).collect();    let (mut i, mut j) = (0, 0);    while i < n && j < m {        if am[i] == bm[j] {            pairs.push((head + i, head + j));            i += 1;            j += 1;        } else if longest[at(i + 1, j)] >= longest[at(i, j + 1)] {            i += 1;        } else {            j += 1;        }    }    pairs.extend((0..tail).map(|k| (a.len() - tail + k, b.len() - tail + k)));    Some(pairs)}#[cfg(test)]mod tests {    use super::*;    const BASE: &str = "# Trip\nPack the bag\nBook the train\nCall Asha\n";    /// RULE: what only one side changed is taken from it — the owner's edit at the top and the assistant's rewrite lower down both stand.    #[test]    fn changes_to_different_lines_are_both_taken() {        let mine = "# Trip to Goa\nPack the bag\nBook the train\nCall Asha\n";        let theirs = "# Trip\nPack the bag\nBook the 7:10 train, seat 42\nCall Asha\nTake the charger\n";        let merged = merge(BASE, mine, theirs);        assert_eq!(merged.text, "# Trip to Goa\nPack the bag\nBook the 7:10 train, seat 42\nCall Asha\nTake the charger\n");        assert!(!merged.both_kept);    }    /// RULE: where both changed the same lines, both are kept, the writer's first — the newer text is never dropped.    #[test]    fn the_same_lines_changed_on_both_sides_are_both_kept() {        let mine = "# Trip\nPack the small bag\nBook the train\nCall Asha\n";        let theirs = "# Trip\nPack the big bag and the tent\nBook the train\nCall Asha\n";        let merged = merge(BASE, mine, theirs);        assert_eq!(merged.text, "# Trip\nPack the small bag\nPack the big bag and the tent\nBook the train\nCall Asha\n");        assert!(merged.both_kept);    }    /// RULE: the assistant rewrote the whole body twice and the writer typed one line into the old one: every word of both is in the result.    #[test]    fn a_whole_rewrite_against_a_small_edit_keeps_every_word() {        let theirs = "Goa, 3 to 7 December.\nTrain 7:10 from Dadar.\n";        let mine = "# Trip\nPack the bag\nBook the train\nCall Asha\nAsk about the dog\n";        let merged = merge(BASE, mine, theirs);        for line in mine.lines().chain(theirs.lines()).filter(|l| !BASE.contains(*l)) {            assert!(merged.text.contains(line), "{line:?} kept: {}", merged.text);        }        assert!(merged.text.contains("Ask about the dog") && merged.text.contains("Train 7:10 from Dadar."));    }    /// RULE: a line changed on one side beside the next line changed on the other is no clash.    #[test]    fn neighbouring_lines_changed_apart_are_both_taken() {        let merged = merge("Pack the bag\nBook the train\n", "Pack the bag and the charger\nBook the train\n", "Pack the bag\nBook the 7:10 train, seat 42\n");        assert_eq!(merged, Merged { text: "Pack the bag and the charger\nBook the 7:10 train, seat 42\n".into(), both_kept: false });    }    /// RULE: one side unchanged answers the other; equal sides answer once; text with no final line end merges whole.    #[test]    fn the_plain_cases() {        assert_eq!(merge(BASE, BASE, "x").text, "x");        assert_eq!(merge(BASE, "y", BASE).text, "y");        assert_eq!(merge(BASE, "z", "z"), Merged { text: "z".into(), both_kept: false });        let merged = merge("a\nb", "a\nb mine", "a\nb theirs");        assert_eq!(merged.text, "a\nb mine\nb theirs");        assert!(merged.both_kept);        assert_eq!(merge("a\n", "a\nmine", "a\n").text, "a\nmine");        assert_eq!(merge("", "mine\n", "theirs\n").text, "mine\ntheirs\n");    }    /// RULE (the owner's case, STALE, 21 Nov 2026): two boxes ticked in an old copy, while the newer text added a paragraph just above    /// the list and an item below it, tick the two boxes and nothing else: no list twice.    #[test]    fn ticking_boxes_in_an_old_copy_ticks_them_beside_lines_added_around_them() {        let base = "Weekend in Hampi\n\n- [ ] Book the bus\n- [ ] Guesthouse near the river\n- [ ] Ask about the boulders";        let theirs = "Weekend in Hampi\n\nLeave Friday after work.\n\n- [ ] Book the bus\n- [ ] Guesthouse near the river\n- [ ] Ask about the boulders\n- [ ] Sunrise at Matanga Hill";        let mine = "Weekend in Hampi\n\n- [x] Book the bus\n- [x] Guesthouse near the river\n- [ ] Ask about the boulders";        let merged = merge(base, mine, theirs);        assert_eq!(merged.text, "Weekend in Hampi\n\nLeave Friday after work.\n\n- [x] Book the bus\n- [x] Guesthouse near the river\n- [ ] Ask about the boulders\n- [ ] Sunrise at Matanga Hill");        assert!(!merged.both_kept);        // A line added just after a ticked one, and a tick just before an added one.        let theirs = base.replace("- [ ] Guesthouse", "- [ ] Bus leaves at 21:30\n- [ ] Guesthouse");        let mine = base.replace("[ ] Book", "[x] Book");        assert_eq!(merge(base, &mine, &theirs).text, theirs.replace("[ ] Book", "[x] Book"));        // A line one side took out and the other left.        let theirs = base.replace("\n- [ ] Guesthouse near the river", "");        assert_eq!(merge(base, &mine, &theirs).text, theirs.replace("[ ] Book", "[x] Book"));    }    /// RULE: lines both added at one place are all kept, the writer's first; any script, the text's own line ends.    #[test]    fn lines_both_added_at_one_place_are_all_kept_in_any_script() {        let base = "నమస్తే\n- [ ] పాలు\n";        let merged = merge(base, "నమస్తే\n- [x] పాలు\n- [ ] గుడ్లు\n", "నమస్తే\n- [ ] పాలు\n- [ ] రొట్టె\n");        assert_eq!(merged.text, "నమస్తే\n- [x] పాలు\n- [ ] గుడ్లు\n- [ ] రొట్టె\n");    }}