Re: [PATCH 1/2] rust: add functions and traits for lossless integer conversions
"Gary Guo" <[email protected]> Mon, 27 Jul 2026 11:28:04 +0100
| 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 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 c= an 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 loc= ally. Best, Gary > > Suggested-by: Danilo Krummrich <[email protected]> > Link: https://lore.kernel.org/rust-for-linux/DDK4KADWJHMG.1FUPL3SDR26XF@k= ernel.org/ > Signed-off-by: Alexandre Courbot <[email protected]> > --- > rust/kernel/num.rs | 3 + > rust/kernel/num/casts.rs | 248 +++++++++++++++++++++++++++++++++++++++++= ++++++ > 2 files changed, 251 insertions(+)