Struct Cacher

Source
pub struct Cacher<F, U, V>
where F: Fn(U) -> V, U: Eq + Hash + Copy, V: Copy,
{ /* private fields */ }
Expand description

The Cacher struct (Memoization) stores a function and a Hashmap. The HashMap keeps track of previous input and output for the function so that it only ever has to be called once per input. Use for expensive functions.

Implementations§

Source§

impl<F, U, V> Cacher<F, U, V>
where F: Fn(U) -> V, U: Eq + Hash + Copy, V: Copy,

Source

pub fn new(calculation: F) -> Cacher<F, U, V>

Constuctor for the Casher

§Examples
let mut squared = Cacher::new(|n: u32| n*n);
Source

pub fn call(&mut self, arg: U) -> V

Performs a lookup into the HashMap to see if the value has already been calculated. If it has, returns the value. If it has not, calls the function, stores the value, then returns the value.

§Examples
let mut squared = Cacher::new(|n: u32| n*n);

// This is where we call the function
let sixteen = squared.call(4);
Source

pub fn call_and_replace(&mut self, arg: U) -> V

Calls the function without performing a lookup and replaces the old return value with the new one, and returns it. Potentially useful if the function reads from a file or RNG whose state may have changed.

Auto Trait Implementations§

§

impl<F, U, V> Freeze for Cacher<F, U, V>
where F: Freeze,

§

impl<F, U, V> RefUnwindSafe for Cacher<F, U, V>

§

impl<F, U, V> Send for Cacher<F, U, V>
where F: Send, U: Send, V: Send,

§

impl<F, U, V> Sync for Cacher<F, U, V>
where F: Sync, U: Sync, V: Sync,

§

impl<F, U, V> Unpin for Cacher<F, U, V>
where F: Unpin, U: Unpin, V: Unpin,

§

impl<F, U, V> UnwindSafe for Cacher<F, U, V>
where F: UnwindSafe, U: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.