Re: [PATCH 1/2] rust: num: casts: replace const type narrowing methods with a macro
From: Alexandre Courbot
Date: Tue Aug 25 2026 - 10:45:24 EST
On Tue Aug 25, 2026 at 11:02 PM JST, Danilo Krummrich wrote:
> On Tue Aug 25, 2026 at 10:25 AM CEST, Miguel Ojeda wrote:
>> On Tue, Aug 25, 2026 at 4:45 AM Alexandre Courbot <acourbot@xxxxxxxxxx> wrote:
>>>
>>> const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
>>>
>>> into
>>>
>>> const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
>>
>> Having said that, macros have a cost too when they introduce new
>> "syntax", so since the beginning we have tried to minimize their use
>> to where we feel is worth it.
>>
>> The former line above is not perfect by any means, but it is
>> nevertheless syntax that one needs to already know. Personally
>> speaking, I don't care if I have to write the former or the latter, to
>> be honest, so I am OK with both ways.
>
> As mentioned in [1], I also think it's not great, but I also don't mind having
> it as is for now.
>
> I guess my main question is how we expect this to evolve. How do we want this to
> look like once we have things like const function arguments or const trait
> methods? Is it worth getting back and forth on a macro solution with this in
> mind?
I've thought about this a bit actually. Let's imagine we have a const
`TryFrom` trait. Even with that, we probably won't want users to do e.g.
`u8::try_from(SOME_U32_CONST).unwrap()` every time they need to narrow
something (if only because it would translate into a runtime panic if
somehow moved outside of a const block).
So for the same reason we are considering `nz!` to build non-zero values
efficiently, I expect `const_as!` to remain around in some capacity,
which should make the transition invisible to users.