Re: [PATCH] rust: transmute: use split_at_checked() and split_at_mut_checked()

From: Alexandre Courbot

Date: Tue Mar 10 2026 - 09:57:22 EST


On Tue Mar 10, 2026 at 6:57 PM JST, Albab Hasan wrote:
> Replace manual bounds checking followed by split_at() and split_at_mut()
> calls with the checked variants split_at_checked() and
> split_at_mut_checked(), which return None instead of panicking on
> out-of-bounds indices.
>
> These methods were stabilized in Rust 1.80.0, which is the current
> minimum supported Rust version for the kernel.
>
> This simplifies from_bytes_prefix(), from_bytes_mut_prefix(), and
> from_bytes_copy_prefix() by removing the explicit bounds checks and
> panic-avoidance comments that are no longer needed.
>
> Signed-off-by: Albab Hasan <albabhasan276@xxxxxxxxx>
> ---
> rust/kernel/transmute.rs | 33 ++++++---------------------------
> 1 file changed, 6 insertions(+), 27 deletions(-)
>
> diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
> index 5711580c9f9b..643b19406a24 100644
> --- a/rust/kernel/transmute.rs
> +++ b/rust/kernel/transmute.rs
> @@ -67,16 +67,9 @@ fn from_bytes_prefix(bytes: &[u8]) -> Option<(&Self, &[u8])>
> where
> Self: Sized,
> {
> - if bytes.len() < size_of::<Self>() {
> - None
> - } else {
> - // PANIC: We checked that `bytes.len() >= size_of::<Self>`, thus `split_at` cannot
> - // panic.
> - // TODO: replace with `split_at_checked` once the MSRV is >= 1.80.
> - let (prefix, remainder) = bytes.split_at(size_of::<Self>());
> + let (prefix, remainder) = bytes.split_at_checked(size_of::<Self>())?;
>
> - Self::from_bytes(prefix).map(|s| (s, remainder))
> - }
> + Self::from_bytes(prefix).map(|s| (s, remainder))

Or as a single expression:

bytes
.split_at_checked(size_of::<Self>())
.and_then(|(prefix, remainder)| Some((Self::from_bytes(prefix)?, remainder)))