Re: [PATCH v4 02/16] rust: mem: add `transmute` with deferred size check
From: Alexandre Courbot
Date: Thu Sep 03 2026 - 07:55:56 EST
On Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
> diff --git a/rust/kernel/mem.rs b/rust/kernel/mem.rs
> new file mode 100644
> index 000000000000..958e43bbcc3a
> --- /dev/null
> +++ b/rust/kernel/mem.rs
> @@ -0,0 +1,99 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Basic utilities for dealing with memory, values, and types.
> +
> +use crate::prelude::*;
> +
> +/// Transmute between two types.
> +///
> +/// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this
> +/// cannot be proven by the compiler.
> +///
> +/// This is equivalent to Rust's `transmute_unchecked` intrinsics.
> +///
> +/// # Safety
> +///
> +/// All safety requirements of [`core::mem::transmute`] apply, plus that the size `Src` and `Dst`
> +/// must match.
> +///
> +/// # Example
nit: IIUC the convention is to always use the plural `Examples`.
> +///
> +/// This can be used when types are known to have the same size, but only at runtime.
> +/// ```no_run
> +/// # use core::any::TypeId;
> +/// fn to_u32<T: 'static>(v: T) -> Option<u32> {
> +/// if TypeId::of::<T>() != TypeId::of::<u32>() {
> +/// return None;
> +/// }
> +///
> +/// // `core::mem::transmute` won't work here.
> +/// // SAFETY: We've checked that `T` is u32!
> +/// Some(unsafe { kernel::mem::transmute_unchecked(v) })
> +/// }
> +///
> +/// to_u32(1u32);
Missing closing code block here - interestingly, without it this block
triggers a "function has unnecessary safety comment" warning.
With this,
Reviewed-by: Alexandre Courbot <acourbot@xxxxxxxxxx>