xref: /openbmc/linux/rust/kernel/sync/arc.rs (revision 9429b12d)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! A reference-counted pointer.
4 //!
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
8 //! threads.
9 //!
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.
15 //!
16 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
17 
18 use crate::{
19     bindings,
20     error::{self, Error},
21     init::{self, InPlaceInit, Init, PinInit},
22     try_init,
23     types::{ForeignOwnable, Opaque},
24 };
25 use alloc::boxed::Box;
26 use core::{
27     alloc::AllocError,
28     fmt,
29     marker::{PhantomData, Unsize},
30     mem::{ManuallyDrop, MaybeUninit},
31     ops::{Deref, DerefMut},
32     pin::Pin,
33     ptr::NonNull,
34 };
35 use macros::pin_data;
36 
37 mod std_vendor;
38 
39 /// A reference-counted pointer to an instance of `T`.
40 ///
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.
43 ///
44 /// # Invariants
45 ///
46 /// The reference count on an instance of [`Arc`] is always non-zero.
47 /// The object pointed to by [`Arc`] is always pinned.
48 ///
49 /// # Examples
50 ///
51 /// ```
52 /// use kernel::sync::Arc;
53 ///
54 /// struct Example {
55 ///     a: u32,
56 ///     b: u32,
57 /// }
58 ///
59 /// // Create a ref-counted instance of `Example`.
60 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
61 ///
62 /// // Get a new pointer to `obj` and increment the refcount.
63 /// let cloned = obj.clone();
64 ///
65 /// // Assert that both `obj` and `cloned` point to the same underlying object.
66 /// assert!(core::ptr::eq(&*obj, &*cloned));
67 ///
68 /// // Destroy `obj` and decrement its refcount.
69 /// drop(obj);
70 ///
71 /// // Check that the values are still accessible through `cloned`.
72 /// assert_eq!(cloned.a, 10);
73 /// assert_eq!(cloned.b, 20);
74 ///
75 /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
76 /// # Ok::<(), Error>(())
77 /// ```
78 ///
79 /// Using `Arc<T>` as the type of `self`:
80 ///
81 /// ```
82 /// use kernel::sync::Arc;
83 ///
84 /// struct Example {
85 ///     a: u32,
86 ///     b: u32,
87 /// }
88 ///
89 /// impl Example {
90 ///     fn take_over(self: Arc<Self>) {
91 ///         // ...
92 ///     }
93 ///
94 ///     fn use_reference(self: &Arc<Self>) {
95 ///         // ...
96 ///     }
97 /// }
98 ///
99 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
100 /// obj.use_reference();
101 /// obj.take_over();
102 /// # Ok::<(), Error>(())
103 /// ```
104 ///
105 /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`:
106 ///
107 /// ```
108 /// use kernel::sync::{Arc, ArcBorrow};
109 ///
110 /// trait MyTrait {
111 ///     // Trait has a function whose `self` type is `Arc<Self>`.
112 ///     fn example1(self: Arc<Self>) {}
113 ///
114 ///     // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`.
115 ///     fn example2(self: ArcBorrow<'_, Self>) {}
116 /// }
117 ///
118 /// struct Example;
119 /// impl MyTrait for Example {}
120 ///
121 /// // `obj` has type `Arc<Example>`.
122 /// let obj: Arc<Example> = Arc::try_new(Example)?;
123 ///
124 /// // `coerced` has type `Arc<dyn MyTrait>`.
125 /// let coerced: Arc<dyn MyTrait> = obj;
126 /// # Ok::<(), Error>(())
127 /// ```
128 pub struct Arc<T: ?Sized> {
129     ptr: NonNull<ArcInner<T>>,
130     _p: PhantomData<ArcInner<T>>,
131 }
132 
133 #[pin_data]
134 #[repr(C)]
135 struct ArcInner<T: ?Sized> {
136     refcount: Opaque<bindings::refcount_t>,
137     data: T,
138 }
139 
140 // This is to allow [`Arc`] (and variants) to be used as the type of `self`.
141 impl<T: ?Sized> core::ops::Receiver for Arc<T> {}
142 
143 // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the
144 // dynamically-sized type (DST) `U`.
145 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {}
146 
147 // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`.
148 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {}
149 
150 // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
151 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
152 // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a
153 // mutable reference when the reference count reaches zero and `T` is dropped.
154 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
155 
156 // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync`
157 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
158 // it needs `T` to be `Send` because any thread that has a `&Arc<T>` may clone it and get an
159 // `Arc<T>` on that thread, so the thread may ultimately access `T` using a mutable reference when
160 // the reference count reaches zero and `T` is dropped.
161 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
162 
163 impl<T> Arc<T> {
164     /// Constructs a new reference counted instance of `T`.
165     pub fn try_new(contents: T) -> Result<Self, AllocError> {
166         // INVARIANT: The refcount is initialised to a non-zero value.
167         let value = ArcInner {
168             // SAFETY: There are no safety requirements for this FFI call.
169             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
170             data: contents,
171         };
172 
173         let inner = Box::try_new(value)?;
174 
175         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
176         // `Arc` object.
177         Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
178     }
179 
180     /// Use the given initializer to in-place initialize a `T`.
181     ///
182     /// If `T: !Unpin` it will not be able to move afterwards.
183     #[inline]
184     pub fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Self>
185     where
186         Error: From<E>,
187     {
188         UniqueArc::pin_init(init).map(|u| u.into())
189     }
190 
191     /// Use the given initializer to in-place initialize a `T`.
192     ///
193     /// This is equivalent to [`Arc<T>::pin_init`], since an [`Arc`] is always pinned.
194     #[inline]
195     pub fn init<E>(init: impl Init<T, E>) -> error::Result<Self>
196     where
197         Error: From<E>,
198     {
199         UniqueArc::init(init).map(|u| u.into())
200     }
201 }
202 
203 impl<T: ?Sized> Arc<T> {
204     /// Constructs a new [`Arc`] from an existing [`ArcInner`].
205     ///
206     /// # Safety
207     ///
208     /// The caller must ensure that `inner` points to a valid location and has a non-zero reference
209     /// count, one of which will be owned by the new [`Arc`] instance.
210     unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
211         // INVARIANT: By the safety requirements, the invariants hold.
212         Arc {
213             ptr: inner,
214             _p: PhantomData,
215         }
216     }
217 
218     /// Returns an [`ArcBorrow`] from the given [`Arc`].
219     ///
220     /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
221     /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised.
222     #[inline]
223     pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> {
224         // SAFETY: The constraint that the lifetime of the shared reference must outlive that of
225         // the returned `ArcBorrow` ensures that the object remains alive and that no mutable
226         // reference can be created.
227         unsafe { ArcBorrow::new(self.ptr) }
228     }
229 
230     /// Compare whether two [`Arc`] pointers reference the same underlying object.
231     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
232         core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr())
233     }
234 }
235 
236 impl<T: 'static> ForeignOwnable for Arc<T> {
237     type Borrowed<'a> = ArcBorrow<'a, T>;
238 
239     fn into_foreign(self) -> *const core::ffi::c_void {
240         ManuallyDrop::new(self).ptr.as_ptr() as _
241     }
242 
243     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
244         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
245         // a previous call to `Arc::into_foreign`.
246         let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
247 
248         // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
249         // for the lifetime of the returned value.
250         unsafe { ArcBorrow::new(inner) }
251     }
252 
253     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
254         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
255         // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
256         // holds a reference count increment that is transferrable to us.
257         unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
258     }
259 }
260 
261 impl<T: ?Sized> Deref for Arc<T> {
262     type Target = T;
263 
264     fn deref(&self) -> &Self::Target {
265         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
266         // safe to dereference it.
267         unsafe { &self.ptr.as_ref().data }
268     }
269 }
270 
271 impl<T: ?Sized> AsRef<T> for Arc<T> {
272     fn as_ref(&self) -> &T {
273         self.deref()
274     }
275 }
276 
277 impl<T: ?Sized> Clone for Arc<T> {
278     fn clone(&self) -> Self {
279         // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero.
280         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
281         // safe to increment the refcount.
282         unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) };
283 
284         // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`.
285         unsafe { Self::from_inner(self.ptr) }
286     }
287 }
288 
289 impl<T: ?Sized> Drop for Arc<T> {
290     fn drop(&mut self) {
291         // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot
292         // touch `refcount` after it's decremented to a non-zero value because another thread/CPU
293         // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to
294         // freed/invalid memory as long as it is never dereferenced.
295         let refcount = unsafe { self.ptr.as_ref() }.refcount.get();
296 
297         // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and
298         // this instance is being dropped, so the broken invariant is not observable.
299         // SAFETY: Also by the type invariant, we are allowed to decrement the refcount.
300         let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) };
301         if is_zero {
302             // The count reached zero, we must free the memory.
303             //
304             // SAFETY: The pointer was initialised from the result of `Box::leak`.
305             unsafe { drop(Box::from_raw(self.ptr.as_ptr())) };
306         }
307     }
308 }
309 
310 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> {
311     fn from(item: UniqueArc<T>) -> Self {
312         item.inner
313     }
314 }
315 
316 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
317     fn from(item: Pin<UniqueArc<T>>) -> Self {
318         // SAFETY: The type invariants of `Arc` guarantee that the data is pinned.
319         unsafe { Pin::into_inner_unchecked(item).inner }
320     }
321 }
322 
323 /// A borrowed reference to an [`Arc`] instance.
324 ///
325 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
326 /// to use just `&T`, which we can trivially get from an `Arc<T>` instance.
327 ///
328 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
329 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
330 /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double
331 /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if
332 /// needed.
333 ///
334 /// # Invariants
335 ///
336 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
337 /// lifetime of the [`ArcBorrow`] instance.
338 ///
339 /// # Example
340 ///
341 /// ```
342 /// use kernel::sync::{Arc, ArcBorrow};
343 ///
344 /// struct Example;
345 ///
346 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
347 ///     e.into()
348 /// }
349 ///
350 /// let obj = Arc::try_new(Example)?;
351 /// let cloned = do_something(obj.as_arc_borrow());
352 ///
353 /// // Assert that both `obj` and `cloned` point to the same underlying object.
354 /// assert!(core::ptr::eq(&*obj, &*cloned));
355 /// # Ok::<(), Error>(())
356 /// ```
357 ///
358 /// Using `ArcBorrow<T>` as the type of `self`:
359 ///
360 /// ```
361 /// use kernel::sync::{Arc, ArcBorrow};
362 ///
363 /// struct Example {
364 ///     a: u32,
365 ///     b: u32,
366 /// }
367 ///
368 /// impl Example {
369 ///     fn use_reference(self: ArcBorrow<'_, Self>) {
370 ///         // ...
371 ///     }
372 /// }
373 ///
374 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
375 /// obj.as_arc_borrow().use_reference();
376 /// # Ok::<(), Error>(())
377 /// ```
378 pub struct ArcBorrow<'a, T: ?Sized + 'a> {
379     inner: NonNull<ArcInner<T>>,
380     _p: PhantomData<&'a ()>,
381 }
382 
383 // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`.
384 impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {}
385 
386 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into
387 // `ArcBorrow<U>`.
388 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>>
389     for ArcBorrow<'_, T>
390 {
391 }
392 
393 impl<T: ?Sized> Clone for ArcBorrow<'_, T> {
394     fn clone(&self) -> Self {
395         *self
396     }
397 }
398 
399 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {}
400 
401 impl<T: ?Sized> ArcBorrow<'_, T> {
402     /// Creates a new [`ArcBorrow`] instance.
403     ///
404     /// # Safety
405     ///
406     /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance:
407     /// 1. That `inner` remains valid;
408     /// 2. That no mutable references to `inner` are created.
409     unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self {
410         // INVARIANT: The safety requirements guarantee the invariants.
411         Self {
412             inner,
413             _p: PhantomData,
414         }
415     }
416 }
417 
418 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> {
419     fn from(b: ArcBorrow<'_, T>) -> Self {
420         // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop`
421         // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the
422         // increment.
423         ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) })
424             .deref()
425             .clone()
426     }
427 }
428 
429 impl<T: ?Sized> Deref for ArcBorrow<'_, T> {
430     type Target = T;
431 
432     fn deref(&self) -> &Self::Target {
433         // SAFETY: By the type invariant, the underlying object is still alive with no mutable
434         // references to it, so it is safe to create a shared reference.
435         unsafe { &self.inner.as_ref().data }
436     }
437 }
438 
439 /// A refcounted object that is known to have a refcount of 1.
440 ///
441 /// It is mutable and can be converted to an [`Arc`] so that it can be shared.
442 ///
443 /// # Invariants
444 ///
445 /// `inner` always has a reference count of 1.
446 ///
447 /// # Examples
448 ///
449 /// In the following example, we make changes to the inner object before turning it into an
450 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()`
451 /// cannot fail.
452 ///
453 /// ```
454 /// use kernel::sync::{Arc, UniqueArc};
455 ///
456 /// struct Example {
457 ///     a: u32,
458 ///     b: u32,
459 /// }
460 ///
461 /// fn test() -> Result<Arc<Example>> {
462 ///     let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?;
463 ///     x.a += 1;
464 ///     x.b += 1;
465 ///     Ok(x.into())
466 /// }
467 ///
468 /// # test().unwrap();
469 /// ```
470 ///
471 /// In the following example we first allocate memory for a ref-counted `Example` but we don't
472 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`],
473 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens
474 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
475 ///
476 /// ```
477 /// use kernel::sync::{Arc, UniqueArc};
478 ///
479 /// struct Example {
480 ///     a: u32,
481 ///     b: u32,
482 /// }
483 ///
484 /// fn test() -> Result<Arc<Example>> {
485 ///     let x = UniqueArc::try_new_uninit()?;
486 ///     Ok(x.write(Example { a: 10, b: 20 }).into())
487 /// }
488 ///
489 /// # test().unwrap();
490 /// ```
491 ///
492 /// In the last example below, the caller gets a pinned instance of `Example` while converting to
493 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during
494 /// initialisation, for example, when initialising fields that are wrapped in locks.
495 ///
496 /// ```
497 /// use kernel::sync::{Arc, UniqueArc};
498 ///
499 /// struct Example {
500 ///     a: u32,
501 ///     b: u32,
502 /// }
503 ///
504 /// fn test() -> Result<Arc<Example>> {
505 ///     let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?);
506 ///     // We can modify `pinned` because it is `Unpin`.
507 ///     pinned.as_mut().a += 1;
508 ///     Ok(pinned.into())
509 /// }
510 ///
511 /// # test().unwrap();
512 /// ```
513 pub struct UniqueArc<T: ?Sized> {
514     inner: Arc<T>,
515 }
516 
517 impl<T> UniqueArc<T> {
518     /// Tries to allocate a new [`UniqueArc`] instance.
519     pub fn try_new(value: T) -> Result<Self, AllocError> {
520         Ok(Self {
521             // INVARIANT: The newly-created object has a ref-count of 1.
522             inner: Arc::try_new(value)?,
523         })
524     }
525 
526     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
527     pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
528         // INVARIANT: The refcount is initialised to a non-zero value.
529         let inner = Box::try_init::<AllocError>(try_init!(ArcInner {
530             // SAFETY: There are no safety requirements for this FFI call.
531             refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
532             data <- init::uninit::<T, AllocError>(),
533         }? AllocError))?;
534         Ok(UniqueArc {
535             // INVARIANT: The newly-created object has a ref-count of 1.
536             // SAFETY: The pointer from the `Box` is valid.
537             inner: unsafe { Arc::from_inner(Box::leak(inner).into()) },
538         })
539     }
540 }
541 
542 impl<T> UniqueArc<MaybeUninit<T>> {
543     /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it.
544     pub fn write(mut self, value: T) -> UniqueArc<T> {
545         self.deref_mut().write(value);
546         // SAFETY: We just wrote the value to be initialized.
547         unsafe { self.assume_init() }
548     }
549 
550     /// Unsafely assume that `self` is initialized.
551     ///
552     /// # Safety
553     ///
554     /// The caller guarantees that the value behind this pointer has been initialized. It is
555     /// *immediate* UB to call this when the value is not initialized.
556     pub unsafe fn assume_init(self) -> UniqueArc<T> {
557         let inner = ManuallyDrop::new(self).inner.ptr;
558         UniqueArc {
559             // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be
560             // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`.
561             inner: unsafe { Arc::from_inner(inner.cast()) },
562         }
563     }
564 
565     /// Initialize `self` using the given initializer.
566     pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
567         // SAFETY: The supplied pointer is valid for initialization.
568         match unsafe { init.__init(self.as_mut_ptr()) } {
569             // SAFETY: Initialization completed successfully.
570             Ok(()) => Ok(unsafe { self.assume_init() }),
571             Err(err) => Err(err),
572         }
573     }
574 
575     /// Pin-initialize `self` using the given pin-initializer.
576     pub fn pin_init_with<E>(
577         mut self,
578         init: impl PinInit<T, E>,
579     ) -> core::result::Result<Pin<UniqueArc<T>>, E> {
580         // SAFETY: The supplied pointer is valid for initialization and we will later pin the value
581         // to ensure it does not move.
582         match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
583             // SAFETY: Initialization completed successfully.
584             Ok(()) => Ok(unsafe { self.assume_init() }.into()),
585             Err(err) => Err(err),
586         }
587     }
588 }
589 
590 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {
591     fn from(obj: UniqueArc<T>) -> Self {
592         // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T`
593         // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`.
594         unsafe { Pin::new_unchecked(obj) }
595     }
596 }
597 
598 impl<T: ?Sized> Deref for UniqueArc<T> {
599     type Target = T;
600 
601     fn deref(&self) -> &Self::Target {
602         self.inner.deref()
603     }
604 }
605 
606 impl<T: ?Sized> DerefMut for UniqueArc<T> {
607     fn deref_mut(&mut self) -> &mut Self::Target {
608         // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so
609         // it is safe to dereference it. Additionally, we know there is only one reference when
610         // it's inside a `UniqueArc`, so it is safe to get a mutable reference.
611         unsafe { &mut self.inner.ptr.as_mut().data }
612     }
613 }
614 
615 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
616     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617         fmt::Display::fmt(self.deref(), f)
618     }
619 }
620 
621 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> {
622     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623         fmt::Display::fmt(self.deref(), f)
624     }
625 }
626 
627 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> {
628     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629         fmt::Debug::fmt(self.deref(), f)
630     }
631 }
632 
633 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> {
634     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635         fmt::Debug::fmt(self.deref(), f)
636     }
637 }
638