Re: [PATCH 1/2] rust: num: casts: replace const type narrowing methods with a macro
"Gary Guo" <[email protected]>
| Newsgroups | org.kernel.vger.rust-for-linux,dev.linux.lists.nova-gpu,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
On Tue Aug 25, 2026 at 3:44 AM BST, Alexandre Courbot wrote:
> The casts module features a series of const converters (e.g.
> `u32_into_u16`) that narrow the type of a const expression provided that
> its value can be proven to fit into the destination type at
> compile-time.
>
> These functions are numerous (9 of them), generated by a macro and thus
> not easily discoverable, and cumbersome to use as they require a
> turbofish and const expression between `{` and `}` braces.
>
> Replace them all by a single `const_as!` macro that expands to a const
> block verifying the lossless nature of the conversion at compile-time.
> This turns e.g.:
>
> const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
>
> into
>
> const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
>
> This makes things easier to read and understand, while shifting the
> burden of checking the conversion's validity from reviewers (via a CAST
> comment) to the compiler.
Thanks, I like this much better than the methods (for reasons that I explained
in my reply to Miguel), and also that this looks nicer.
Reviewed-by: Gary Guo <[email protected]>
>
> Signed-off-by: Alexandre Courbot <[email protected]>
> ---
> rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
> 1 file changed, 79 insertions(+), 50 deletions(-)