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