Re: [PATCH v5 0/4] rust: add `TryFrom` and `Into` derive macros
From: Alexandre Courbot
Date: Sat Feb 28 2026 - 00:32:19 EST
On Thu Jan 29, 2026 at 11:32 PM JST, Jesung Yang via B4 Relay wrote:
> This patch series introduces derive macros for the `TryFrom` and `Into`
> traits.
FWIW I have converted nova-core to use this, and this results in -200LoC
delta. Obviously I like this very much. :)
A few pieces of feedback for things I noticed while doing the
conversion:
- Very often we need to convert a type from and into the same primitive.
Not having to repeat the same thing in `#[try_from(foo)]` and
`#[into(foo)]` for these cases would be nice.
- In some rare cases, we want to convert an enum with 4 variants into
e.g. a `Bounded<u8, 2>`. This can be done using a `From`
implementation, and that's what the register macro expects. These
cases are not covered by the current macro (they are few however).
- When converting from/into boundeds, the number of used bits is the
only thing that counts - the backing type (u8, u32, ...) is
irrelevant. I thought it would be cool to be able to have a generic
TryFrom/Into implementation that works irrespective of the backing
type, but as far as I can tell this would be difficult to achieve.
Just throwing the idea in case others are more inspired than I am. :)
<snip>
> One last point: the current `Into` implementation relies on
> `Bounded::from_expr()`, which utilizes `build_assert!()`. So the
> expanded result looks roughly like this:
>
> impl From<Enum> for Bounded<u8, 4> {
> fn from(value: Enum) -> Bounded<u8, 4> {
> // Compile-time assertions to guarantee `value` fits within
> // `u8` (Omitted)
>
> Bounded::<u8, 4>::from_expr(value as u8)
> }
> }
>
> After some experimentation, it appears that the compiler correctly
> optimizes out the assertion if (and only if) the `Bounded` type covers
> all enum discriminants, though I'm not 100% certain of this behavior in
> all cases. Can we approach this better?
I think you should also be able to have a match arm for all variants and
call the `Bounded::new` const method - hopefully the compiler will
optimize that as well. That or rely on unsafe code and a (hypothetical)
`new_unchecked` constructor for Bounded, since the macro can infer that
its invariants are respected.