Skip to content

Commit 06c0e54

Browse files
author
Markus Westerlind
committed
Less mutation
1 parent 408fa92 commit 06c0e54

File tree

1 file changed

+19
-26
lines changed

1 file changed

+19
-26
lines changed

diffus/src/lcs.rs

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,32 +28,25 @@ where
2828
I: DoubleEndedIterator<Item = T>,
2929
J: DoubleEndedIterator<Item = T>,
3030
{
31-
let mut prefix_eq = 0;
32-
let mut suffix_eq = 0;
33-
{
34-
let mut x_iter = x();
35-
let mut y_iter = y();
36-
// We must not compute an overlapping `prefix_eq` and `suffix_eq` so we only check the suffix
37-
// if there is something that is not the same in the middle of the iterators
38-
let mut check_suffix = false;
39-
loop {
40-
match (x_iter.next(), y_iter.next()) {
41-
(Some(x), Some(y)) if x.same(&y) => prefix_eq += 1,
42-
(Some(_), Some(_)) => {
43-
check_suffix = true;
44-
break;
45-
}
46-
(None, _) | (_, None) => break,
47-
}
48-
}
49-
if check_suffix {
50-
suffix_eq = x_iter
51-
.rev()
52-
.zip(y_iter.rev())
53-
.take_while(|(x, y)| x.same(y))
54-
.count();
55-
}
56-
}
31+
let mut x_iter = x();
32+
let mut y_iter = y();
33+
let prefix_eq = x_iter
34+
.by_ref()
35+
.zip(y_iter.by_ref())
36+
.take_while(|(x, y)| x.same(y))
37+
.count();
38+
// Only check the suffix if we did not consume the entirety of either of the iterators
39+
// (If one of them are consumed, we would double count elements)
40+
let check_suffix = x_len.min(y_len) != prefix_eq;
41+
let suffix_eq = if check_suffix {
42+
x_iter
43+
.rev()
44+
.zip(y_iter.rev())
45+
.take_while(|(x, y)| x.same(y))
46+
.count()
47+
} else {
48+
0
49+
};
5750

5851
let width = x_len.saturating_sub(prefix_eq + suffix_eq) + 1;
5952
let height = y_len.saturating_sub(prefix_eq + suffix_eq) + 1;

0 commit comments

Comments
 (0)