archery/shared_pointer/kind/rc/
mod.rs1use crate::shared_pointer::kind::SharedPointerKind;
2use alloc::boxed::Box;
3use alloc::rc::Rc;
4use core::fmt;
5use core::fmt::Debug;
6use core::fmt::Formatter;
7use core::mem;
8use core::mem::ManuallyDrop;
9use core::ops::Deref;
10use core::ops::DerefMut;
11use core::ptr;
12
13type UntypedRc = Rc<()>;
14
15pub struct RcK {
18 inner: ManuallyDrop<UntypedRc>,
22}
23
24impl RcK {
25 #[inline(always)]
26 fn new_from_inner<T>(rc: Rc<T>) -> RcK {
27 RcK { inner: ManuallyDrop::new(unsafe { mem::transmute::<Rc<T>, UntypedRc>(rc) }) }
28 }
29
30 #[inline(always)]
31 unsafe fn take_inner<T>(self) -> Rc<T> {
32 unsafe {
33 let rc: UntypedRc = ManuallyDrop::into_inner(self.inner);
34
35 mem::transmute(rc)
36 }
37 }
38
39 #[inline(always)]
40 unsafe fn as_inner_ref<T>(&self) -> &Rc<T> {
41 unsafe {
42 let rc_t: *const Rc<T> = ptr::from_ref::<UntypedRc>(self.inner.deref()).cast::<Rc<T>>();
43
44 let _ = mem::transmute::<UntypedRc, Rc<T>>;
50
51 &*rc_t
52 }
53 }
54
55 #[inline(always)]
56 unsafe fn as_inner_mut<T>(&mut self) -> &mut Rc<T> {
57 unsafe {
58 let rc_t: *mut Rc<T> =
59 ptr::from_mut::<UntypedRc>(self.inner.deref_mut()).cast::<Rc<T>>();
60
61 &mut *rc_t
62 }
63 }
64}
65
66unsafe impl SharedPointerKind for RcK {
67 #[inline(always)]
68 fn new<T>(v: T) -> RcK {
69 RcK::new_from_inner(Rc::new(v))
70 }
71
72 #[inline(always)]
73 fn from_box<T>(v: Box<T>) -> RcK {
74 RcK::new_from_inner::<T>(Rc::from(v))
75 }
76
77 #[inline(always)]
78 unsafe fn as_ptr<T>(&self) -> *const T {
79 unsafe { Rc::as_ptr(self.as_inner_ref()) }
80 }
81
82 #[inline(always)]
83 unsafe fn deref<T>(&self) -> &T {
84 unsafe { self.as_inner_ref::<T>().as_ref() }
85 }
86
87 #[inline(always)]
88 unsafe fn try_unwrap<T>(self) -> Result<T, RcK> {
89 unsafe { Rc::try_unwrap(self.take_inner()).map_err(RcK::new_from_inner) }
90 }
91
92 #[inline(always)]
93 unsafe fn get_mut<T>(&mut self) -> Option<&mut T> {
94 unsafe { Rc::get_mut(self.as_inner_mut()) }
95 }
96
97 #[inline(always)]
98 unsafe fn make_mut<T: Clone>(&mut self) -> &mut T {
99 unsafe { Rc::make_mut(self.as_inner_mut()) }
100 }
101
102 #[inline(always)]
103 unsafe fn strong_count<T>(&self) -> usize {
104 unsafe { Rc::strong_count(self.as_inner_ref::<T>()) }
105 }
106
107 #[inline(always)]
108 unsafe fn clone<T>(&self) -> RcK {
109 unsafe { RcK { inner: ManuallyDrop::new(Rc::clone(self.as_inner_ref())) } }
110 }
111
112 #[inline(always)]
113 unsafe fn drop<T>(&mut self) {
114 unsafe {
115 ptr::drop_in_place::<Rc<T>>(self.as_inner_mut());
116 }
117 }
118}
119
120impl Debug for RcK {
121 #[inline(always)]
122 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
123 f.write_str("RcK")
124 }
125}
126
127#[cfg(test)]
128mod test;