files: replace Vec + index access with iterator in DiffLineIterator

This commit is contained in:
Yuya Nishihara 2024-08-14 14:12:56 +09:00
parent 54f5c01eae
commit f85792288f

View file

@ -16,6 +16,7 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fmt::{Debug, Error, Formatter}; use std::fmt::{Debug, Error, Formatter};
use std::{iter, vec};
use crate::diff; use crate::diff;
use crate::diff::{Diff, DiffHunk}; use crate::diff::{Diff, DiffHunk};
@ -50,8 +51,7 @@ pub fn diff<'a>(left: &'a [u8], right: &'a [u8]) -> DiffLineIterator<'a> {
} }
pub struct DiffLineIterator<'a> { pub struct DiffLineIterator<'a> {
diff_hunks: Vec<DiffHunk<'a>>, diff_hunks: iter::Fuse<vec::IntoIter<DiffHunk<'a>>>,
current_pos: usize,
current_line: DiffLine<'a>, current_line: DiffLine<'a>,
queued_lines: VecDeque<DiffLine<'a>>, queued_lines: VecDeque<DiffLine<'a>>,
} }
@ -66,8 +66,7 @@ impl<'a> DiffLineIterator<'a> {
hunks: vec![], hunks: vec![],
}; };
DiffLineIterator { DiffLineIterator {
diff_hunks, diff_hunks: diff_hunks.into_iter().fuse(),
current_pos: 0,
current_line, current_line,
queued_lines: VecDeque::new(), queued_lines: VecDeque::new(),
} }
@ -80,10 +79,11 @@ impl<'a> Iterator for DiffLineIterator<'a> {
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
// TODO: Should we attempt to interpret as utf-8 and otherwise break only at // TODO: Should we attempt to interpret as utf-8 and otherwise break only at
// newlines? // newlines?
while self.current_pos < self.diff_hunks.len() && self.queued_lines.is_empty() { while self.queued_lines.is_empty() {
let hunk = &self.diff_hunks[self.current_pos]; let Some(hunk) = self.diff_hunks.next() else {
self.current_pos += 1; break;
match hunk { };
match &hunk {
DiffHunk::Matching(text) => { DiffHunk::Matching(text) => {
let lines = text.split_inclusive(|b| *b == b'\n'); let lines = text.split_inclusive(|b| *b == b'\n');
for line in lines { for line in lines {