[PATCH v9 03/15] gpu: nova-core: num: add functions to safely convert a const value to a smaller type

Alexandre Courbot posted 15 patches 1 month ago
[PATCH v9 03/15] gpu: nova-core: num: add functions to safely convert a const value to a smaller type
Posted by Alexandre Courbot 1 month ago
There are times where we need to store a constant value defined as a
larger type (e.g. through a binding) into a smaller type, knowing
that the value will fit. Rust, unfortunately, only provides us with the
`as` operator for that purpose, the use of which is discouraged as it
silently strips data.

Extend the `num` module with functions allowing to perform the
conversion infallibly, at compile time.

Example:

    const FOO_VALUE: u32 = 1;

    // `FOO_VALUE` fits into a `u8`, so the conversion is valid.
    let foo = num::u32_to_u8::<{ FOO_VALUE }>();

We are going to use this feature extensively in Nova.

Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
 drivers/gpu/nova-core/num.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)

diff --git a/drivers/gpu/nova-core/num.rs b/drivers/gpu/nova-core/num.rs
index 92a91b9e30de..f3740ab6cb9d 100644
--- a/drivers/gpu/nova-core/num.rs
+++ b/drivers/gpu/nova-core/num.rs
@@ -163,3 +163,54 @@ fn into_safe_cast(self) -> T {
         T::from_safe_cast(self)
     }
 }
+
+macro_rules! impl_const_into {
+    ($from:ty => { $($into:ty),* }) => {
+        $(
+        paste! {
+            #[doc = ::core::concat!(
+                "Performs a build-time safe conversion of a [`",
+                ::core::stringify!($from),
+                "`] constant value into a [`",
+                ::core::stringify!($into),
+                "`].")]
+            ///
+            /// This checks at compile-time that the conversion is lossless, and triggers a build
+            /// error if it isn't.
+            ///
+            /// # Examples
+            ///
+            /// ```
+            /// use kernel::num;
+            ///
+            /// // Succeeds because the value of the source fits into the destination's type.
+            #[doc = ::core::concat!(
+                "assert_eq!(num::",
+                ::core::stringify!($from),
+                "_into_",
+                ::core::stringify!($into),
+                "(1",
+                ::core::stringify!($from),
+                "), 1",
+                ::core::stringify!($into),
+                ");")]
+            /// ```
+            #[allow(unused)]
+            pub(crate) const fn [<$from _into_ $into>]<const N: $from>() -> $into {
+                // Make sure that the target type is smaller than the source one.
+                static_assert!($from::BITS >= $into::BITS);
+                // CAST: we statically enforced above that `$from` is larger than `$into`, so the
+                // `as` conversion will be lossless.
+                build_assert!(N >= $into::MIN as $from && N <= $into::MAX as $from);
+
+                N as $into
+            }
+        }
+        )*
+    };
+}
+
+impl_const_into!(usize => { u8, u16, u32 });
+impl_const_into!(u64 => { u8, u16, u32 });
+impl_const_into!(u32 => { u8, u16 });
+impl_const_into!(u16 => { u8 });

-- 
2.51.2
Re: [PATCH v9 03/15] gpu: nova-core: num: add functions to safely convert a const value to a smaller type
Posted by Mikko Perttunen 1 month ago
On Monday, November 10, 2025 10:34 PM Alexandre Courbot wrote:
> There are times where we need to store a constant value defined as a
> larger type (e.g. through a binding) into a smaller type, knowing
> that the value will fit. Rust, unfortunately, only provides us with the
> `as` operator for that purpose, the use of which is discouraged as it
> silently strips data.
> 
> Extend the `num` module with functions allowing to perform the
> conversion infallibly, at compile time.
> 
> Example:
> 
>     const FOO_VALUE: u32 = 1;
> 
>     // `FOO_VALUE` fits into a `u8`, so the conversion is valid.
>     let foo = num::u32_to_u8::<{ FOO_VALUE }>();
> 
> We are going to use this feature extensively in Nova.
> 
> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
> ---
>  drivers/gpu/nova-core/num.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 51 insertions(+)
> 
> diff --git a/drivers/gpu/nova-core/num.rs b/drivers/gpu/nova-core/num.rs
> index 92a91b9e30de..f3740ab6cb9d 100644
> --- a/drivers/gpu/nova-core/num.rs
> +++ b/drivers/gpu/nova-core/num.rs
> @@ -163,3 +163,54 @@ fn into_safe_cast(self) -> T {
>          T::from_safe_cast(self)
>      }
>  }
> +
> +macro_rules! impl_const_into {
> +    ($from:ty => { $($into:ty),* }) => {
> +        $(
> +        paste! {
> +            #[doc = ::core::concat!(
> +                "Performs a build-time safe conversion of a [`",
> +                ::core::stringify!($from),
> +                "`] constant value into a [`",
> +                ::core::stringify!($into),
> +                "`].")]
> +            ///
> +            /// This checks at compile-time that the conversion is lossless, and triggers a build
> +            /// error if it isn't.
> +            ///
> +            /// # Examples
> +            ///
> +            /// ```
> +            /// use kernel::num;
> +            ///
> +            /// // Succeeds because the value of the source fits into the destination's type.
> +            #[doc = ::core::concat!(
> +                "assert_eq!(num::",
> +                ::core::stringify!($from),
> +                "_into_",
> +                ::core::stringify!($into),
> +                "(1",
> +                ::core::stringify!($from),
> +                "), 1",
> +                ::core::stringify!($into),
> +                ");")]

