Re: [PATCH 1/2] rust: add functions and traits for lossless integer conversions

From: Gary Guo

Date: Mon Jul 27 2026 - 06:37:14 EST


On Mon Jul 27, 2026 at 11:15 AM BST, Alexandre Courbot wrote:
> The core library's `From` implementations do not cover conversions that
> are not portable or future-proof. For instance, even though it is safe
> today, `From<usize>` is not implemented for `u64` because of the
> possibility of supporting larger-than-64bit architectures in the future.
>
> However, the kernel supports a narrower set of architectures, with a
> considerable amount of code that is architecture-specific. This makes it
> helpful and desirable to provide more infallible conversions, lest we
> need to rely on the `as` keyword and carry the risk of silently losing
> data.
>
> Thus, introduce a new module `num::casts` that provides safe const
> functions performing more conversions allowed by the build target, as
> well as `FromSafeCast` and `IntoSafeCast` traits that are just
> extensions of `From` and `Into` to conversions that are known to be
> lossless.

I'm okay with having u32 -> usize casts and usize -> u64 casts, but having
usize -> u32 and u64 -> usize casts like this series do is worrying as it can be
misused from drivers that are supposed to be supporting multiple platforms or
core subsystems.

Pointer-size dependent drivers that need these casts should define them locally.

Best,
Gary

>
> Suggested-by: Danilo Krummrich <dakr@xxxxxxxxxx>
> Link: https://lore.kernel.org/rust-for-linux/DDK4KADWJHMG.1FUPL3SDR26XF@xxxxxxxxxx/
> Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
> ---
> rust/kernel/num.rs | 3 +
> rust/kernel/num/casts.rs | 248 +++++++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 251 insertions(+)