Skip to content

Commit ee7dfce

Browse files
committed
Revert implementing Iterator::nth[_back] in terms of advance_by[_back]
1 parent 9fdaeb3 commit ee7dfce

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

library/core/src/iter/traits/double_ended.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,14 @@ pub trait DoubleEndedIterator: Iterator {
174174
/// ```
175175
#[inline]
176176
#[stable(feature = "iter_nth_back", since = "1.37.0")]
177-
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
178-
self.advance_back_by(n).ok()?;
179-
self.next_back()
177+
fn nth_back(&mut self, mut n: usize) -> Option<Self::Item> {
178+
for x in self.rev() {
179+
if n == 0 {
180+
return Some(x);
181+
}
182+
n -= 1;
183+
}
184+
None
180185
}
181186

182187
/// This is the reverse version of [`Iterator::try_fold()`]: it takes

library/core/src/iter/traits/iterator.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -363,9 +363,14 @@ pub trait Iterator {
363363
/// ```
364364
#[inline]
365365
#[stable(feature = "rust1", since = "1.0.0")]
366-
fn nth(&mut self, n: usize) -> Option<Self::Item> {
367-
self.advance_by(n).ok()?;
368-
self.next()
366+
fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
367+
while let Some(x) = self.next() {
368+
if n == 0 {
369+
return Some(x);
370+
}
371+
n -= 1;
372+
}
373+
None
369374
}
370375

371376
/// Creates an iterator starting at the same point, but stepping by

0 commit comments

Comments
 (0)