Struct core_memo::MemoOnce [−][src]
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!");
Methods
impl<'p, T: Memoize> MemoOnce<'p, T>
[src]
impl<'p, T: Memoize> MemoOnce<'p, T>
pub fn new(p: &'p T::Param) -> Self
[src]
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.
pub fn clear(&mut self)
[src]
pub fn clear(&mut self)
Clears any cached value
The value will be reevaluated the next time it is needed.
pub fn is_ready(&self) -> bool
[src]
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.
pub fn ready(&mut self)
[src]
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.
pub fn update(&mut self)
[src]
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.
pub fn get(&mut self) -> &T
[src]
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()
.
pub fn try_get(&self) -> Option<&T>
[src]
pub fn try_get(&self) -> Option<&T>
Get the value if it is available
If there is a cached value, returns it. If the value needs to be
computed, returns None
.
pub fn param(&self) -> &T::Param
[src]
pub fn param(&self) -> &T::Param
Get a reference to the parameter used for the computation