diff: simplify context line extraction by using DoubleEndedIterator

This commit is contained in:
Yuya Nishihara 2024-06-28 23:53:53 +09:00
parent 3d458c3e58
commit 318f594291

View file

@ -775,18 +775,12 @@ fn unified_diff_hunks<'content>(
for hunk in diff.hunks() { for hunk in diff.hunks() {
match hunk { match hunk {
DiffHunk::Matching(content) => { DiffHunk::Matching(content) => {
let lines = content.split_inclusive(|b| *b == b'\n').collect_vec(); let mut lines = content.split_inclusive(|b| *b == b'\n').fuse();
// Number of context lines to print after the previous non-matching hunk. if show_context_after {
let num_after_lines = lines.len().min(if show_context_after { current_hunk.extend_context_lines(lines.by_ref().take(num_context_lines));
num_context_lines }
} else { let before_lines = lines.by_ref().rev().take(num_context_lines).collect_vec();
0 let num_skip_lines = lines.count();
});
current_hunk.extend_context_lines(lines.iter().copied().take(num_after_lines));
let num_skip_lines = lines
.len()
.saturating_sub(num_after_lines)
.saturating_sub(num_context_lines);
if num_skip_lines > 0 { if num_skip_lines > 0 {
let left_start = current_hunk.left_line_range.end + num_skip_lines; let left_start = current_hunk.left_line_range.end + num_skip_lines;
let right_start = current_hunk.right_line_range.end + num_skip_lines; let right_start = current_hunk.right_line_range.end + num_skip_lines;
@ -799,9 +793,7 @@ fn unified_diff_hunks<'content>(
lines: vec![], lines: vec![],
}; };
} }
current_hunk.extend_context_lines( current_hunk.extend_context_lines(before_lines.into_iter().rev());
lines.iter().copied().skip(num_after_lines + num_skip_lines),
);
} }
DiffHunk::Different(content) => { DiffHunk::Different(content) => {
show_context_after = true; show_context_after = true;