Re: [PATCH v15 1/7] rust: sync: add `SetOnce`
From: Benno Lossin
Date: Tue Jul 08 2025 - 05:04:17 EST
On Mon Jul 7, 2025 at 3:29 PM CEST, Andreas Hindborg wrote:
> Introduce the `SetOnce` type, a container that can only be written once.
> The container uses an internal atomic to synchronize writes to the internal
> value.
>
> Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
One nit and a safety comment fix below. (feel free to ignore the nit)
With the safety comment fixed:
Reviewed-by: Benno Lossin <lossin@xxxxxxxxxx>
> ---
> rust/kernel/sync.rs | 2 +
> rust/kernel/sync/set_once.rs | 125 +++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 127 insertions(+)
>
> diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs
> index 81e3a806e57e2..13e6bc7fa87ac 100644
> --- a/rust/kernel/sync.rs
> +++ b/rust/kernel/sync.rs
> @@ -18,6 +18,7 @@
> mod locked_by;
> pub mod poll;
> pub mod rcu;
> +mod set_once;
I would have named this `once`.
> pub use arc::{Arc, ArcBorrow, UniqueArc};
> pub use completion::Completion;
> + /// Get a reference to the contained object.
> + ///
> + /// Returns [`None`] if this [`SetOnce`] is empty.
> + pub fn as_ref(&self) -> Option<&T> {
> + if self.init.load(Acquire) == 2 {
> + // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
> + // contains a valid value.
And the type invariants also ensure that the value of `self.init`
doesn't change.
So probably
// SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
// contains a valid value. They also guarantee that `self.init` doesn't change.
If you come up with something better, feel free to use it.
---
Cheers,
Benno
> + Some(unsafe { &*self.value.get() })
> + } else {
> + None
> + }
> + }