From ee7dfce02db695b02803f5eb1a0b9309eb735a84 Mon Sep 17 00:00:00 2001 From: Tim Vermeulen Date: Wed, 7 Oct 2020 18:52:35 +0200 Subject: [PATCH] Revert implementing `Iterator::nth[_back]` in terms of `advance_by[_back]` --- library/core/src/iter/traits/double_ended.rs | 11 ++++++++--- library/core/src/iter/traits/iterator.rs | 11 ++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index 16bee0e2eee18..f7d09c23de023 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -174,9 +174,14 @@ pub trait DoubleEndedIterator: Iterator { /// ``` #[inline] #[stable(feature = "iter_nth_back", since = "1.37.0")] - fn nth_back(&mut self, n: usize) -> Option { - self.advance_back_by(n).ok()?; - self.next_back() + fn nth_back(&mut self, mut n: usize) -> Option { + for x in self.rev() { + if n == 0 { + return Some(x); + } + n -= 1; + } + None } /// This is the reverse version of [`Iterator::try_fold()`]: it takes diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 813afcc0ec6e4..b2e789adaf54a 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -363,9 +363,14 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn nth(&mut self, n: usize) -> Option { - self.advance_by(n).ok()?; - self.next() + fn nth(&mut self, mut n: usize) -> Option { + while let Some(x) = self.next() { + if n == 0 { + return Some(x); + } + n -= 1; + } + None } /// Creates an iterator starting at the same point, but stepping by