Skip to content

Commit 49af347

Browse files
committed
Implement as_chunks with split_at_unchecked
1 parent d287f3e commit 49af347

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)