| Crates.io | derive-insert |
| lib.rs | derive-insert |
| version | 0.1.1 |
| created_at | 2024-11-30 10:16:28.252791+00 |
| updated_at | 2024-11-30 10:24:28.662873+00 |
| description | A simple `GetOrInsert` trait for enums and its derive macro. |
| homepage | |
| repository | https://github.com/wada314/derive-insert |
| max_upload_size | |
| id | 1466487 |
| size | 19,379 |
A trait for enum types that support .insert(x) method which sets the enum variant to
something unique for x and returns a mutable reference to the value.
The most trivial example is Option<T>.
This operation is somehow not trivial to write in Rust (See the following sample generated code).
#[derive(GetOrInsert)] macro provides an implementation for enums
with every variant having a single distinct field types (or an unit type like Option::None).
If you write an enum like this:
use ::derive_insert::GetOrInsert;
#[derive(GetOrInsert)]
pub enum Foo {
Bar(i32),
Baz(String),
AnEmptyVariant,
}
The following code will be generated:
impl GetOrInsert<i32> for Foo {
fn insert(&mut self, value: i32) -> &mut i32 {
*self = Self::Bar(value);
match self {
Self::Bar(ref mut x) => x,
_ => unreachable!(),
}
}
fn get_or_insert_with<F: FnOnce() -> i32>(&mut self, f: F) -> &mut i32 {
match self {
Self::Bar(ref mut x) => x,
_ => self.insert(f()),
}
}
}
impl GetOrInsert<String> for Foo {
// ... Same for Foo::Baz
}
// Foo::AnEmptyVariant is skipped because it's an unit variant
Currently, this derive macro only supports the enum variants which are:
e.g. Option::Some(T)),e.g. Option::None).