Skip to main content

cranpose_core/
owned.rs

1use std::cell::{Ref, RefCell, RefMut};
2use std::rc::Rc;
3
4/// Single-threaded owner for values remembered by the Composer.
5///
6/// This type stores `T` inside an `Rc<RefCell<...>>`, allowing cheap cloning of the
7/// handle while keeping ownership of `T` within the composition.
8pub struct Owned<T> {
9    inner: Rc<RefCell<T>>,
10}
11
12impl<T> Clone for Owned<T> {
13    fn clone(&self) -> Self {
14        Self {
15            inner: Rc::clone(&self.inner),
16        }
17    }
18}
19
20impl<T> Owned<T> {
21    pub fn new(value: T) -> Self {
22        Self {
23            inner: Rc::new(RefCell::new(value)),
24        }
25    }
26
27    /// Run `f` with an immutable reference to the stored value.
28    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
29        let borrow = self.inner.borrow();
30        f(&*borrow)
31    }
32
33    /// Run `f` with a mutable reference to the stored value.
34    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
35        let mut borrow = self.inner.borrow_mut();
36        f(&mut *borrow)
37    }
38
39    /// Borrow the stored value immutably.
40    pub fn borrow(&self) -> Ref<'_, T> {
41        self.inner.borrow()
42    }
43
44    /// Borrow the stored value mutably.
45    pub fn borrow_mut(&self) -> RefMut<'_, T> {
46        self.inner.borrow_mut()
47    }
48
49    /// Replace the stored value entirely.
50    pub fn replace(&self, new_value: T) {
51        *self.inner.borrow_mut() = new_value;
52    }
53}