Skip to content

Commit

Permalink
Rollup merge of rust-lang#68597 - ollie27:skip_nth_last, r=Amanieu
Browse files Browse the repository at this point in the history
Simplify `Skip::nth` and `Skip::last` implementations

The main improvement is to make `last` no longer recursive.
  • Loading branch information
Dylan-DPC authored Feb 17, 2020
2 parents 3747a48 + 84f3356 commit 034b334
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions src/libcore/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1890,17 +1890,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 @@ -1916,17 +1914,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 034b334

Please sign in to comment.