From aec1f2aefb15fc874fcf641eddcaac658f2441bb Mon Sep 17 00:00:00 2001 From: Waffle Lapkin Date: Mon, 6 Jul 2026 20:51:32 +0200 Subject: [PATCH] simplify `slice::Iter[Mut]::next_chunk` implementation I verified that this doesn't pessimize codegen using the example from the PR that inroduced the optimization of `next_chunk` (# 149131): ```rust #![feature(iter_next_chunk)] #[no_mangle] pub fn simd_sum_slow(arr: &[u32]) -> u32 { const STEP_SIZE: usize = 16; let mut result = [0; STEP_SIZE]; let mut iter = arr.iter(); while let Ok(c) = iter.next_chunk::() { for (&n, r) in c.iter().zip(result.iter_mut()) { *r += n; } } result.iter().sum() } ``` I compiled this example with ```shell ./build/host/stage1/bin/rustc t.rs --emit=asm -O --crate-type=lib ``` Before and after this change; the only difference is the choice of the jump instruction, which I think shouldn't make any difference: ```diff 28,29c28,29 < cmpq $64, %rsi < jae .LBB0_2 --- > cmpq $60, %rsi > ja .LBB0_2 ``` --- library/core/src/slice/iter/macros.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/library/core/src/slice/iter/macros.rs b/library/core/src/slice/iter/macros.rs index 1c8a4d5ba3c..6f0f7aa7404 100644 --- a/library/core/src/slice/iter/macros.rs +++ b/library/core/src/slice/iter/macros.rs @@ -192,25 +192,20 @@ macro_rules! iterator { } fn next_chunk(&mut self) -> Result<[$elem; N], crate::array::IntoIter<$elem, N>> { - if T::IS_ZST { + if T::IS_ZST || len!(self) < N { return crate::array::iter_next_chunk(self); } - let len = len!(self); - if len >= N { - // SAFETY: we are just getting an array of [T; N] and moving the pointer over a little - let r = unsafe { self.post_inc_start(N).cast_array().$into_ref() } - .$array_ref(); // must convert &[T; N] to [&T; N] + + // SAFETY: the check above ensures len >= N + unsafe { + let r = self + .post_inc_start(N) + .cast_array() // NonNull -> NonNull<[T; N]> + // SAFETY: post_inc_start(N) insures we don't return overlapping `&mut`s + .$into_ref() // NonNull<[T; N]> -> &{mut} [T; N] + .$array_ref(); // must convert &{mut} [T; N] to [&{mut} T; N] + Ok(r) - } else { - // cant use $array_ref because theres no builtin for &mut [MU; N] -> [&mut MU; N] - // cant use copy_nonoverlapping as the $elem is of type &{mut} T instead of T - let mut a = [const { crate::mem::MaybeUninit::<$elem>::uninit() }; N]; - for into in (&mut a).into_iter().take(len) { - // SAFETY: take(n) limits to remainder (slice produces worse codegen) - into.write(unsafe { self.post_inc_start(1).$into_ref() }); - } - // SAFETY: we just initialized elements 0..len - unsafe { Err(crate::array::IntoIter::new_unchecked(a, 0..len)) } } }