1 // SPDX-License-Identifier: GPL-2.0
3 //! A reference-counted pointer.
5 //! This module implements a way for users to create reference-counted objects and pointers to
6 //! them. Such a pointer automatically increments and decrements the count, and drops the
7 //! underlying object when it reaches zero. It is also safe to use concurrently from multiple
10 //! It is different from the standard library's [`Arc`] in a few ways:
11 //! 1. It is backed by the kernel's `refcount_t` type.
12 //! 2. It does not support weak references, which allows it to be half the size.
13 //! 3. It saturates the reference count instead of aborting when it goes over a threshold.
14 //! 4. It does not provide a `get_mut` method, so the ref counted object is pinned.
16 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
19 alloc::{box_ext::BoxExt, AllocError, Flags},
21 init::{self, InPlaceInit, Init, PinInit},
23 types::{ForeignOwnable, Opaque},
25 use alloc::boxed::Box;
29 marker::{PhantomData, Unsize},
30 mem::{ManuallyDrop, MaybeUninit},
31 ops::{Deref, DerefMut},
39 /// A reference-counted pointer to an instance of `T`.
41 /// The reference count is incremented when new instances of [`Arc`] are created, and decremented
42 /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped.
46 /// The reference count on an instance of [`Arc`] is always non-zero.
47 /// The object pointed to by [`Arc`] is always pinned.
52 /// use kernel::sync::Arc;
59 /// // Create a refcounted instance of `Example`.
60 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
62 /// // Get a new pointer to `obj` and increment the refcount.
63 /// let cloned = obj.clone();
65 /// // Assert that both `obj` and `cloned` point to the same underlying object.
66 /// assert!(core::ptr::eq(&*obj, &*cloned));
68 /// // Destroy `obj` and decrement its refcount.
71 /// // Check that the values are still accessible through `cloned`.
72 /// assert_eq!(cloned.a, 10);
73 /// assert_eq!(cloned.b, 20);
75 /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
76 /// # Ok::<(), Error>(())
79 /// Using `Arc<T>` as the type of `self`:
82 /// use kernel::sync::Arc;
90 /// fn take_over(self: Arc<Self>) {
94 /// fn use_reference(self: &Arc<Self>) {
99 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
100 /// obj.use_reference();
102 /// # Ok::<(), Error>(())
105 /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
108 /// use kernel::sync::{Arc, ArcBorrow};
111 /// // Trait has a function whose `self` type is `Arc<Self>`.
112 /// fn example1(self: Arc<Self>) {}
114 /// // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
115 /// fn example2(self: ArcBorrow<'_, Self>) {}
119 /// impl MyTrait for Example {}
121 /// // `obj` has type `Arc<Example>`.
122 /// let obj: Arc<Example> = Arc::new(Example, GFP_KERNEL)?;
124 /// // `coerced` has type `Arc<dyn MyTrait>`.
125 /// let coerced: Arc<dyn MyTrait> = obj;
126 /// # Ok::<(), Error>(())
128 pub struct Arc<T: ?Sized> {
129 ptr: NonNull<ArcInner<T>>,
130 _p: PhantomData<ArcInner<T>>,
135 struct ArcInner<T: ?Sized> {
136 refcount: Opaque<bindings::refcount_t>,
140 impl<T: ?Sized> ArcInner<T> {
141 /// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`].
145 /// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must
146 /// not yet have been destroyed.
147 unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> {
148 let refcount_layout = Layout::new::<bindings::refcount_t>();
149 // SAFETY: The caller guarantees that the pointer is valid.
150 let val_layout = Layout::for_value(unsafe { &*ptr });
151 // SAFETY: We're computing the layout of a real struct that existed when compiling this
152 // binary, so its layout is not so large that it can trigger arithmetic overflow.
153 let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
155 // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and
156 // `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field.
158 // This is documented at:
159 // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
160 let ptr = ptr as *const ArcInner<T>;
162 // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
163 // pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is
165 let ptr = unsafe { ptr.byte_sub(val_offset) };
167 // SAFETY: The pointer can't be null since you can't have an `ArcInner<T>` value at the null
169 unsafe { NonNull::new_unchecked(ptr.cast_mut()) }
173 // This is to allow [`Arc`] (and variants) to be used as the type of `self`.
174 impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
176 // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
177 // dynamically-sized type (DST) `U`.
178 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
180 // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`.
181 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {}
183 // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
184 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
185 // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a
186 // mutable reference when the reference count reaches zero and `T` is dropped.
187 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
189 // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync`
190 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
191 // it needs `T` to be `Send` because any thread that has a `&Arc<T>` may clone it and get an
192 // `Arc<T>` on that thread, so the thread may ultimately access `T` using a mutable reference when
193 // the reference count reaches zero and `T` is dropped.
194 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
197 /// Constructs a new reference counted instance of `T`.
198 pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
199 // INVARIANT: The refcount is initialised to a non-zero value.
200 let value = ArcInner {
201 // SAFETY: There are no safety requirements for this FFI call.
202 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
206 let inner = <Box<_> as BoxExt<_>>::new(value, flags)?;
208 // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
210 Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
213 /// Use the given initializer to in-place initialize a `T`.
215 /// If `T: !Unpin` it will not be able to move afterwards.
217 pub fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> error::Result<Self>
221 UniqueArc::pin_init(init, flags).map(|u| u.into())
224 /// Use the given initializer to in-place initialize a `T`.
226 /// This is equivalent to [`Arc<T>::pin_init`], since an [`Arc`] is always pinned.
228 pub fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self>
232 UniqueArc::init(init, flags).map(|u| u.into())
236 impl<T: ?Sized> Arc<T> {
237 /// Constructs a new [`Arc`] from an existing [`ArcInner`].
241 /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
242 /// count, one of which will be owned by the new [`Arc`] instance.
243 unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
244 // INVARIANT: By the safety requirements, the invariants hold.
251 /// Convert the [`Arc`] into a raw pointer.
253 /// The raw pointer has ownership of the refcount that this Arc object owned.
254 pub fn into_raw(self) -> *const T {
255 let ptr = self.ptr.as_ptr();
256 core::mem::forget(self);
257 // SAFETY: The pointer is valid.
258 unsafe { core::ptr::addr_of!((*ptr).data) }
261 /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
265 /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
266 /// must not be called more than once for each previous call to [`Arc::into_raw`].
267 pub unsafe fn from_raw(ptr: *const T) -> Self {
268 // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
269 // `Arc` that is still valid.
270 let ptr = unsafe { ArcInner::container_of(ptr) };
272 // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
273 // reference count held then will be owned by the new `Arc` object.
274 unsafe { Self::from_inner(ptr) }
277 /// Returns an [`ArcBorrow`] from the given [`Arc`].
279 /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
280 /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
282 pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
283 // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
284 // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
285 // reference can be created.
286 unsafe { ArcBorrow::new(self.ptr) }
289 /// Compare whether two [`Arc`] pointers reference the same underlying object.
290 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
291 core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
294 /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique.
296 /// When this destroys the `Arc`, it does so while properly avoiding races. This means that
297 /// this method will never call the destructor of the value.
302 /// use kernel::sync::{Arc, UniqueArc};
304 /// let arc = Arc::new(42, GFP_KERNEL)?;
305 /// let unique_arc = arc.into_unique_or_drop();
307 /// // The above conversion should succeed since refcount of `arc` is 1.
308 /// assert!(unique_arc.is_some());
310 /// assert_eq!(*(unique_arc.unwrap()), 42);
312 /// # Ok::<(), Error>(())
316 /// use kernel::sync::{Arc, UniqueArc};
318 /// let arc = Arc::new(42, GFP_KERNEL)?;
319 /// let another = arc.clone();
321 /// let unique_arc = arc.into_unique_or_drop();
323 /// // The above conversion should fail since refcount of `arc` is >1.
324 /// assert!(unique_arc.is_none());
326 /// # Ok::<(), Error>(())
328 pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
329 // We will manually manage the refcount in this method, so we disable the destructor.
330 let me = ManuallyDrop::new(self);
331 // SAFETY: We own a refcount, so the pointer is still valid.
332 let refcount = unsafe { me.ptr.as_ref() }.refcount.get();
334 // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will
335 // return without further touching the `Arc`. If the refcount reaches zero, then there are
336 // no other arcs, and we can create a `UniqueArc`.
338 // SAFETY: We own a refcount, so the pointer is not dangling.
339 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
341 // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized
342 // accesses to the refcount.
343 unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) };
345 // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We
346 // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin
348 Some(Pin::from(UniqueArc {
349 inner: ManuallyDrop::into_inner(me),
357 impl<T: 'static> ForeignOwnable for Arc<T> {
358 type Borrowed<'a> = ArcBorrow<'a, T>;
360 fn into_foreign(self) -> *const core::ffi::c_void {
361 ManuallyDrop::new(self).ptr.as_ptr() as _
364 unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
365 // SAFETY: By the safety requirement of this function, we know that `ptr` came from
366 // a previous call to `Arc::into_foreign`.
367 let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
369 // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
370 // for the lifetime of the returned value.
371 unsafe { ArcBorrow::new(inner) }
374 unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
375 // SAFETY: By the safety requirement of this function, we know that `ptr` came from
376 // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
377 // holds a reference count increment that is transferrable to us.
378 unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
382 impl<T: ?Sized> Deref for Arc<T> {
385 fn deref(&self) -> &Self::Target {
386 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
387 // safe to dereference it.
388 unsafe { &self.ptr.as_ref().data }
392 impl<T: ?Sized> AsRef<T> for Arc<T> {
393 fn as_ref(&self) -> &T {
398 impl<T: ?Sized> Clone for Arc<T> {
399 fn clone(&self) -> Self {
400 // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
401 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
402 // safe to increment the refcount.
403 unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
405 // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
406 unsafe { Self::from_inner(self.ptr) }
410 impl<T: ?Sized> Drop for Arc<T> {
412 // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
413 // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
414 // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
415 // freed/invalid memory as long as it is never dereferenced.
416 let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
418 // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
419 // this instance is being dropped, so the broken invariant is not observable.
420 // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
421 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
423 // The count reached zero, we must free the memory.
425 // SAFETY: The pointer was initialised from the result of `Box::leak`.
426 unsafe { drop(Box::from_raw(self.ptr.as_ptr())) };
431 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
432 fn from(item: UniqueArc<T>) -> Self {
437 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
438 fn from(item: Pin<UniqueArc<T>>) -> Self {
439 // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
440 unsafe { Pin::into_inner_unchecked(item).inner }
444 /// A borrowed reference to an [`Arc`] instance.
446 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
447 /// to use just `&T`, which we can trivially get from an [`Arc<T>`] instance.
449 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
450 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
451 /// to a pointer ([`Arc<T>`]) to the object (`T`). An [`ArcBorrow`] eliminates this double
452 /// indirection while still allowing one to increment the refcount and getting an [`Arc<T>`] when/if
457 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
458 /// lifetime of the [`ArcBorrow`] instance.
463 /// use kernel::sync::{Arc, ArcBorrow};
467 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
471 /// let obj = Arc::new(Example, GFP_KERNEL)?;
472 /// let cloned = do_something(obj.as_arc_borrow());
474 /// // Assert that both `obj` and `cloned` point to the same underlying object.
475 /// assert!(core::ptr::eq(&*obj, &*cloned));
476 /// # Ok::<(), Error>(())
479 /// Using `ArcBorrow<T>` as the type of `self`:
482 /// use kernel::sync::{Arc, ArcBorrow};
490 /// fn use_reference(self: ArcBorrow<'_, Self>) {
495 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
496 /// obj.as_arc_borrow().use_reference();
497 /// # Ok::<(), Error>(())
499 pub struct ArcBorrow<'a, T: ?Sized + 'a> {
500 inner: NonNull<ArcInner<T>>,
501 _p: PhantomData<&'a ()>,
504 // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`.
505 impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {}
507 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
509 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
514 impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
515 fn clone(&self) -> Self {
520 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
522 impl<T: ?Sized> ArcBorrow<'_, T> {
523 /// Creates a new [`ArcBorrow`] instance.
527 /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
528 /// 1. That `inner` remains valid;
529 /// 2. That no mutable references to `inner` are created.
530 unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
531 // INVARIANT: The safety requirements guarantee the invariants.
538 /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with
539 /// [`Arc::into_raw`].
543 /// * The provided pointer must originate from a call to [`Arc::into_raw`].
544 /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must
546 /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a
547 /// [`UniqueArc`] reference to this value.
548 pub unsafe fn from_raw(ptr: *const T) -> Self {
549 // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an
550 // `Arc` that is still valid.
551 let ptr = unsafe { ArcInner::container_of(ptr) };
553 // SAFETY: The caller promises that the value remains valid since the reference count must
554 // not hit zero, and no mutable reference will be created since that would involve a
556 unsafe { Self::new(ptr) }
560 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
561 fn from(b: ArcBorrow<'_, T>) -> Self {
562 // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
563 // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
565 ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
571 impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
574 fn deref(&self) -> &Self::Target {
575 // SAFETY: By the type invariant, the underlying object is still alive with no mutable
576 // references to it, so it is safe to create a shared reference.
577 unsafe { &self.inner.as_ref().data }
581 /// A refcounted object that is known to have a refcount of 1.
583 /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
587 /// `inner` always has a reference count of 1.
591 /// In the following example, we make changes to the inner object before turning it into an
592 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
596 /// use kernel::sync::{Arc, UniqueArc};
603 /// fn test() -> Result<Arc<Example>> {
604 /// let mut x = UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?;
610 /// # test().unwrap();
613 /// In the following example we first allocate memory for a refcounted `Example` but we don't
614 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
615 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
616 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
619 /// use kernel::sync::{Arc, UniqueArc};
626 /// fn test() -> Result<Arc<Example>> {
627 /// let x = UniqueArc::new_uninit(GFP_KERNEL)?;
628 /// Ok(x.write(Example { a: 10, b: 20 }).into())
631 /// # test().unwrap();
634 /// In the last example below, the caller gets a pinned instance of `Example` while converting to
635 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
636 /// initialisation, for example, when initialising fields that are wrapped in locks.
639 /// use kernel::sync::{Arc, UniqueArc};
646 /// fn test() -> Result<Arc<Example>> {
647 /// let mut pinned = Pin::from(UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?);
648 /// // We can modify `pinned` because it is `Unpin`.
649 /// pinned.as_mut().a += 1;
650 /// Ok(pinned.into())
653 /// # test().unwrap();
655 pub struct UniqueArc<T: ?Sized> {
659 impl<T> UniqueArc<T> {
660 /// Tries to allocate a new [`UniqueArc`] instance.
661 pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> {
663 // INVARIANT: The newly-created object has a refcount of 1.
664 inner: Arc::new(value, flags)?,
668 /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
669 pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
670 // INVARIANT: The refcount is initialised to a non-zero value.
671 let inner = Box::try_init::<AllocError>(
673 // SAFETY: There are no safety requirements for this FFI call.
674 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
675 data <- init::uninit::<T, AllocError>(),
680 // INVARIANT: The newly-created object has a refcount of 1.
681 // SAFETY: The pointer from the `Box` is valid.
682 inner: unsafe { Arc::from_inner(Box::leak(inner).into()) },
687 impl<T> UniqueArc<MaybeUninit<T>> {
688 /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
689 pub fn write(mut self, value: T) -> UniqueArc<T> {
690 self.deref_mut().write(value);
691 // SAFETY: We just wrote the value to be initialized.
692 unsafe { self.assume_init() }
695 /// Unsafely assume that `self` is initialized.
699 /// The caller guarantees that the value behind this pointer has been initialized. It is
700 /// *immediate* UB to call this when the value is not initialized.
701 pub unsafe fn assume_init(self) -> UniqueArc<T> {
702 let inner = ManuallyDrop::new(self).inner.ptr;
704 // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
705 // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
706 inner: unsafe { Arc::from_inner(inner.cast()) },
710 /// Initialize `self` using the given initializer.
711 pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
712 // SAFETY: The supplied pointer is valid for initialization.
713 match unsafe { init.__init(self.as_mut_ptr()) } {
714 // SAFETY: Initialization completed successfully.
715 Ok(()) => Ok(unsafe { self.assume_init() }),
716 Err(err) => Err(err),
720 /// Pin-initialize `self` using the given pin-initializer.
721 pub fn pin_init_with<E>(
723 init: impl PinInit<T, E>,
724 ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
725 // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
726 // to ensure it does not move.
727 match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
728 // SAFETY: Initialization completed successfully.
729 Ok(()) => Ok(unsafe { self.assume_init() }.into()),
730 Err(err) => Err(err),
735 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
736 fn from(obj: UniqueArc<T>) -> Self {
737 // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
738 // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
739 unsafe { Pin::new_unchecked(obj) }
743 impl<T: ?Sized> Deref for UniqueArc<T> {
746 fn deref(&self) -> &Self::Target {
751 impl<T: ?Sized> DerefMut for UniqueArc<T> {
752 fn deref_mut(&mut self) -> &mut Self::Target {
753 // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
754 // it is safe to dereference it. Additionally, we know there is only one reference when
755 // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
756 unsafe { &mut self.inner.ptr.as_mut().data }
760 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 fmt::Display::fmt(self.deref(), f)
766 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
767 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
768 fmt::Display::fmt(self.deref(), f)
772 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
774 fmt::Debug::fmt(self.deref(), f)
778 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780 fmt::Debug::fmt(self.deref(), f)