Skip to content

Instantly share code, notes, and snippets.

@leiter-jakab
Last active December 26, 2020 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leiter-jakab/7e2d6560251170230da1e64df9f5e992 to your computer and use it in GitHub Desktop.
Save leiter-jakab/7e2d6560251170230da1e64df9f5e992 to your computer and use it in GitHub Desktop.
Cacher implementation in Rust
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hash, Hasher};
use std::fmt::Display;
fn main() {
let mut c: Cacher<u32, u32> = Cacher::new(|x| x);
let v = c.value(3);
println!("uncached value is: {}", v);
let v = c.value(3);
println!("cached value is: {}", v);
}
struct Cacher<T, U>
where
T: Hash + Display,
{
calculation: fn(T) -> U,
cache: HashMap<u64, U>,
}
impl<T, U> Cacher<T, U>
where
T: Hash + Display,
{
fn new(calculation: fn(T) -> U) -> Self {
Self {
calculation,
cache: HashMap::new(),
}
}
fn value(&mut self, arg: T) -> &U {
let mut hasher = DefaultHasher::new();
arg.hash(&mut hasher);
let hash = hasher.finish();
if !self.cache.contains_key(&hash) {
println!("value for arg = {} not konwn yet", &arg);
let res = (self.calculation)(arg);
self.cache.insert(hash, res);
}
self.cache.get(&hash).unwrap()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment