Skip to contentSkip to conversation

rust: add functions and traits for lossless integer conversions

RFC PATCH Superseded Alexandre Courbot 1 participant 1 message Nov 4, 2025

Subsystems (2)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

RFC PATCH 1/1 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 to support 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.

---
This got already reviewed in the context of Nova [1][2][3] and I am thinking of merging it soon there, but since it was suggested that this would also be useful in the kernel crate, I am sending this RFC for more visibility.

It might be a bit tight to get this in shape for 6.19 (thus the first merge into Nova as we have a lot of incoming code that benefits from this), but maybe we can consider the following cycle.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
[3] https://lore.kernel.org/rust-for-linux/[email protected]/

---
 rust/kernel/lib.rs       |   1 +
 rust/kernel/num.rs       |   6 ++
 rust/kernel/num/casts.rs | 245 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 252 insertions(+)
rust/kernel/lib.rs +1 -0
index 3dd7bebe7888..235d0d8b1eff 100644
@@ -109,6 +109,7 @@
 pub mod mm;
 #[cfg(CONFIG_NET)]
 pub mod net;
+pub mod num;
 pub mod of;
 #[cfg(CONFIG_PM_OPP)]
 pub mod opp;
rust/kernel/num.rs new file +6 -0
new file mode 100644
index 000000000000..3de1decb7779
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Numerical features for the kernel.
+
+pub mod casts;
+pub use casts::*;
rust/kernel/num/casts.rs new file +245 -0

245 lines not on this page · raw message

---
base-commit: 6553a8f168fb7941ae73d39eccac64f3a2b9b399
change-id: 20251104-as_casts-6a8882ac0192

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>