Rollup merge of #142549 - the8472:intersperse-fold-tweak, r=tgross35

small iter.intersperse.fold() optimization

No need to call into fold when the first item is already None, this avoids some redundant work for empty iterators.

"But it uses Fuse" one might want to protest, but Fuse is specialized and may call into the inner iterator anyway.
This commit is contained in:
Michael Goulet 2025-06-26 20:15:18 -04:00 committed by GitHub
commit 9820197e12
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -223,7 +223,16 @@ where
{
let mut accum = init;
let first = if started { next_item.take() } else { iter.next() };
let first = if started {
next_item.take()
} else {
let n = iter.next();
// skip invoking fold() for empty iterators
if n.is_none() {
return accum;
}
n
};
if let Some(x) = first {
accum = f(accum, x);
}