Created
April 14, 2023 09:42
-
-
Save pragmatrix/298631f979537028195db6cff55dfd48 to your computer and use it in GitHub Desktop.
RcCache. - A simple cache that wraps references that point to values to reference counted values in Rust. Mostly written by GPT-4
This file contains 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::{cell::RefCell, collections::HashMap, hash::Hash, rc::Rc}; | |
#[derive(Debug)] | |
pub struct RcCache<K, V> | |
where | |
K: Eq + Hash + Clone, | |
V: Clone, | |
{ | |
data: RefCell<HashMap<K, Rc<V>>>, | |
} | |
impl<K, V> Default for RcCache<K, V> | |
where | |
K: Eq + Hash + Clone, | |
V: Clone, | |
{ | |
fn default() -> Self { | |
Self { | |
data: Default::default(), | |
} | |
} | |
} | |
impl<K, V> RcCache<K, V> | |
where | |
K: Eq + Hash + Clone, | |
V: Clone, | |
{ | |
pub fn get<F>(&self, key: K, value_fn: F) -> Rc<V> | |
where | |
F: FnOnce(&K) -> V, | |
{ | |
let mut data = self.data.borrow_mut(); | |
let entry = data.entry(key.clone()); | |
Rc::clone(entry.or_insert_with(|| Rc::new(value_fn(&key)))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment