Skip to content

Commit 306f0d0

Browse files
committed
Fix Skip::nth
1. Remove an unnecessary condition. 2. Avoid advancing after nth/next returns None.
1 parent 2963a6f commit 306f0d0

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/libcore/iter.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2039,14 +2039,17 @@ impl<I> Iterator for Skip<I> where I: Iterator {
20392039

20402040
#[inline]
20412041
fn nth(&mut self, n: usize) -> Option<I::Item> {
2042+
// Can't just add n + self.n due to overflow.
20422043
if self.n == 0 {
20432044
self.iter.nth(n)
2044-
} else if n == 0 {
2045-
self.next()
20462045
} else {
2047-
self.next();
2048-
// Recurse on the first case.
2049-
self.iter.nth(n-1)
2046+
let to_skip = self.n;
2047+
self.n = 0;
2048+
// nth(n) skips n+1
2049+
if self.iter.nth(to_skip-1).is_none() {
2050+
return None;
2051+
}
2052+
self.iter.nth(n)
20502053
}
20512054
}
20522055

0 commit comments

Comments
 (0)