]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
rust: pin-init: Implement `InPlaceWrite<T>` for `&'static mut MaybeUninit<T>`
authorOleksandr Babak <alexanderbabak@proton.me>
Thu, 8 Jan 2026 12:43:16 +0000 (13:43 +0100)
committerBenno Lossin <lossin@kernel.org>
Sat, 17 Jan 2026 09:53:28 +0000 (10:53 +0100)
This feature allows users to use `&'static mut MaybeUninit<T>` as a
place to initialize the value. It mirrors an existing implemetation
for `Box<MaybeUninit>`, but enables users to use external allocation
mechanisms such as `static_cell` [1].

Signed-off-by: Oleksandr Babak <alexanderbabak@proton.me>
Link: https://crates.io/crates/static_cell
[ Added link to `static_cell` - Benno ]
Signed-off-by: Benno Lossin <lossin@kernel.org>
rust/pin-init/src/lib.rs

index 780b4fead22d9e05dad7ae6133e0fa5205caa01e..49945fc07f2592e33e61b7588d487fc708e88df4 100644 (file)
@@ -1403,6 +1403,33 @@ pub trait InPlaceWrite<T> {
     fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
 }
 
+impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
+    type Initialized = &'static mut T;
+
+    fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
+        let slot = self.as_mut_ptr();
+
+        // SAFETY: `slot` is a valid pointer to uninitialized memory.
+        unsafe { init.__init(slot)? };
+
+        // SAFETY: The above call initialized the memory.
+        unsafe { Ok(self.assume_init_mut()) }
+    }
+
+    fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
+        let slot = self.as_mut_ptr();
+
+        // SAFETY: `slot` is a valid pointer to uninitialized memory.
+        //
+        // The `'static` borrow guarantees the data will not be
+        // moved/invalidated until it gets dropped (which is never).
+        unsafe { init.__pinned_init(slot)? };
+
+        // SAFETY: The above call initialized the memory.
+        Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
+    }
+}
+
 /// Trait facilitating pinned destruction.
 ///
 /// Use [`pinned_drop`] to implement this trait safely: