From ee615ec9ba2d80152592da79071d9d603ec39a9d Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Sat, 8 Apr 2023 12:26:33 +0000 Subject: [PATCH] rust: sync: add functions for initializing `UniqueArc>` Add two functions `init_with` and `pin_init_with` to `UniqueArc>` to initialize the memory of already allocated `UniqueArc`s. This is useful when you want to allocate memory check some condition inside of a context where allocation is forbidden and then conditionally initialize an object. Signed-off-by: Benno Lossin Reviewed-by: Gary Guo Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Link: https://lore.kernel.org/r/20230408122429.1103522-16-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index de36d55e81d86..e6d2062424652 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -544,6 +544,30 @@ impl UniqueArc> { inner: unsafe { Arc::from_inner(inner.cast()) }, } } + + /// Initialize `self` using the given initializer. + pub fn init_with(mut self, init: impl Init) -> core::result::Result, E> { + // SAFETY: The supplied pointer is valid for initialization. + match unsafe { init.__init(self.as_mut_ptr()) } { + // SAFETY: Initialization completed successfully. + Ok(()) => Ok(unsafe { self.assume_init() }), + Err(err) => Err(err), + } + } + + /// Pin-initialize `self` using the given pin-initializer. + pub fn pin_init_with( + mut self, + init: impl PinInit, + ) -> core::result::Result>, E> { + // SAFETY: The supplied pointer is valid for initialization and we will later pin the value + // to ensure it does not move. + match unsafe { init.__pinned_init(self.as_mut_ptr()) } { + // SAFETY: Initialization completed successfully. + Ok(()) => Ok(unsafe { self.assume_init() }.into()), + Err(err) => Err(err), + } + } } impl From> for Pin> {