Skip to content

Commit ffa6a7f

Browse files
y86-devojeda
authored andcommitted
rust: sync: add functions for initializing UniqueArc<MaybeUninit<T>>
Add two functions `init_with` and `pin_init_with` to `UniqueArc<MaybeUninit<T>>` 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 <[email protected]> Reviewed-by: Gary Guo <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Andreas Hindborg <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 9f5e526 commit ffa6a7f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Diff for: rust/kernel/sync/arc.rs

+24
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,30 @@ impl<T> UniqueArc<MaybeUninit<T>> {
544544
inner: unsafe { Arc::from_inner(inner.cast()) },
545545
}
546546
}
547+
548+
/// Initialize `self` using the given initializer.
549+
pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> {
550+
// SAFETY: The supplied pointer is valid for initialization.
551+
match unsafe { init.__init(self.as_mut_ptr()) } {
552+
// SAFETY: Initialization completed successfully.
553+
Ok(()) => Ok(unsafe { self.assume_init() }),
554+
Err(err) => Err(err),
555+
}
556+
}
557+
558+
/// Pin-initialize `self` using the given pin-initializer.
559+
pub fn pin_init_with<E>(
560+
mut self,
561+
init: impl PinInit<T, E>,
562+
) -> core::result::Result<Pin<UniqueArc<T>>, E> {
563+
// SAFETY: The supplied pointer is valid for initialization and we will later pin the value
564+
// to ensure it does not move.
565+
match unsafe { init.__pinned_init(self.as_mut_ptr()) } {
566+
// SAFETY: Initialization completed successfully.
567+
Ok(()) => Ok(unsafe { self.assume_init() }.into()),
568+
Err(err) => Err(err),
569+
}
570+
}
547571
}
548572

549573
impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> {

0 commit comments

Comments
 (0)