| Crates.io | enum_inliner |
| lib.rs | enum_inliner |
| version | 0.0.1 |
| created_at | 2025-01-16 22:09:19.893425+00 |
| updated_at | 2025-01-21 03:56:28.37946+00 |
| description | Define custom code that's inlined for every variant of an enum |
| homepage | https://github.com/lffg/enum_inliner |
| repository | https://github.com/lffg/enum_inliner |
| max_upload_size | |
| id | 1520002 |
| size | 11,683 |
enum_inlinerTakes this:
mod strategy_impl { ... }
enum_inliner::enum_inline!(
#[derive(Copy, Clone)]
enum Strategy {
A,
B,
C,
}
impl<const __VARIANT__: ident> Strategy {
fn dbg_s(self) -> String {
format!("{:?}", strategy_impl::__VARIANT__)
}
}
);
And expands each function inside the provided impl block by "copying" its body
— the template — into the match arms generated for the corresponding enum.
One would get this:
mod strategy_impl { ... }
#[derive(Copy, Clone)]
enum Strategy {
A,
B,
C,
}
impl Strategy {
fn dbg_s(self) -> String {
match self {
Self::A => format!("{:?}", strategy_impl::A),
Self::B => format!("{:?}", strategy_impl::B),
Self::C => format!("{:?}", strategy_impl::C),
}
}
}
See the complete code in this simple example test.
Use cases aren't vast; but sometimes this may come in handy.
One of such use cases is when working with traits that aren't
object-safe/dyn-safe (cannot be used with dyn), but still require dynamic
dispatch at runtime. In these situations, one can create an enum with variants
representing each trait implementation, which is used to perform the dispatch
based on the enum "tags", which can pass through runtime.
Even though this kind of functionality can be implemented using a
declarative macro, the macro_rules! implementation becomes extremely
convoluted. User-level error messages also get degraded.
MIT license.