Skip to content

Specialize StepBy::nth #47552

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

Merged
merged 6 commits into from
Jan 31, 2018
Merged
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions src/libcore/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,18 @@ impl<I> Iterator for StepBy<I> where I: Iterator {
(f(inner_hint.0), inner_hint.1.map(f))
}
}

#[inline]
fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
if self.first_take {
if n == 0 {
self.first_take = false;
return self.iter.next()
}
n -= 1;
}
self.iter.nth(n * self.step)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good change! ❤️

I think that this needs to handle overflow in the multiplication, though, since I could write (0u64..).step_by(0x10000).nth(0x10000) on a 32-bit machine, for example.

Also, tests?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests are a good call, I found 2 off-by-ones while implementing them.

I added overflow behaviour, but it is pretty weighty. While I think that it shouldn't influence normal execution due to intrinsics::likely and branch prediction, I do think that it is pretty complicated code, which doesn't really add too much value. Anyway, now that it exists, I don't mind keeping it :)

}
}

// StepBy can only make the iterator shorter, so the len will still fit.
Expand Down