Skip to content

Instantly share code, notes, and snippets.

@cyypherus
Created October 7, 2024 17:01
Show Gist options
  • Save cyypherus/d997a36f2e886e586b61a054d8240447 to your computer and use it in GitHub Desktop.
Save cyypherus/d997a36f2e886e586b61a054d8240447 to your computer and use it in GitHub Desktop.
Rust EZ Pointer
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Clone)]
struct EZ<T> {
inner: Rc<RefCell<T>>,
}
impl<T> EZ<T> {
fn new(value: T) -> Self {
EZ {
inner: Rc::new(RefCell::new(value)),
}
}
fn value_with<F, R>(&self, f: F) -> R
where
F: FnOnce(&T) -> R,
{
f(&self.inner.try_borrow().unwrap())
}
fn write<F>(&self, f: F)
where
F: FnOnce(&mut T),
{
f(&mut self.inner.try_borrow_mut().unwrap())
}
}
impl<T> EZ<T> where T: Copy {
fn value(&self) -> T {
*self.inner.try_borrow().unwrap()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment