Skip to content

Optimize &Iterator::nth #25471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/libcore/iter.rs
Original file line number Diff line number Diff line change
@@ -160,8 +160,8 @@ pub trait Iterator {
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
for x in self.by_ref() {
fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
for x in self {
if n == 0 { return Some(x) }
n -= 1;
}
@@ -636,7 +636,7 @@ pub trait Iterator {
fn all<F>(&mut self, mut f: F) -> bool where
Self: Sized, F: FnMut(Self::Item) -> bool
{
for x in self.by_ref() {
for x in self {
if !f(x) {
return false;
}
@@ -663,7 +663,7 @@ pub trait Iterator {
Self: Sized,
F: FnMut(Self::Item) -> bool
{
for x in self.by_ref() {
for x in self {
if f(x) {
return true;
}
@@ -688,7 +688,7 @@ pub trait Iterator {
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
for x in self.by_ref() {
for x in self {
if predicate(&x) { return Some(x) }
}
None
@@ -724,7 +724,7 @@ pub trait Iterator {
P: FnMut(Self::Item) -> bool,
{
// `enumerate` might overflow.
for (i, x) in self.by_ref().enumerate() {
for (i, x) in self.enumerate() {
if predicate(x) {
return Some(i);
}
@@ -1127,6 +1127,7 @@ impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) }
}

/// Conversion from an `Iterator`
14 changes: 14 additions & 0 deletions src/libcoretest/iter.rs
Original file line number Diff line number Diff line change
@@ -651,6 +651,20 @@ fn test_by_ref() {
assert_eq!(xs.next(), Some(5));
}

#[test]
fn test_by_ref_nth() {
let mut xs = 0..10;
let mut ys = 0..10;
let mut ysr = ys.by_ref();
loop {
match (xs.nth(2), ysr.nth(2)) {
(Some(x), Some(y)) => assert_eq!(x, y),
(None, None) => break,
_ => panic!("Both iterators should have finished at the same time."),
}
}
}

#[test]
fn test_rev() {
let xs = [2, 4, 6, 8, 10, 12, 14, 16];