Skip to content

Commit ef4b306

Browse files
committed
Auto merge of #89774 - the8472:inline-mut-iter-next, r=m-ou-se
inline next() on &mut Iterator impl In [#87431](https://github.com/rust-lang/rust/pull/87431/files#diff-79a6b417b85ecf4f1a4ef2235135fedf540199caf6e9e1d154ac6a413b40a757R132-R136) I found that `(&mut range).fold` doesn't optimize well because the default impl for for `fold` on `&mut Iterator` doesn't inline `next`. In that particular case it was worked around by using `try_fold` which takes a `&mut self` instead of `self`. Let's see if this can be fixed more broadly.
2 parents d7c97a0 + f1c588f commit ef4b306

File tree

2 files changed

+7
-13
lines changed

2 files changed

+7
-13
lines changed

library/core/src/array/iter.rs

+6-13
Original file line numberDiff line numberDiff line change
@@ -135,19 +135,12 @@ impl<T, const N: usize> Iterator for IntoIter<T, N> {
135135
Fold: FnMut(Acc, Self::Item) -> Acc,
136136
{
137137
let data = &mut self.data;
138-
// FIXME: This uses try_fold(&mut iter) instead of fold(iter) because the latter
139-
// would go through the blanket `impl Iterator for &mut I` implementation
140-
// which lacks inline annotations on its methods and adding those would be a larger
141-
// perturbation than using try_fold here.
142-
// Whether it would be beneficial to add those annotations should be investigated separately.
143-
(&mut self.alive)
144-
.try_fold::<_, _, Result<_, !>>(init, |acc, idx| {
145-
// SAFETY: idx is obtained by folding over the `alive` range, which implies the
146-
// value is currently considered alive but as the range is being consumed each value
147-
// we read here will only be read once and then considered dead.
148-
Ok(fold(acc, unsafe { data.get_unchecked(idx).assume_init_read() }))
149-
})
150-
.unwrap()
138+
self.alive.by_ref().fold(init, |acc, idx| {
139+
// SAFETY: idx is obtained by folding over the `alive` range, which implies the
140+
// value is currently considered alive but as the range is being consumed each value
141+
// we read here will only be read once and then considered dead.
142+
fold(acc, unsafe { data.get_unchecked(idx).assume_init_read() })
143+
})
151144
}
152145

153146
fn count(self) -> usize {

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

+1
Original file line numberDiff line numberDiff line change
@@ -3460,6 +3460,7 @@ pub trait Iterator {
34603460
#[stable(feature = "rust1", since = "1.0.0")]
34613461
impl<I: Iterator + ?Sized> Iterator for &mut I {
34623462
type Item = I::Item;
3463+
#[inline]
34633464
fn next(&mut self) -> Option<I::Item> {
34643465
(**self).next()
34653466
}

0 commit comments

Comments
 (0)