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

"Danilo Krummrich" <[email protected]> Mon, 27 Jul 2026 13:19:35 +0200
Newsgroups dev.linux.lists.nova-gpu,org.kernel.vger.linux-kernel,org.kernel.vger.rust-for-linux
Message-ID <[email protected]>
On Mon Jul 27, 2026 at 12:28 PM CEST, Gary Guo wrote:
> 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 havin=
g
> 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 platform=
s or
> core subsystems.
>
> Pointer-size dependent drivers that need these casts should define them l=
ocally.

I also raised this concern in the context of [1]. On the other hand, it is =
not
as if this can "randomly" break with exotic or niche kernel configs; 32bit =
vs.
64bit compile tests are well covered.

So, as long as we are explicit about it, I think it should be fine. Maybe w=
e can
export the non-portable ones with a different name?

[1] https://lore.kernel.org/driver-core/[email protected]=
rg/