From 31d95c2f99bf16e59b996cf6a227e198a64e835c Mon Sep 17 00:00:00 2001 From: Asahi Lina Date: Mon, 3 Apr 2023 19:01:12 +0900 Subject: [PATCH] rust: sync: arc: Add UniqueArc::assume_init() We can already create `UniqueArc>` instances with `UniqueArc::try_new_uninit()` and write to them with `write()`. Add the missing unsafe `assume_init()` function to promote it to `UniqueArc`, so users can do piece-wise initialization of the contents instead of doing it all at once as long as they keep the invariants (the same requirements as `MaybeUninit::assume_init()`). This mirrors the std `Arc::assume_init()` function. In the kernel, since we have `UniqueArc`, arguably this only belongs there since most use cases will initialize it immediately after creating it, before demoting it to `Arc` to share it. [ Miguel: The "Rust pin-init API for pinned initialization of structs" patch series [1] from Benno Lossin contains a very similar patch: rust: sync: add `assume_init` to `UniqueArc` Adds the `assume_init` function to `UniqueArc>` that unsafely assumes the value to be initialized and yields a value of type `UniqueArc`. This function is used when manually initializing the pointee of an `UniqueArc`. To make that patch a noop and thus drop it, I adjusted the `SAFETY` comment here to be the same as in the current latest version of that series (v7). I have also brought the `Reviewed-by`s there into here, and reworded the `Co-authored-by` into `Co-developed-by`. ] Link: https://lore.kernel.org/r/20230408122429.1103522-5-y86-dev@protonmail.com [1] Co-developed-by: Benno Lossin Signed-off-by: Benno Lossin Signed-off-by: Asahi Lina Reviewed-by: Gary Guo Reviewed-by: Wedson Almeida Filho Reviewed-by: Andreas Hindborg Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20230224-rust-arc-v2-2-5c97a865b276@asahilina.net Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 4ab9b28..8ce6d6b 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -492,6 +492,17 @@ impl UniqueArc> { /// Converts a `UniqueArc>` into a `UniqueArc` by writing a value into it. pub fn write(mut self, value: T) -> UniqueArc { self.deref_mut().write(value); + // SAFETY: We just wrote the value to be initialized. + unsafe { self.assume_init() } + } + + /// Unsafely assume that `self` is initialized. + /// + /// # Safety + /// + /// The caller guarantees that the value behind this pointer has been initialized. It is + /// *immediate* UB to call this when the value is not initialized. + pub unsafe fn assume_init(self) -> UniqueArc { let inner = ManuallyDrop::new(self).inner.ptr; UniqueArc { // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be -- 2.7.4