2 releases
0.0.2 | Aug 19, 2024 |
---|---|
0.0.1 | Aug 4, 2024 |
#2089 in Rust patterns
16KB
319 lines
struct_cache_field
struct_cache_field
crate provides macros that cache method results to struct fields.
Licence
MIT or Apache-2.0.
lib.rs
:
struct_cache_field
struct_cache_field
provides procedual macros to declare/manage cache fields for methods.
Usage
#[struct_cache_field::impl_cached_method]
impl Hoge {
pub fn two_times_x(&self) -> u64 {
2 * self.x
}
fn x_plus_1(&mut self) -> u64 {
self.x = self.x + 1;
self.x
}
}
#[struct_cache_field::add_cache_field]
struct Hoge {
x: u64,
}
fn main() {
let mut hoge = Hoge {
x: 1,
__cache_fields__: Default::default(),
};
assert_eq!(hoge.two_times_x(), &2);
assert_eq!(hoge.two_times_x(), &2);
hoge.x = 2;
assert_eq!(hoge.two_times_x(), &2);
assert_eq!(hoge.x_plus_1(), &3);
assert_eq!(hoge.x_plus_1(), &3);
hoge.x = 3;
assert_eq!(hoge.x_plus_1(), &3);
}
#[impl_cached_method]
generates a struct to hold caches for methods.
struct __struct_cache_field__HogeCacheFields {
two_times_x: ::core::cell::OnceCell<u64>,
x_plus_1: ::core::cell::OnceCell<u64>,
}
#[add_cache_field]
adds it to the original struct definition.
struct Hoge {
x: u64,
__cache_fields__: __struct_cache_field__HogeCacheFields,
}
Note that currently procedural macro in expression position is currently not supported.
So, you need to initialize __cache_fields__
with Default::default()
by yourself.
You MUST use both #[impl_cached_method]
and #[add_cache_field]
together.
If you use only #[impl_cached_method]
, it can cause a compile error in other crates.
Because this crate uses type-name-keyed compile time storage.
In the above example, #[impl_cached_method]
registeres data with key "Hoge"
, and
#[add_cache_field]
consumes it.
Dependencies
~1.6–9MB
~88K SLoC