pub struct MemoOnce<'p, T: Memoize>where
T::Param: 'p,{ /* private fields */ }
Expand description
Memoized value which holds a reference to the parameter for its computation
See the crate-level documentation for information how to use the library.
This type is designed for one-shot lazy computations. It holds a reference
to the input parameter for the computation, meaning that it cannot be
mutated while the MemoOnce
is alive.
§Example
use core_memo::{Memoize, MemoOnce};
// something trivial for the sake of example
struct MemoLength(usize);
impl Memoize for MemoLength {
type Param = String;
fn memoize(p: &String) -> Self {
MemoLength(p.len())
}
}
let mut my_string = String::from("My length is important!");
// ... some fancy computations ...
{
// we want to use our hard-to-compute value many times in this block,
// so we want to memoize it:
let mut len: MemoOnce<MemoLength> = MemoOnce::new(&my_string);
// ... more fancy computations ...
assert_eq!(len.get().0, 23);
// ... more stuff ...
println!("{}", len.get().0);
}
// now our `MemoOnce` has been dropped, our String is no longer borrowed,
// and we are free to mutate it:
my_string.push_str(" Not anymore!");
Implementations§
Source§impl<'p, T: Memoize> MemoOnce<'p, T>
impl<'p, T: Memoize> MemoOnce<'p, T>
Sourcepub fn new(p: &'p T::Param) -> Self
pub fn new(p: &'p T::Param) -> Self
Creates a new MemoOnce
instance
You must pass a reference to the object which will be used as the parameter for your computation.
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears any cached value
The value will be reevaluated the next time it is needed.
Sourcepub fn is_ready(&self) -> bool
pub fn is_ready(&self) -> bool
Check if there is a cached value
If this method returns true
, the next call to get()
will return a
stored memoized value.
If this method returns false
, the next call to get()
will recompute
the value.
Sourcepub fn ready(&mut self)
pub fn ready(&mut self)
If the value is not ready, compute it and cache it
Call this method if you want to make sure that future get()
calls can
return instantly without computing the value.
Sourcepub fn update(&mut self)
pub fn update(&mut self)
Force the value to be recomputed
This discards any stored value and computes a new one immediately.
It is probably better to call clear()
instead, to compute the value
lazily when it is next needed.
Sourcepub fn get(&mut self) -> &T
pub fn get(&mut self) -> &T
Get the value
If the value has already been computed, this function returns the cached value. If not, it is computed and cached for future use.
If you need to make sure this method always returns quickly, call
ready()
beforehand or use try_get()
.