Skip to content

Commit 901e416

Browse files
committed
rust: arc: add new ArcBorrow docs and examples
This is part of the effort to minimize the differences of the `rust` branch with respect to mainline in order to eventually drop it. Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 003d799 commit 901e416

File tree

1 file changed

+50
-3
lines changed

1 file changed

+50
-3
lines changed

rust/kernel/sync/arc.rs

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,12 +378,59 @@ impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> {
378378
}
379379
}
380380

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.
382391
///
383392
/// # Invariants
384393
///
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+
/// ```
387434
pub struct ArcBorrow<'a, T: ?Sized + 'a> {
388435
inner: NonNull<ArcInner<T>>,
389436
_p: PhantomData<&'a ()>,

0 commit comments

Comments
 (0)