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. Additionally, the safety requirements of 250 // `ForeignOwnable::borrow_mut` ensure that no new mutable references are created. 251 unsafe { ArcBorrow::new(inner) } 252 } 253 254 unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { 255 // SAFETY: By the safety requirement of this function, we know that `ptr` came from 256 // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and 257 // holds a reference count increment that is transferrable to us. 258 unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) } 259 } 260 } 261 262 impl<T: ?Sized> Deref for Arc<T> { 263 type Target = T; 264 265 fn deref(&self) -> &Self::Target { 266 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 267 // safe to dereference it. 268 unsafe { &self.ptr.as_ref().data } 269 } 270 } 271 272 impl<T: ?Sized> AsRef<T> for Arc<T> { 273 fn as_ref(&self) -> &T { 274 self.deref() 275 } 276 } 277 278 impl<T: ?Sized> Clone for Arc<T> { 279 fn clone(&self) -> Self { 280 // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero. 281 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 282 // safe to increment the refcount. 283 unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) }; 284 285 // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. 286 unsafe { Self::from_inner(self.ptr) } 287 } 288 } 289 290 impl<T: ?Sized> Drop for Arc<T> { 291 fn drop(&mut self) { 292 // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot 293 // touch `refcount` after it's decremented to a non-zero value because another thread/CPU 294 // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to 295 // freed/invalid memory as long as it is never dereferenced. 296 let refcount = unsafe { self.ptr.as_ref() }.refcount.get(); 297 298 // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and 299 // this instance is being dropped, so the broken invariant is not observable. 300 // SAFETY: Also by the type invariant, we are allowed to decrement the refcount. 301 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) }; 302 if is_zero { 303 // The count reached zero, we must free the memory. 304 // 305 // SAFETY: The pointer was initialised from the result of `Box::leak`. 306 unsafe { Box::from_raw(self.ptr.as_ptr()) }; 307 } 308 } 309 } 310 311 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> { 312 fn from(item: UniqueArc<T>) -> Self { 313 item.inner 314 } 315 } 316 317 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> { 318 fn from(item: Pin<UniqueArc<T>>) -> Self { 319 // SAFETY: The type invariants of `Arc` guarantee that the data is pinned. 320 unsafe { Pin::into_inner_unchecked(item).inner } 321 } 322 } 323 324 /// A borrowed reference to an [`Arc`] instance. 325 /// 326 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler 327 /// to use just `&T`, which we can trivially get from an `Arc<T>` instance. 328 /// 329 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` 330 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) 331 /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double 332 /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if 333 /// needed. 334 /// 335 /// # Invariants 336 /// 337 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the 338 /// lifetime of the [`ArcBorrow`] instance. 339 /// 340 /// # Example 341 /// 342 /// ``` 343 /// use kernel::sync::{Arc, ArcBorrow}; 344 /// 345 /// struct Example; 346 /// 347 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { 348 /// e.into() 349 /// } 350 /// 351 /// let obj = Arc::try_new(Example)?; 352 /// let cloned = do_something(obj.as_arc_borrow()); 353 /// 354 /// // Assert that both `obj` and `cloned` point to the same underlying object. 355 /// assert!(core::ptr::eq(&*obj, &*cloned)); 356 /// # Ok::<(), Error>(()) 357 /// ``` 358 /// 359 /// Using `ArcBorrow<T>` as the type of `self`: 360 /// 361 /// ``` 362 /// use kernel::sync::{Arc, ArcBorrow}; 363 /// 364 /// struct Example { 365 /// a: u32, 366 /// b: u32, 367 /// } 368 /// 369 /// impl Example { 370 /// fn use_reference(self: ArcBorrow<'_, Self>) { 371 /// // ... 372 /// } 373 /// } 374 /// 375 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?; 376 /// obj.as_arc_borrow().use_reference(); 377 /// # Ok::<(), Error>(()) 378 /// ``` 379 pub struct ArcBorrow<'a, T: ?Sized + 'a> { 380 inner: NonNull<ArcInner<T>>, 381 _p: PhantomData<&'a ()>, 382 } 383 384 // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`. 385 impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {} 386 387 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into 388 // `ArcBorrow<U>`. 389 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>> 390 for ArcBorrow<'_, T> 391 { 392 } 393 394 impl<T: ?Sized> Clone for ArcBorrow<'_, T> { 395 fn clone(&self) -> Self { 396 *self 397 } 398 } 399 400 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} 401 402 impl<T: ?Sized> ArcBorrow<'_, T> { 403 /// Creates a new [`ArcBorrow`] instance. 404 /// 405 /// # Safety 406 /// 407 /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: 408 /// 1. That `inner` remains valid; 409 /// 2. That no mutable references to `inner` are created. 410 unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { 411 // INVARIANT: The safety requirements guarantee the invariants. 412 Self { 413 inner, 414 _p: PhantomData, 415 } 416 } 417 } 418 419 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { 420 fn from(b: ArcBorrow<'_, T>) -> Self { 421 // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` 422 // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the 423 // increment. 424 ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) 425 .deref() 426 .clone() 427 } 428 } 429 430 impl<T: ?Sized> Deref for ArcBorrow<'_, T> { 431 type Target = T; 432 433 fn deref(&self) -> &Self::Target { 434 // SAFETY: By the type invariant, the underlying object is still alive with no mutable 435 // references to it, so it is safe to create a shared reference. 436 unsafe { &self.inner.as_ref().data } 437 } 438 } 439 440 /// A refcounted object that is known to have a refcount of 1. 441 /// 442 /// It is mutable and can be converted to an [`Arc`] so that it can be shared. 443 /// 444 /// # Invariants 445 /// 446 /// `inner` always has a reference count of 1. 447 /// 448 /// # Examples 449 /// 450 /// In the following example, we make changes to the inner object before turning it into an 451 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()` 452 /// cannot fail. 453 /// 454 /// ``` 455 /// use kernel::sync::{Arc, UniqueArc}; 456 /// 457 /// struct Example { 458 /// a: u32, 459 /// b: u32, 460 /// } 461 /// 462 /// fn test() -> Result<Arc<Example>> { 463 /// let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?; 464 /// x.a += 1; 465 /// x.b += 1; 466 /// Ok(x.into()) 467 /// } 468 /// 469 /// # test().unwrap(); 470 /// ``` 471 /// 472 /// In the following example we first allocate memory for a ref-counted `Example` but we don't 473 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`], 474 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens 475 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic): 476 /// 477 /// ``` 478 /// use kernel::sync::{Arc, UniqueArc}; 479 /// 480 /// struct Example { 481 /// a: u32, 482 /// b: u32, 483 /// } 484 /// 485 /// fn test() -> Result<Arc<Example>> { 486 /// let x = UniqueArc::try_new_uninit()?; 487 /// Ok(x.write(Example { a: 10, b: 20 }).into()) 488 /// } 489 /// 490 /// # test().unwrap(); 491 /// ``` 492 /// 493 /// In the last example below, the caller gets a pinned instance of `Example` while converting to 494 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during 495 /// initialisation, for example, when initialising fields that are wrapped in locks. 496 /// 497 /// ``` 498 /// use kernel::sync::{Arc, UniqueArc}; 499 /// 500 /// struct Example { 501 /// a: u32, 502 /// b: u32, 503 /// } 504 /// 505 /// fn test() -> Result<Arc<Example>> { 506 /// let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?); 507 /// // We can modify `pinned` because it is `Unpin`. 508 /// pinned.as_mut().a += 1; 509 /// Ok(pinned.into()) 510 /// } 511 /// 512 /// # test().unwrap(); 513 /// ``` 514 pub struct UniqueArc<T: ?Sized> { 515 inner: Arc<T>, 516 } 517 518 impl<T> UniqueArc<T> { 519 /// Tries to allocate a new [`UniqueArc`] instance. 520 pub fn try_new(value: T) -> Result<Self, AllocError> { 521 Ok(Self { 522 // INVARIANT: The newly-created object has a ref-count of 1. 523 inner: Arc::try_new(value)?, 524 }) 525 } 526 527 /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. 528 pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>, AllocError> { 529 // INVARIANT: The refcount is initialised to a non-zero value. 530 let inner = Box::try_init::<AllocError>(try_init!(ArcInner { 531 // SAFETY: There are no safety requirements for this FFI call. 532 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), 533 data <- init::uninit::<T, AllocError>(), 534 }? AllocError))?; 535 Ok(UniqueArc { 536 // INVARIANT: The newly-created object has a ref-count of 1. 537 // SAFETY: The pointer from the `Box` is valid. 538 inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, 539 }) 540 } 541 } 542 543 impl<T> UniqueArc<MaybeUninit<T>> { 544 /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it. 545 pub fn write(mut self, value: T) -> UniqueArc<T> { 546 self.deref_mut().write(value); 547 // SAFETY: We just wrote the value to be initialized. 548 unsafe { self.assume_init() } 549 } 550 551 /// Unsafely assume that `self` is initialized. 552 /// 553 /// # Safety 554 /// 555 /// The caller guarantees that the value behind this pointer has been initialized. It is 556 /// *immediate* UB to call this when the value is not initialized. 557 pub unsafe fn assume_init(self) -> UniqueArc<T> { 558 let inner = ManuallyDrop::new(self).inner.ptr; 559 UniqueArc { 560 // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be 561 // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`. 562 inner: unsafe { Arc::from_inner(inner.cast()) }, 563 } 564 } 565 566 /// Initialize `self` using the given initializer. 567 pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> { 568 // SAFETY: The supplied pointer is valid for initialization. 569 match unsafe { init.__init(self.as_mut_ptr()) } { 570 // SAFETY: Initialization completed successfully. 571 Ok(()) => Ok(unsafe { self.assume_init() }), 572 Err(err) => Err(err), 573 } 574 } 575 576 /// Pin-initialize `self` using the given pin-initializer. 577 pub fn pin_init_with<E>( 578 mut self, 579 init: impl PinInit<T, E>, 580 ) -> core::result::Result<Pin<UniqueArc<T>>, E> { 581 // SAFETY: The supplied pointer is valid for initialization and we will later pin the value 582 // to ensure it does not move. 583 match unsafe { init.__pinned_init(self.as_mut_ptr()) } { 584 // SAFETY: Initialization completed successfully. 585 Ok(()) => Ok(unsafe { self.assume_init() }.into()), 586 Err(err) => Err(err), 587 } 588 } 589 } 590 591 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> { 592 fn from(obj: UniqueArc<T>) -> Self { 593 // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T` 594 // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`. 595 unsafe { Pin::new_unchecked(obj) } 596 } 597 } 598 599 impl<T: ?Sized> Deref for UniqueArc<T> { 600 type Target = T; 601 602 fn deref(&self) -> &Self::Target { 603 self.inner.deref() 604 } 605 } 606 607 impl<T: ?Sized> DerefMut for UniqueArc<T> { 608 fn deref_mut(&mut self) -> &mut Self::Target { 609 // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so 610 // it is safe to dereference it. Additionally, we know there is only one reference when 611 // it's inside a `UniqueArc`, so it is safe to get a mutable reference. 612 unsafe { &mut self.inner.ptr.as_mut().data } 613 } 614 } 615 616 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> { 617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 618 fmt::Display::fmt(self.deref(), f) 619 } 620 } 621 622 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> { 623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 624 fmt::Display::fmt(self.deref(), f) 625 } 626 } 627 628 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> { 629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 630 fmt::Debug::fmt(self.deref(), f) 631 } 632 } 633 634 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> { 635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 636 fmt::Debug::fmt(self.deref(), f) 637 } 638 } 639