Skip to content

Instantly share code, notes, and snippets.

@darotar
Created October 8, 2021 08:15
Show Gist options
  • Save darotar/23a3d55ff543b880fb0260c13d7f0cba to your computer and use it in GitHub Desktop.
Save darotar/23a3d55ff543b880fb0260c13d7f0cba to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::hash::Hash;
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Hash + Eq + Clone,
V: Copy,
{
calculation: T,
values: HashMap<U, V>,
}
impl<T, U, V> Cacher<T, U, V>
where
T: Fn(U) -> V,
U: Hash + Eq + Clone,
V: Copy,
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg).map(|v| v.clone()) {
Some(v) => v,
None => {
let v: V = (self.calculation)(arg.clone());
self.values.insert(arg, v.clone());
v
}
}
}
}
fn main() {
let mut cacher = Cacher::new(|i: i32| i + 10);
println!("{}", cacher.value(10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment