Skip to content

Commit

Permalink
Simplify Skip::nth and Skip::last implementations
Browse files Browse the repository at this point in the history
The main improvement is to make `last` no longer recursive.
  • Loading branch information
ollie27 committed Jan 28, 2020
1 parent 80a65bc commit 84f3356
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions src/libcore/iter/adapters/mod.rs
Expand Up @@ -1801,17 +1801,15 @@ where
#[inline]
fn nth(&mut self, n: usize) -> Option<I::Item> {
// Can't just add n + self.n due to overflow.
if self.n == 0 {
self.iter.nth(n)
} else {
if self.n > 0 {
let to_skip = self.n;
self.n = 0;
// nth(n) skips n+1
if self.iter.nth(to_skip - 1).is_none() {
return None;
}
self.iter.nth(n)
}
self.iter.nth(n)
}

#[inline]
Expand All @@ -1827,17 +1825,13 @@ where

#[inline]
fn last(mut self) -> Option<I::Item> {
if self.n == 0 {
self.iter.last()
} else {
let next = self.next();
if next.is_some() {
// recurse. n should be 0.
self.last().or(next)
} else {
None
if self.n > 0 {
// nth(n) skips n+1
if self.iter.nth(self.n - 1).is_none() {
return None;
}
}
self.iter.last()
}

#[inline]
Expand Down

0 comments on commit 84f3356

Please sign in to comment.