Skip to content

Commit ee9a9f8

Browse files
committed
Auto merge of #124793 - scottmcm:simplify-as-chunks, r=Nilstrieb
Implement `as_chunks` with `split_at_unchecked` We were discussing various ways to do [this on Discord](https://discord.com/channels/273534239310479360/273541522815713281/1236946363120619521), and in the process I noticed that <https://rust.godbolt.org/z/1P16P37Go> is emitting a panic path inside `as_chunks`. It optimizes out in release, but we could just not do that in the first place. We're already doing unsafe code that depends on this value being calculated correctly, so might as well call `split_at_unchecked` instead of `split_at`.
2 parents 87293c9 + 49af347 commit ee9a9f8

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

library/core/src/slice/mod.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -1337,8 +1337,10 @@ impl<T> [T] {
13371337
#[must_use]
13381338
pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
13391339
assert!(N != 0, "chunk size must be non-zero");
1340-
let len = self.len() / N;
1341-
let (multiple_of_n, remainder) = self.split_at(len * N);
1340+
let len_rounded_down = self.len() / N * N;
1341+
// SAFETY: The rounded-down value is always the same or smaller than the
1342+
// original length, and thus must be in-bounds of the slice.
1343+
let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) };
13421344
// SAFETY: We already panicked for zero, and ensured by construction
13431345
// that the length of the subslice is a multiple of N.
13441346
let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
@@ -1487,8 +1489,10 @@ impl<T> [T] {
14871489
#[must_use]
14881490
pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
14891491
assert!(N != 0, "chunk size must be non-zero");
1490-
let len = self.len() / N;
1491-
let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1492+
let len_rounded_down = self.len() / N * N;
1493+
// SAFETY: The rounded-down value is always the same or smaller than the
1494+
// original length, and thus must be in-bounds of the slice.
1495+
let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) };
14921496
// SAFETY: We already panicked for zero, and ensured by construction
14931497
// that the length of the subslice is a multiple of N.
14941498
let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };

0 commit comments

Comments
 (0)