Skip to main content

cranpose_core/
owned.rs

1use std::{
2    cell::{Ref, RefCell, RefMut},
3    rc::{Rc, Weak},
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
71    pub(crate) fn downgrade(&self) -> WeakOwned<T> {
72        WeakOwned {
73            inner: Rc::downgrade(&self.inner),
74        }
75    }
76
77    pub(crate) fn strong_count(&self) -> usize {
78        Rc::strong_count(&self.inner)
79    }
80
81    pub(crate) fn weak_count(&self) -> usize {
82        Rc::weak_count(&self.inner)
83    }
84}
85
86pub(crate) struct WeakOwned<T> {
87    inner: Weak<OwnedInner<T>>,
88}
89
90impl<T> Clone for WeakOwned<T> {
91    fn clone(&self) -> Self {
92        Self {
93            inner: Weak::clone(&self.inner),
94        }
95    }
96}
97
98impl<T> WeakOwned<T> {
99    pub(crate) fn with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
100        let inner = self.inner.upgrade()?;
101        let borrow = inner.value.borrow();
102        Some(f(&*borrow))
103    }
104}