Skip to content

Commit d89e458

Browse files
committed
optimize slice::Iter::fold
1 parent cfb0f11 commit d89e458

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/core/src/slice/iter/macros.rs

+23
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,29 @@ macro_rules! iterator {
191191
self.next_back()
192192
}
193193

194+
#[inline]
195+
fn fold<B, F>(mut self, init: B, mut f: F) -> B
196+
where
197+
F: FnMut(B, Self::Item) -> B,
198+
{
199+
// Handling the 0-len case explicitly and then using a do-while style loop
200+
// helps the optimizer. See issue #106288
201+
if is_empty!(self) {
202+
return init;
203+
}
204+
let mut acc = init;
205+
// SAFETY: The 0-len case was handled above so one loop iteration is guaranteed.
206+
unsafe {
207+
loop {
208+
acc = f(acc, next_unchecked!(self));
209+
if is_empty!(self) {
210+
break;
211+
}
212+
}
213+
}
214+
acc
215+
}
216+
194217
// We override the default implementation, which uses `try_fold`,
195218
// because this simple implementation generates less LLVM IR and is
196219
// faster to compile.

0 commit comments

Comments
 (0)