This expands to e.g. assert_eq!(num::u32_to_u8(1u32), 1u8), i.e. not with a generic parameter.

With that fixed,

Reviewed-by: Mikko Perttunen <mperttunen@nvidia.com>

> +            /// ```
> +            #[allow(unused)]
> +            pub(crate) const fn [<$from _into_ $into>]<const N: $from>() -> $into {
> +                // Make sure that the target type is smaller than the source one.
> +                static_assert!($from::BITS >= $into::BITS);
> +                // CAST: we statically enforced above that `$from` is larger than `$into`, so the
> +                // `as` conversion will be lossless.
> +                build_assert!(N >= $into::MIN as $from && N <= $into::MAX as $from);
> +
> +                N as $into
> +            }
> +        }
> +        )*
> +    };
> +}
> +
> +impl_const_into!(usize => { u8, u16, u32 });
> +impl_const_into!(u64 => { u8, u16, u32 });
> +impl_const_into!(u32 => { u8, u16 });
> +impl_const_into!(u16 => { u8 });
> 
> 
Re: [PATCH v9 03/15] gpu: nova-core: num: add functions to safely convert a const value to a smaller type
Posted by Alexandre Courbot 1 month ago
On Fri Nov 14, 2025 at 3:49 PM JST, Mikko Perttunen wrote:
> On Monday, November 10, 2025 10:34 PM Alexandre Courbot wrote:
>> There are times where we need to store a constant value defined as a
>> larger type (e.g. through a binding) into a smaller type, knowing
>> that the value will fit. Rust, unfortunately, only provides us with the
>> `as` operator for that purpose, the use of which is discouraged as it
>> silently strips data.
>> 
>> Extend the `num` module with functions allowing to perform the
>> conversion infallibly, at compile time.
>> 
>> Example:
>> 
>>     const FOO_VALUE: u32 = 1;
>> 
>>     // `FOO_VALUE` fits into a `u8`, so the conversion is valid.
>>     let foo = num::u32_to_u8::<{ FOO_VALUE }>();
>> 
>> We are going to use this feature extensively in Nova.
>> 
>> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
>> ---
>>  drivers/gpu/nova-core/num.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++
>>  1 file changed, 51 insertions(+)
>> 
>> diff --git a/drivers/gpu/nova-core/num.rs b/drivers/gpu/nova-core/num.rs
>> index 92a91b9e30de..f3740ab6cb9d 100644
>> --- a/drivers/gpu/nova-core/num.rs
>> +++ b/drivers/gpu/nova-core/num.rs
>> @@ -163,3 +163,54 @@ fn into_safe_cast(self) -> T {
>>          T::from_safe_cast(self)
>>      }
>>  }
>> +
>> +macro_rules! impl_const_into {
>> +    ($from:ty => { $($into:ty),* }) => {
>> +        $(
>> +        paste! {
>> +            #[doc = ::core::concat!(
>> +                "Performs a build-time safe conversion of a [`",
>> +                ::core::stringify!($from),
>> +                "`] constant value into a [`",
>> +                ::core::stringify!($into),
>> +                "`].")]
>> +            ///
>> +            /// This checks at compile-time that the conversion is lossless, and triggers a build
>> +            /// error if it isn't.
>> +            ///
>> +            /// # Examples
>> +            ///
>> +            /// ```
>> +            /// use kernel::num;
>> +            ///
>> +            /// // Succeeds because the value of the source fits into the destination's type.
>> +            #[doc = ::core::concat!(
>> +                "assert_eq!(num::",
>> +                ::core::stringify!($from),
>> +                "_into_",
>> +                ::core::stringify!($into),
>> +                "(1",
>> +                ::core::stringify!($from),
>> +                "), 1",
>> +                ::core::stringify!($into),
>> +                ");")]
>
> This expands to e.g. assert_eq!(num::u32_to_u8(1u32), 1u8), i.e. not with a generic parameter.

Ah, nice catch, thanks! I missed that because the doccomments are not
built yet for code outside of `kernel`.

Fixing it by taking the example from the non-Nova RFC [1] of this patch.

[1] https://lore.kernel.org/all/20251104-as_casts-v1-1-0a0e95bd2a9f@nvidia.com/