Skip to content

Instantly share code, notes, and snippets.

@pragmatrix
Created April 14, 2023 09:42
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 pragmatrix/298631f979537028195db6cff55dfd48 to your computer and use it in GitHub Desktop.
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
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