Skip to contentSkip to conversation

rust: num: bounded: mark __new as unsafe

PATCH Applied Hsiu Che Yu 3 participants 6 messages Dec 4, 2025 – Jan 7

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 rust: num: bounded: mark __new as unsafe

The Bounded::__new() constructor relies on the caller to ensure the value can be represented within N bits. Failing to uphold this requirement breaks the type invariant. Mark it as unsafe and document this requirement in a Safety section to make the contract explicit.

Update all call sites to use unsafe blocks and change their comments from INVARIANT: to SAFETY:, as they are now justifying unsafe operations rather than establishing type invariants.

---
Changes in v3:
- Add Link: tag (suggested by Alexandre Courbot)
- Remove empty line before Signed-off-by

Changes in v2:
- Mark Bounded::__new as unsafe and add Safety documentation
- Update all call sites with unsafe blocks and SAFETY comments

Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]/
Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

---
 rust/kernel/num/bounded.rs | 34 +++++++++++++++++++---------------
 1 file changed, 19 insertions(+), 15 deletions(-)
rust/kernel/num/bounded.rs +19 -15
index f870080af8ac..5838c84f8a53 100644
@@ -259,9 +259,9 @@ pub const fn new<const VALUE: $type>() -> Self {
                     assert!(fits_within!(VALUE, $type, N));
                 }
 
-                // INVARIANT: `fits_within` confirmed that `VALUE` can be represented within
+                // SAFETY: `fits_within` confirmed that `VALUE` can be represented within
                 // `N` bits.
-                Self::__new(VALUE)
+                unsafe { Self::__new(VALUE) }
             }
         }
         )*
@@ -284,7 +284,11 @@ impl<T, const N: u32> Bounded<T, N>
     ///
     /// The caller remains responsible for checking, either statically or dynamically, that `value`
     /// can be represented as a `T` using at most `N` bits.
-    const fn __new(value: T) -> Self {
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that `value` can be represented within `N` bits.
+    const unsafe fn __new(value: T) -> Self {
         // Enforce the type invariants.
         const {
             // `N` cannot be zero.
@@ -328,8 +332,8 @@ const fn __new(value: T) -> Self {
     /// ```
     pub fn try_new(value: T) -> Option<Self> {
         fits_within(value, N).then(|| {
-            // INVARIANT: `fits_within` confirmed that `value` can be represented within `N` bits.
-            Self::__new(value)
+            // SAFETY: `fits_within` confirmed that `value` can be represented within `N` bits.
+            unsafe { Self::__new(value) }
         })
     }
 
@@ -370,8 +374,8 @@ pub fn from_expr(expr: T) -> Self {
             "Requested value larger than maximal representable value."
         );
 
-        // INVARIANT: `fits_within` confirmed that `expr` can be represented within `N` bits.
-        Self::__new(expr)
+        // SAFETY: `fits_within` confirmed that `expr` can be represented within `N` bits.
+        unsafe { Self::__new(expr) }
     }
 
     /// Returns the wrapped value as the backing type.
@@ -410,9 +414,9 @@ pub const fn extend<const M: u32>(self) -> Bounded<T, M> {
             );
         }
 
-        // INVARIANT: The value did fit within `N` bits, so it will all the more fit within
+        // SAFETY: The value did fit within `N` bits, so it will all the more fit within
         // the larger `M` bits.
-        Bounded::__new(self.0)
+        unsafe { Bounded::__new(self.0) }
     }
 
     /// Attempts to shrink the number of bits usable for `self`.
@@ -466,9 +470,9 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `U` and `T` have the same sign, hence this conversion cannot fail.
         let value = unsafe { U::try_from(self.get()).unwrap_unchecked() };
 
-        // INVARIANT: Although the backing type has changed, the value is still represented within
+        // SAFETY: Although the backing type has changed, the value is still represented within
         // `N` bits, and with the same signedness.
-        Bounded::__new(value)
+        unsafe { Bounded::__new(value) }
     }
 }
 
@@ -944,9 +948,9 @@ impl<T, const N: u32> From<$type> for Bounded<T, N>
             Self: AtLeastXBits<{ <$type as Integer>::BITS as usize }>,
         {
             fn from(value: $type) -> Self {
-                // INVARIANT: The trait bound on `Self` guarantees that `N` bits is
+                // SAFETY: The trait bound on `Self` guarantees that `N` bits is
                 // enough to hold any value of the source type.
-                Self::__new(T::from(value))
+                unsafe { Self::__new(T::from(value)) }
             }
         }
         )*
@@ -1051,8 +1055,8 @@ impl<T, const N: u32> From<bool> for Bounded<T, N>
     T: Integer + From<bool>,
 {
     fn from(value: bool) -> Self {
-        // INVARIANT: A boolean can be represented using a single bit, and thus fits within any
+        // SAFETY: A boolean can be represented using a single bit, and thus fits within any
         // integer type for any `N` > 0.
-        Self::__new(T::from(value))
+        unsafe { Self::__new(T::from(value)) }
     }
 }
Signature · 1 line
2.43.0
maintainer Acked-by on v3 1/1
#1 lore raw
Quoted 9 lines · Hsiu Che Yu

The Bounded::__new() constructor relies on the caller to ensure the value can be represented within N bits. Failing to uphold this requirement breaks the type invariant. Mark it as unsafe and document this requirement in a Safety section to make the contract explicit.

Update all call sites to use unsafe blocks and change their comments from INVARIANT: to SAFETY:, as they are now justifying unsafe operations rather than establishing type invariants.

Quoted 5 lines

I believe I gave my acked-by on v2, but just to make sure it isn't missed:

Miguel, do you prefer to take this directly, or should I gather all the num/* patches and send you a PR in one go sometime later?

#2 lore raw
Quoted 3 lines · Alexandre Courbot

Miguel, do you prefer to take this directly, or should I gather all the num/* patches and send you a PR in one go sometime later?

Just to avoid forgetting later, which ones do you mean? i.e. I have these in my radar:

[PATCH v3] rust: num: bounded: mark __new as unsafe
[PATCH] rust: num: fix typos in Bounded documentation
[PATCH] rust: num: bounded: rename try_into_bitint to try_into_bounded One in [PATCH v2 0/7] rust: build_assert: document and fix use
with function arguments

None seems urgent, i.e. they can be added to rust-fixes after -rc1 I think, right?

Thanks!

Cheers,
Miguel

#3 lore raw
Quoted 8 lines · Miguel Ojeda
Quoted 3 lines · Alexandre Courbot

Miguel, do you prefer to take this directly, or should I gather all the num/* patches and send you a PR in one go sometime later?

Just to avoid forgetting later, which ones do you mean? i.e. I have these in my radar:

Quoted 8 lines

[PATCH v3] rust: num: bounded: mark __new as unsafe
[PATCH] rust: num: fix typos in Bounded documentation
[PATCH] rust: num: bounded: rename try_into_bitint to try_into_bounded One in [PATCH v2 0/7] rust: build_assert: document and fix use
with function arguments

None seems urgent, i.e. they can be added to rust-fixes after -rc1 I think, right?

Oh yes, actually I was thinking about rust-next rather than rust-fixes, but that works as well. My point was more about taking the mental burden of tracking this off your shoulders. :)

#4 lore raw
In reply to Hsiu Che Yu
Quoted 3 lines · Hsiu Che Yu
     /// The caller remains responsible for checking, either statically or dynamically, that `value`
     /// can be represented as a `T` using at most `N` bits.

I will apply this one, but I think this paragraph is not needed, i.e. we can remove it, since now we added it as an actual precondition.

Also, it would be good to add back an // INVARIANT: comment, but just once, inside __new(), when we construct Self(value).

What do you think, Alexandre? All those can be done later.

Thanks!

Cheers,
Miguel

Applied
#5 lore raw
In reply to Hsiu Che Yu
Quoted 10 lines · Hsiu Che Yu

The Bounded::__new() constructor relies on the caller to ensure the value can be represented within N bits. Failing to uphold this requirement breaks the type invariant. Mark it as unsafe and document this requirement in a Safety section to make the contract explicit.

Update all call sites to use unsafe blocks and change their comments from INVARIANT: to SAFETY:, as they are now justifying unsafe operations rather than establishing type invariants.

Quoted 5 lines

Applied to rust-fixes -- thanks everyone!

We can do the cleanups I mentioned on top later, but let's get this part done.

Cheers,
Miguel