Skip to content

Instantly share code, notes, and snippets.

@m1el
Last active March 4, 2019 00:43
Show Gist options
  • Save m1el/4583d806cc58640b34565fe0218e7551 to your computer and use it in GitHub Desktop.
Save m1el/4583d806cc58640b34565fe0218e7551 to your computer and use it in GitHub Desktop.
use std::cmp::{Eq};
use std::collections::HashMap;
use std::hash::{Hash};
struct Cacher<I, O, F>
where
F: Fn(I) -> O,
{
function: F,
cache: HashMap<I, O>,
}
impl<I, O, F> Cacher<I, O, F>
where
I: Eq + Hash + Clone,
O: Clone,
F: Fn(I) -> O,
{
fn new(fun: F) -> Cacher<I, O, F> {
Cacher {
function: fun,
cache: HashMap::new(),
}
}
fn call(&mut self, key: I) -> O {
let f = &self.function;
self.cache.entry(key.clone())
.or_insert_with(|| (f)(key))
.clone()
}
}
fn some_fn(i: i32) -> i32 {
println!("Calculating value...");
return i * 2;
}
fn some_fn_2(_i: &str) -> i32 {
println!("Calculating value...");
return 2;
}
fn main() {
let mut cacher = Cacher::new(some_fn);
println!("{:?}", cacher.call(5));
println!("{:?}", cacher.call(5));
let mut cacher2 = Cacher::new(some_fn_2);
println!("{:?}", cacher2.call("asd"));
println!("{:?}", cacher2.call("asd"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment