Re: [PATCH v4 1/2] rust: num: add cv! macro to create values from constant expressions

From: Eliot Courtney

Date: Tue Oct 13 2026 - 01:54:03 EST


On Sat Oct 3, 2026 at 1:59 AM JST, Miguel Ojeda wrote:
> On Thu, Sep 17, 2026 at 10:35 AM Eliot Courtney <ecourtney@xxxxxxxxxx> wrote:
>>
>> from constants without a verbose turbofish syntax.
>> For example, `const { NonZero::new(1).unwrap() }` can be written as
>
> Word wrap or newline?
>
>> +/// Creates a value from an integer constant expression, with validity checked at build time.
>
> Maybe:
>
> ... a constant value ("cv") ...
>
> since we explain that in the commit message, but not in the actual
> documentation :)
>
> I would also say "at compile time", and possibly mention it is usable
> in const context (we use "build time" for things like `build_assert!`,
> which can be much later, e.g. link time).
>
>> + };
>> + // Using `FromConst<V>::VALUE` means const generic expressions can't be used, since it requires
>
> Newline between these two lines?
>
>> +/// Types that can be created from an integer constant expression validated at build time.
>
> Ditto (please see above).
>
>> +/// Implement this trait to make a type usable with [`cv!`]. Use the [`cv`] macro, not this trait
>
> The second intra-doc link should also have a `!` for consistency.
>
>> + /// Fails the build if `V` is not a valid value for `Self`.
>
> [`Self`]
>
>> + // CAST: the macro is only used for types up to 64 bits wide, so `MIN` and `MAX`
>
> "CAST: The"
>
>> + // CAST: the assert above confirmed that `V` fits in `$type`.
>
> Ditto.
>
>> + // SAFETY: the assert above confirmed that `value` can be represented within `N`
>
> Ditto.
>
> Acked-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
>
> One thing before that, though: are these assertions expected to fail?
>
> const X: i64 = 1 << 31;
> const Y: i64 = cv!(1 << 31);
> assert_eq!(X, Y);
>
> Or:
>
> const X: u64 = 2 << 31;
> const Y: u64 = cv!(2 << 31);
> assert_eq!(X, Y);
>
> Because that is quite surprising, especially since we say "with the
> target type inferred from the context" in the documentation.
>
> I hope that helps & thanks Eliot for working on this!
>
> Cheers,
> Miguel

Miguel, thanks for noticing this! I agree this is surprising and worth a
pitfalls section like Alex suggests. AFAICT this can only affect
expressions which use left shift, so at least it's not all arithmetic.
And we can hit the same thing calling regular functions, e.g.
i64::from(2 << 31), although the macro does make it feel a bit more like
it should work. Let me add a pitfalls section for now.