Skip to content

Commit

Permalink
Auto merge of #47772 - arthurprs:iter-position-bounds-check, r=dtolnay
Browse files Browse the repository at this point in the history
Use the slice length to hint the optimizer about iter.position result

Using the len of the iterator doesn't give the same result.
That's also why we can't generalize it to all TrustedLen iterators.

Problem demo: https://godbolt.org/g/MXg2ae
Fix demo: https://godbolt.org/g/P8q5aZ

Second attempt of #47333
Third attempt of #45501
Fixes #45964
  • Loading branch information
bors committed Jan 28, 2018
2 parents 7046a40 + 4f7109a commit 0119b44
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1245,7 +1245,8 @@ macro_rules! iterator {
P: FnMut(Self::Item) -> bool,
{
// The addition might panic on overflow
let n = self.len();
// Use the len of the slice to hint optimizer to remove result index bounds check.
let n = make_slice!(self.ptr, self.end).len();
self.try_fold(0, move |i, x| {
if predicate(x) { Err(i) }
else { Ok(i + 1) }
Expand All @@ -1263,7 +1264,8 @@ macro_rules! iterator {
{
// No need for an overflow check here, because `ExactSizeIterator`
// implies that the number of elements fits into a `usize`.
let n = self.len();
// Use the len of the slice to hint optimizer to remove result index bounds check.
let n = make_slice!(self.ptr, self.end).len();
self.try_rfold(n, move |i, x| {
let i = i - 1;
if predicate(x) { Err(i) }
Expand Down

0 comments on commit 0119b44

Please sign in to comment.