From 49af347653beb2ee3b9c83b1beb741b63b86f211 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Mon, 6 May 2024 01:04:27 -0700 Subject: [PATCH] Implement `as_chunks` with `split_at_unchecked` --- library/core/src/slice/mod.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index ed7bcec89b9f9..57526dcd00ca8 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -1337,8 +1337,10 @@ impl [T] { #[must_use] pub const fn as_chunks(&self) -> (&[[T; N]], &[T]) { assert!(N != 0, "chunk size must be non-zero"); - let len = self.len() / N; - let (multiple_of_n, remainder) = self.split_at(len * N); + let len_rounded_down = self.len() / N * N; + // SAFETY: The rounded-down value is always the same or smaller than the + // original length, and thus must be in-bounds of the slice. + let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) }; // SAFETY: We already panicked for zero, and ensured by construction // that the length of the subslice is a multiple of N. let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() }; @@ -1487,8 +1489,10 @@ impl [T] { #[must_use] pub const fn as_chunks_mut(&mut self) -> (&mut [[T; N]], &mut [T]) { assert!(N != 0, "chunk size must be non-zero"); - let len = self.len() / N; - let (multiple_of_n, remainder) = self.split_at_mut(len * N); + let len_rounded_down = self.len() / N * N; + // SAFETY: The rounded-down value is always the same or smaller than the + // original length, and thus must be in-bounds of the slice. + let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) }; // SAFETY: We already panicked for zero, and ensured by construction // that the length of the subslice is a multiple of N. let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };