Last active
December 26, 2020 12:25
-
-
Save leiter-jakab/7e2d6560251170230da1e64df9f5e992 to your computer and use it in GitHub Desktop.
Cacher implementation in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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