@@ -378,12 +378,59 @@ impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
378
378
}
379
379
}
380
380
381
- /// A borrowed [`Arc`] with manually-managed lifetime.
381
+ /// A borrowed reference to an [`Arc`] instance.
382
+ ///
383
+ /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler
384
+ /// to use just `&T`, which we can trivially get from an `Arc<T>` instance.
385
+ ///
386
+ /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>`
387
+ /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference)
388
+ /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double
389
+ /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if
390
+ /// needed.
382
391
///
383
392
/// # Invariants
384
393
///
385
- /// There are no mutable references to the underlying [`Arc`], and it remains valid for the lifetime
386
- /// of the [`ArcBorrow`] instance.
394
+ /// There are no mutable references to the underlying [`Arc`], and it remains valid for the
395
+ /// lifetime of the [`ArcBorrow`] instance.
396
+ ///
397
+ /// # Example
398
+ ///
399
+ /// ```
400
+ /// use crate::sync::{Arc, ArcBorrow};
401
+ ///
402
+ /// struct Example;
403
+ ///
404
+ /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> {
405
+ /// e.into()
406
+ /// }
407
+ ///
408
+ /// let obj = Arc::try_new(Example)?;
409
+ /// let cloned = do_something(obj.as_arc_borrow());
410
+ ///
411
+ /// // Assert that both `obj` and `cloned` point to the same underlying object.
412
+ /// assert!(core::ptr::eq(&*obj, &*cloned));
413
+ /// ```
414
+ ///
415
+ /// Using `ArcBorrow<T>` as the type of `self`:
416
+ ///
417
+ /// ```
418
+ /// use crate::sync::{Arc, ArcBorrow};
419
+ ///
420
+ /// struct Example {
421
+ /// a: u32,
422
+ /// b: u32,
423
+ /// }
424
+ ///
425
+ /// impl Example {
426
+ /// fn use_reference(self: ArcBorrow<'_, Self>) {
427
+ /// // ...
428
+ /// }
429
+ /// }
430
+ ///
431
+ /// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
432
+ /// obj.as_arc_borrow().use_reference();
433
+ /// ```
387
434
pub struct ArcBorrow < ' a , T : ?Sized + ' a > {
388
435
inner : NonNull < ArcInner < T > > ,
389
436
_p : PhantomData < & ' a ( ) > ,
0 commit comments