Three-way merge of byte content. Given three versions of a file: - `base` — the common ancestor (A's original content) - `ours` — our modified version (A' after revise) - `theirs` — their modified version (A+B content after B was applied to A) This computes B's delta via `diff(base, theirs)`, then applies that delta to `ours`. For each region: - **Equal** (B didn't change): keep whatever `
(base: &[u8], ours: &[u8], theirs: &[u8])
| 608 | /// assert_eq!(merged, b"line alpha revised\nline beta\n"); |
| 609 | /// ``` |
| 610 | pub fn merge_text(base: &[u8], ours: &[u8], theirs: &[u8]) -> Result<Vec<u8>, String> { |
| 611 | let base_lines: Vec<Line> = Line::from_bytes(base); |
| 612 | let ours_lines: Vec<Line> = Line::from_bytes(ours); |
| 613 | let theirs_lines: Vec<Line> = Line::from_bytes(theirs); |
| 614 | |
| 615 | // What each side changed relative to the common base (diff3). |
| 616 | let a_delta = diff(&base_lines, &ours_lines, Algorithm::Myers); |
| 617 | let b_delta = diff(&base_lines, &theirs_lines, Algorithm::Myers); |
| 618 | |
| 619 | /// How `ours` renders one base region. |
| 620 | #[derive(Default)] |
| 621 | struct OursRender { |
| 622 | /// ours line index for each unchanged base line. |
| 623 | kept: Vec<Option<usize>>, |
| 624 | /// ours replacement line ranges for base lines ours changed |
| 625 | /// (delete = empty replacement). |
| 626 | changed: Vec<Option<(usize, usize)>>, |
| 627 | /// lines ours inserted at a base position (emit when the walk passes). |
| 628 | inserted: Vec<Vec<usize>>, |
| 629 | } |
| 630 | |
| 631 | let mut mapping = OursRender { |
| 632 | kept: vec![None; base_lines.len()], |
| 633 | changed: vec![None; base_lines.len()], |
| 634 | inserted: vec![Vec::new(); base_lines.len() + 1], |
| 635 | }; |
| 636 | for op in a_delta.ops() { |
| 637 | match op { |
| 638 | DiffOp::Equal { |
| 639 | old_pos, |
| 640 | new_pos, |
| 641 | len, |
| 642 | .. |
| 643 | } => { |
| 644 | for i in 0..*len { |
| 645 | mapping.kept[*old_pos + i] = Some(*new_pos + i); |
| 646 | } |
| 647 | } |
| 648 | DiffOp::Insert { |
| 649 | old_pos, |
| 650 | new_pos, |
| 651 | len, |
| 652 | } => { |
| 653 | for i in 0..*len { |
| 654 | mapping.inserted[*old_pos].push(*new_pos + i); |
| 655 | } |
| 656 | } |
| 657 | DiffOp::Delete { old_pos, len, .. } => { |
| 658 | for i in 0..*len { |
| 659 | mapping.changed[*old_pos + i] = Some((ours_lines.len(), 0)); |
| 660 | } |
| 661 | } |
| 662 | DiffOp::Replace { |
| 663 | old_pos, |
| 664 | old_len, |
| 665 | new_pos, |
| 666 | new_len, |
| 667 | } => { |