about summary refs log tree commit diff
path: root/library
diff options
context:
space:
mode:
authorMichael Goulet <michael@errs.io>2025-06-26 20:15:18 -0400
committerGitHub <noreply@github.com>2025-06-26 20:15:18 -0400
commit9820197e120ea6714a188903e38db53aefa76b57 (patch)
treed19ad7e3fa6ee7159ef176fa838336fdb635d828 /library
parent36cde678948400f2dcda71ed09e2072f093b63d5 (diff)
parente6c300892dce9202e4f21359129569536945dfea (diff)
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.
Diffstat (limited to 'library')
-rw-r--r--library/core/src/iter/adapters/intersperse.rs11
1 files changed, 10 insertions, 1 deletions
diff --git a/library/core/src/iter/adapters/intersperse.rs b/library/core/src/iter/adapters/intersperse.rs
index c97a59b614f..843479e2a27 100644
--- a/library/core/src/iter/adapters/intersperse.rs
+++ b/library/core/src/iter/adapters/intersperse.rs
@@ -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);
     }