Skip to content

Commit

Permalink
rust: sync: allow type of self to be Arc<T> or variants
Browse files Browse the repository at this point in the history
This allows associated functions whose `self` argument has `Arc<T>` or
variants as their type. This, in turn, allows callers to use the dot
syntax to make calls.

Signed-off-by: Wedson Almeida Filho <[email protected]>
Reviewed-by: Alice Ryhl <[email protected]>
Reviewed-by: Gary Guo <[email protected]>
Reviewed-by: Vincenzo Palazzo <[email protected]>
Acked-by: Boqun Feng <[email protected]>
Signed-off-by: Miguel Ojeda <[email protected]>
  • Loading branch information
wedsonaf authored and ojeda committed Jan 16, 2023
1 parent 9dc0436 commit 5352877
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions rust/kernel/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#![no_std]
#![feature(allocator_api)]
#![feature(core_ffi_c)]
#![feature(receiver_trait)]

// Ensure conditional compilation based on the kernel configuration works;
// otherwise we may silently break things like initcall handling.
Expand Down
28 changes: 28 additions & 0 deletions rust/kernel/sync/arc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,31 @@ use core::{marker::PhantomData, ops::Deref, ptr::NonNull};
///
/// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed.
/// ```
///
/// Using `Arc<T>` as the type of `self`:
///
/// ```
/// use kernel::sync::Arc;
///
/// struct Example {
/// a: u32,
/// b: u32,
/// }
///
/// impl Example {
/// fn take_over(self: Arc<Self>) {
/// // ...
/// }
///
/// fn use_reference(self: &Arc<Self>) {
/// // ...
/// }
/// }
///
/// let obj = Arc::try_new(Example { a: 10, b: 20 })?;
/// obj.use_reference();
/// obj.take_over();
/// ```
pub struct Arc<T: ?Sized> {
ptr: NonNull<ArcInner<T>>,
_p: PhantomData<ArcInner<T>>,
Expand All @@ -68,6 +93,9 @@ struct ArcInner<T: ?Sized> {
data: T,
}

// This is to allow [`Arc`] (and variants) to be used as the type of `self`.
impl<T: ?Sized> core::ops::Receiver for Arc<T> {}

// SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because
// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
// `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` directly, for
Expand Down

0 comments on commit 5352877

Please sign in to comment.