Crates.io | derive-insert |
lib.rs | derive-insert |
version | |
source | src |
created_at | 2024-11-30 10:16:28.252791 |
updated_at | 2024-11-30 10:24:28.662873 |
description | A simple `GetOrInsert` trait for enums and its derive macro. |
homepage | |
repository | https://github.com/wada314/derive-insert |
max_upload_size | |
id | 1466487 |
Cargo.toml error: | TOML parse error at line 17, column 1 | 17 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
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
).