Skip to main content

cranpose_core/
owned.rs

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