Skip to content

Commit 0119b44

Browse files
committed
Auto merge of #47772 - arthurprs:iter-position-bounds-check, r=dtolnay
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
2 parents 7046a40 + 4f7109a commit 0119b44

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/libcore/slice/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1245,7 +1245,8 @@ macro_rules! iterator {
12451245
P: FnMut(Self::Item) -> bool,
12461246
{
12471247
// The addition might panic on overflow
1248-
let n = self.len();
1248+
// Use the len of the slice to hint optimizer to remove result index bounds check.
1249+
let n = make_slice!(self.ptr, self.end).len();
12491250
self.try_fold(0, move |i, x| {
12501251
if predicate(x) { Err(i) }
12511252
else { Ok(i + 1) }
@@ -1263,7 +1264,8 @@ macro_rules! iterator {
12631264
{
12641265
// No need for an overflow check here, because `ExactSizeIterator`
12651266
// implies that the number of elements fits into a `usize`.
1266-
let n = self.len();
1267+
// Use the len of the slice to hint optimizer to remove result index bounds check.
1268+
let n = make_slice!(self.ptr, self.end).len();
12671269
self.try_rfold(n, move |i, x| {
12681270
let i = i - 1;
12691271
if predicate(x) { Err(i) }

0 commit comments

Comments
 (0)