Skip to content

Instantly share code, notes, and snippets.

@aszenz
Created July 4, 2020 08:46
Show Gist options
  • Select an option

  • Save aszenz/cd822ea10559e15ad036d57ab3276428 to your computer and use it in GitHub Desktop.

Select an option

Save aszenz/cd822ea10559e15ad036d57ab3276428 to your computer and use it in GitHub Desktop.
use std::collections::hash_map::HashMap;
/// Cacher can cache function calls of one argument
pub struct Cacher<Computation, Input, Output>
where
Computation: Fn(Input) -> Output,
Input: std::cmp::Eq + std::hash::Hash,
Output: std::clone::Clone,
Input: std::clone::Clone,
{
computation: Computation,
cache_store: HashMap<Input, Output>,
}
impl<Computation, Input, Output> Cacher<Computation, Input, Output>
where
Computation: Fn(Input) -> Output,
Input: std::cmp::Eq + std::hash::Hash,
Output: std::clone::Clone,
Input: std::clone::Clone,
{
/// Returns a function cacher
///
/// # Arguments
///
/// * `computation` - A fn to cache
///
/// # Example
///
/// ```
/// use cacher::cacher::Cacher;
/// fn hello(name: &str) -> String { "hey".to_owned() + name }
/// let cached_function = Cacher::new(hello);
/// ```
pub fn new(computation: Computation) -> Cacher<Computation, Input, Output> {
Cacher {
computation,
cache_store: HashMap::new(),
}
}
/// Returns the computed value either from the cache or by computing it
///
/// # Arguments
///
/// * `input` - The input to the computation
///
/// # Example
///
/// ```
/// use cacher::cacher::Cacher;
/// fn hello(name: &str) -> String { "hey ".to_owned() + name }
/// let cached_function = Cacher::new(hello);
/// let z = cached_function.get("adam");
/// assert_eq!(z, "hey adam")
/// ```
pub fn get(mut self, input: Input) -> Output {
match self.cache_store.get(&input) {
Some(v) => v.clone(),
None => {
let cloned_input = input.clone();
let output = (self.computation)(input);
let cloned_output = output.clone();
self.cache_store.insert(cloned_input, output);
cloned_output
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment