rc_cell/
lib.rs

1//! Provides a thin wrapper over `Rc<RefCell<T>>` for higher ergonomics, as managing nested types
2//! gets annoying.
3
4use std::rc::{Rc, Weak};
5use std::cell::RefCell;
6use std::fmt::{Pointer, Formatter, Result as FmtResult, Display, Error as FmtError};
7use std::ops::Deref;
8
9/// The main attraction. Equivalent to `Rc<RefCell<T>>` but with one fewer type. `Rc` methods are
10/// reimplemented, and `RefCell` methods are gained by its `Deref` implementation.
11///
12/// All undocumented methods are equivalent to the `Rc` function of identical name.
13#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
14pub struct RcCell<T>(Rc<RefCell<T>>);
15
16impl<T> RcCell<T> {
17    pub fn new(value: T) -> Self {
18        Self(Rc::new(RefCell::new(value)))
19    }
20    pub fn try_unwrap(this: Self) -> Result<T, Self> {
21        Rc::try_unwrap(this.0).map(RefCell::into_inner).map_err(Self)
22    }
23    pub fn downgrade(&self) -> RcCellWeak<T> {
24        RcCellWeak(Rc::downgrade(&self.0))
25    }
26    pub fn weak_count(&self) -> usize {
27        Rc::weak_count(&self.0)
28    }
29    pub fn strong_count(&self) -> usize {
30        Rc::strong_count(&self.0)
31    }
32    pub fn ptr_eq(&self, other: &Self) -> bool {
33        Rc::ptr_eq(&self.0, &other.0)
34    }
35    /// Like `swap`, but with another `RcCell` instead of a `RefCell`.
36    pub fn swap_with(&self, other: &Self) {
37        self.swap(&other.0)
38    }
39}
40
41impl<T> Deref for RcCell<T> {
42    type Target = RefCell<T>;
43
44    fn deref(&self) -> &Self::Target {
45        &*self.0
46    }
47}
48
49impl<T> From<T> for RcCell<T> {
50    fn from(t: T) -> Self {
51        Self::new(t)
52    }
53}
54
55impl<T> From<Box<T>> for RcCell<T> {
56    fn from(t: Box<T>) -> Self {
57        Self::new(*t)
58    }
59}
60
61impl<T> Pointer for RcCell<T> {
62    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
63        write!(f, "{:p}", self.0)
64    }
65}
66
67impl<T> Display for RcCell<T> where T: Display {
68    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
69        write!(f, "{}", self.0.try_borrow().map_err(|_| FmtError)?)
70    }
71}
72
73/// Equivalent to `Weak<RefCell<T>>` but with one fewer type.
74///
75/// All undocumented methods are equivalent to the `Rc` function of identical name.
76#[derive(Debug, Default, Clone)]
77pub struct RcCellWeak<T>(Weak<RefCell<T>>);
78
79impl<T> RcCellWeak<T> {
80    pub fn new() -> Self {
81        Self(Weak::new())
82    }
83    pub fn upgrade(&self) -> Option<RcCell<T>> {
84        self.0.upgrade().map(RcCell)
85    }
86    pub fn ptr_eq(&self, other: &Self) -> bool {
87        self.0.ptr_eq(&other.0)
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use crate::RcCell;
94
95    #[test]
96    fn basic_test() {
97        let cell = RcCell::new("test");
98        let cell2 = cell.clone();
99        assert_eq!(cell.strong_count(), 2);
100        std::mem::drop(cell2);
101        assert_eq!(cell.strong_count(), 1);
102    }
103}