The engine's hunks-from-changed-lines core, as a free function (the CLI's `impl Diff` carries a thin wrapper). Group numbered changed lines into diff hunks with true file offsets. `changed` must be in file order. Changes separated by more than `2 * context` unchanged lines become separate hunks; closer changes merge with the gap emitted as context. Context line content is taken from `before_lines
(
changed: &[NumberedLine],
before_lines: Option<&[Vec<u8>]>,
context: usize,
)
| 816 | /// at boundary `p` is `@@ -p,0 +n,k @@`, a pure deletion is |
| 817 | /// `@@ -l,k +p,0 @@`, and context lines count toward both sides. |
| 818 | pub fn hunks_from_changed_lines( |
| 819 | changed: &[NumberedLine], |
| 820 | before_lines: Option<&[Vec<u8>]>, |
| 821 | context: usize, |
| 822 | ) -> Vec<DiffHunk> { |
| 823 | let mut hunks = Vec::new(); |
| 824 | if changed.is_empty() { |
| 825 | return hunks; |
| 826 | } |
| 827 | |
| 828 | let old_len = before_lines.map(|l| l.len()).unwrap_or(0); |
| 829 | let ctx = if before_lines.is_some() { context } else { 0 }; |
| 830 | let merge_gap = 2 * ctx as isize; |
| 831 | |
| 832 | // 1. Group into runs of nearby changes, measured in old-file |
| 833 | // coordinates. |
| 834 | let mut runs: Vec<(usize, usize)> = Vec::new(); |
| 835 | let mut run_start = 0usize; |
| 836 | let mut run_hi = changed[0].old_pos(); |
| 837 | for (i, nl) in changed.iter().enumerate().skip(1) { |
| 838 | let lo = nl.old_pos(); |
| 839 | // Unchanged lines between the run and this change. An addition |
| 840 | // sits at a boundary, so the gap is measured from the boundary |
| 841 | // itself; a removal occupies a line, hence the extra -1. |
| 842 | let gap = match nl.line.status { |
| 843 | LineStatus::Removed => lo as isize - run_hi as isize - 1, |
| 844 | _ => lo as isize - run_hi as isize, |
| 845 | }; |
| 846 | if gap > merge_gap { |
| 847 | runs.push((run_start, i)); |
| 848 | run_start = i; |
| 849 | } |
| 850 | run_hi = run_hi.max(nl.old_pos()); |
| 851 | } |
| 852 | runs.push((run_start, changed.len())); |
| 853 | |
| 854 | // 2. Emit one hunk per run. |
| 855 | for (start, end) in runs { |
| 856 | let lines = &changed[start..end]; |
| 857 | |
| 858 | let removed_count = lines.iter().filter(|l| l.line.is_removed()).count(); |
| 859 | let added_count = lines.len() - removed_count; |
| 860 | |
| 861 | let old_lo = lines.iter().map(|l| l.old_pos()).min().unwrap_or(0); |
| 862 | let old_hi = lines.iter().map(|l| l.old_pos()).max().unwrap_or(0); |
| 863 | let new_lo = lines.iter().map(|l| l.new_pos()).min().unwrap_or(0); |
| 864 | |
| 865 | // Old-file range covered by the hunk, including context. |
| 866 | let (old_start, old_end, old_count) = if removed_count > 0 { |
| 867 | let s = old_lo.saturating_sub(ctx).max(1); |
| 868 | let e = if ctx > 0 { |
| 869 | old_hi.saturating_add(ctx).min(old_len) |
| 870 | } else { |
| 871 | old_hi |
| 872 | }; |
| 873 | let e = e.max(s); |
| 874 | (s, e, e - s + 1) |
| 875 | } else { |