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    /// Creates an owner holding `value`.
31    pub fn new(value: T) -> Self {
32        Self::with_states(value, Vec::new())
33    }
34
35    pub(crate) fn with_states(value: T, states: Vec<Rc<StateHandleLease>>) -> Self {
36        Self {
37            inner: Rc::new(OwnedInner {
38                value: RefCell::new(value),
39                _states: states,
40            }),
41        }
42    }
43
44    /// Run `f` with an immutable reference to the stored value.
45    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
46        let borrow = self.inner.value.borrow();
47        f(&*borrow)
48    }
49
50    /// Run `f` with a mutable reference to the stored value.
51    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
52        let mut borrow = self.inner.value.borrow_mut();
53        f(&mut *borrow)
54    }
55
56    /// Borrow the stored value immutably.
57    pub fn borrow(&self) -> Ref<'_, T> {
58        self.inner.value.borrow()
59    }
60
61    /// Borrow the stored value mutably.
62    pub fn borrow_mut(&self) -> RefMut<'_, T> {
63        self.inner.value.borrow_mut()
64    }
65
66    /// Replace the stored value entirely.
67    pub fn replace(&self, new_value: T) {
68        *self.inner.value.borrow_mut() = new_value;
69    }
70}