Skip to main content

archery/shared_pointer/kind/arc/
mod.rs

1use crate::shared_pointer::kind::SharedPointerKind;
2use crate::shared_pointer::kind::erased_ptr::ErasedPtr;
3use alloc::boxed::Box;
4use alloc::sync::Arc;
5use core::fmt;
6use core::fmt::Debug;
7use core::fmt::Formatter;
8use core::mem::ManuallyDrop;
9
10/// [Type constructors](https://en.wikipedia.org/wiki/Type_constructor) for
11/// [`Arc`] pointers.
12pub struct ArcK {
13    /// A pointer previously obtained from [`Arc::into_raw()`] for the `T` this instance was
14    /// constructed with, and round-tripped through [`Arc::from_raw()`] on every operation. This
15    /// avoids relying on the layout of `Arc<T>` (which is not part of Rust's stable ABI) to
16    /// perform the type erasure.
17    ///
18    /// The referenced [`Arc`] allocation is kept alive by this pointer (which owns one strong
19    /// reference) until [`SharedPointerKind::drop()`] is called.
20    inner: ErasedPtr,
21}
22
23// SAFETY: `ArcK` is a type-erased handle to an `Arc<T>` for some `T`. `Arc<T>` is `Send + Sync`
24// when `T: Send + Sync`. `ArcK` itself is unconditionally `Send + Sync` because it has no
25// knowledge of `T`; the safe wrapper `SharedPointer<T, ArcK>` gates its own `Send`/`Sync` impls
26// on `T: Send + Sync` (see the "Wrapping in a safe API" section on `SharedPointerKind`).
27unsafe impl Send for ArcK {}
28unsafe impl Sync for ArcK {}
29
30impl ArcK {
31    #[inline(always)]
32    fn new_from_inner<T>(arc: Arc<T>) -> ArcK {
33        ArcK { inner: ErasedPtr::new(Arc::into_raw(arc)) }
34    }
35
36    /// Reconstructs a non-owning view of the inner [`Arc<T>`].
37    ///
38    /// The returned [`ManuallyDrop`] must not be unwrapped: dropping the inner [`Arc`] would
39    /// decrement a refcount that this instance still logically owns.
40    ///
41    /// # Safety
42    ///
43    /// `Self` must have been constructed with the same `T`.
44    #[inline(always)]
45    unsafe fn as_inner<T>(&self) -> ManuallyDrop<Arc<T>> {
46        // SAFETY: By the type-parameter invariant, `self.inner` was produced by
47        // `Arc::into_raw::<T>` and points to a live `Arc<T>` allocation. Wrapping the
48        // reconstructed `Arc` in `ManuallyDrop` prevents it from decrementing the strong count
49        // when this local goes out of scope.
50        ManuallyDrop::new(unsafe { Arc::from_raw(self.inner.cast::<T>()) })
51    }
52
53    /// Takes ownership of the inner [`Arc<T>`], consuming `self`.
54    ///
55    /// # Safety
56    ///
57    /// `Self` must have been constructed with the same `T`.
58    #[inline(always)]
59    unsafe fn take_inner<T>(self) -> Arc<T> {
60        // SAFETY: By the type-parameter invariant, `self.inner` was produced by
61        // `Arc::into_raw::<T>`. `self` is consumed by value and `ArcK` has no `Drop` impl, so
62        // the ownership of the strong reference transfers cleanly to the returned `Arc<T>`.
63        unsafe { Arc::from_raw(self.inner.cast::<T>()) }
64    }
65}
66
67unsafe impl SharedPointerKind for ArcK {
68    #[inline(always)]
69    fn new<T>(v: T) -> ArcK {
70        ArcK::new_from_inner(Arc::new(v))
71    }
72
73    #[inline(always)]
74    fn from_box<T>(v: Box<T>) -> ArcK {
75        ArcK::new_from_inner::<T>(Arc::from(v))
76    }
77
78    #[inline(always)]
79    unsafe fn as_ptr<T>(&self) -> *const T {
80        // SAFETY: The type-parameter invariant is forwarded to `ErasedPtr::cast`.
81        unsafe { self.inner.cast::<T>() }
82    }
83
84    #[inline(always)]
85    unsafe fn deref<T>(&self) -> &T {
86        // SAFETY: By the type-parameter invariant, `self.inner` was produced by
87        // `Arc::into_raw::<T>`, so it points to a valid `T` inside an allocation that is kept
88        // alive by `self`. The returned reference is tied to the lifetime of `&self`.
89        unsafe { &*self.inner.cast::<T>() }
90    }
91
92    #[inline(always)]
93    unsafe fn try_unwrap<T>(self) -> Result<T, ArcK> {
94        // SAFETY: The type-parameter invariant is forwarded to `take_inner`.
95        let arc: Arc<T> = unsafe { self.take_inner::<T>() };
96
97        Arc::try_unwrap(arc).map_err(ArcK::new_from_inner)
98    }
99
100    #[inline(always)]
101    unsafe fn get_mut<T>(&mut self) -> Option<&mut T> {
102        // SAFETY: The type-parameter invariant is forwarded to `map_owned`; `Arc::from_raw` and
103        // `Arc::into_raw` are an inverse pair for `Arc<T>`.
104        let ret: Option<*mut T> = unsafe {
105            self.inner.map_owned::<T, Arc<T>, _>(Arc::from_raw, Arc::as_ptr, |arc| {
106                Arc::get_mut(arc).map(core::ptr::from_mut)
107            })
108        };
109
110        // SAFETY: If `Arc::get_mut` returned `Some`, no other strong or weak reference existed
111        // at the time of the call, so we have exclusive access to the `T`. The allocation is
112        // kept alive for at least as long as `self` because `self.inner` still owns a strong
113        // reference. The returned reference's lifetime is bound to `&mut self`, so no other
114        // access through `self` can occur while it is live.
115        ret.map(|p| unsafe { &mut *p })
116    }
117
118    #[inline(always)]
119    unsafe fn make_mut<T: Clone>(&mut self) -> &mut T {
120        // SAFETY: The type-parameter invariant is forwarded to `map_owned`; `Arc::from_raw` and
121        // `Arc::into_raw` are an inverse pair for `Arc<T>`.
122        let ret: *mut T = unsafe {
123            self.inner.map_owned::<T, Arc<T>, _>(Arc::from_raw, Arc::as_ptr, |arc| {
124                core::ptr::from_mut(Arc::make_mut(arc))
125            })
126        };
127
128        // SAFETY: `Arc::make_mut` guarantees exclusive access to the (possibly freshly cloned)
129        // `T`. The allocation is kept alive by `self.inner`. The returned reference's lifetime
130        // is bound to `&mut self`, so no other access through `self` can occur while it is
131        // live.
132        unsafe { &mut *ret }
133    }
134
135    #[inline(always)]
136    unsafe fn strong_count<T>(&self) -> usize {
137        // SAFETY: The type-parameter invariant is forwarded to `as_inner`.
138        let arc: ManuallyDrop<Arc<T>> = unsafe { self.as_inner::<T>() };
139
140        Arc::strong_count(&*arc)
141    }
142
143    #[inline(always)]
144    unsafe fn clone<T>(&self) -> ArcK {
145        // SAFETY: The type-parameter invariant is forwarded to `as_inner`.
146        let arc: ManuallyDrop<Arc<T>> = unsafe { self.as_inner::<T>() };
147
148        ArcK::new_from_inner(Arc::clone(&*arc))
149    }
150
151    #[inline(always)]
152    unsafe fn drop<T>(&mut self) {
153        // SAFETY: By the type-parameter invariant, `self.inner` was produced by
154        // `Arc::into_raw::<T>`. Reconstructing the `Arc<T>` and letting it drop decrements the
155        // strong count matching the initial `Arc::into_raw`. The caller guarantees this is the
156        // last use of `self`.
157        drop(unsafe { Arc::from_raw(self.inner.cast::<T>()) });
158    }
159}
160
161impl Debug for ArcK {
162    #[inline(always)]
163    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
164        f.write_str("ArcK")
165    }
166}
167
168#[cfg(test)]
169mod test;