generic_container/impls/rc_refcell.rs
1use core::convert::Infallible;
2use core::cell::{Ref, RefCell, RefMut};
3use alloc::rc::Rc;
4
5use crate::container_traits::{
6 FragileContainer, FragileMutContainer, FragileTryContainer, FragileTryMutContainer,
7};
8
9
10impl<T: ?Sized> FragileTryContainer<T> for Rc<RefCell<T>> {
11 type Ref<'a> = Ref<'a, T> where T: 'a;
12 type RefError = Infallible;
13
14 #[inline]
15 fn new_container(t: T) -> Self where T: Sized {
16 Self::new(RefCell::new(t))
17 }
18
19 /// Attempt to retrieve the inner `T` from the container.
20 /// Behaves identically to [`Rc::into_inner`].
21 #[inline]
22 fn into_inner(self) -> Option<T> where T: Sized {
23 Self::into_inner(self).map(RefCell::into_inner)
24 }
25
26 /// Get immutable access to the inner `T`.
27 ///
28 /// Uses [`RefCell::borrow`], so this container is
29 /// [fragile](crate#fragility-potential-panics-or-deadlocks).
30 ///
31 /// ## Panics
32 /// Panics if the contract of a fragile container is broken.
33 #[inline]
34 fn try_get_ref(&self) -> Result<Self::Ref<'_>, Self::RefError> {
35 Ok(self.borrow())
36 }
37}
38
39impl<T: ?Sized> FragileContainer<T> for Rc<RefCell<T>> {
40 /// Get immutable access to the inner `T`.
41 ///
42 /// Uses [`RefCell::borrow`], so this container is
43 /// [fragile](crate#fragility-potential-panics-or-deadlocks).
44 ///
45 /// ## Panics
46 /// Panics if the contract of a fragile container is broken.
47 #[inline]
48 fn get_ref(&self) -> Self::Ref<'_> {
49 self.borrow()
50 }
51}
52
53impl<T: ?Sized> FragileTryMutContainer<T> for Rc<RefCell<T>> {
54 type RefMut<'a> = RefMut<'a, T> where T: 'a;
55 type RefMutError = Infallible;
56
57 /// Get mutable access to the inner `T`.
58 ///
59 /// Uses [`RefCell::borrow_mut`], so this container is
60 /// [fragile](crate#fragility-potential-panics-or-deadlocks).
61 ///
62 /// ## Panics
63 /// Panics if the contract of a fragile container is broken.
64 #[inline]
65 fn try_get_mut(&mut self) -> Result<Self::RefMut<'_>, Self::RefMutError> {
66 Ok(self.borrow_mut())
67 }
68}
69
70impl<T: ?Sized> FragileMutContainer<T> for Rc<RefCell<T>> {
71 /// Get mutable access to the inner `T`.
72 ///
73 /// Uses [`RefCell::borrow_mut`], so this container is
74 /// [fragile](crate#fragility-potential-panics-or-deadlocks).
75 ///
76 /// ## Panics
77 /// Panics if the contract of a fragile container is broken.
78 #[inline]
79 fn get_mut(&mut self) -> Self::RefMut<'_> {
80 self.borrow_mut()
81 }
82}