1 Commits
Author SHA1 Message Date
Alexandre Courbot 47f27155f1 rust: add functions and traits for lossless integer conversions
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
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.

Some conversions are architecture-specific: for instance, converting a
`u64` to a `usize` is only lossless on 64-bit platforms. These
conversions are made available via a dedicated `arch` sub-module.

Suggested-by: Danilo Krummrich <[email protected]>
Link: https://lore.kernel.org/rust-for-linux/[email protected]/
Signed-off-by: Alexandre Courbot <[email protected]>
Reviewed-by: Danilo Krummrich <[email protected]>
Link: https://patch.msgid.link/[email protected]
[ Added a few more intra-doc links. - Miguel ]
Signed-off-by: Miguel Ojeda <[email protected]>
2026-08-13 13:41:28 +02:00