[v6.1] rust: types: add `Opaque::pin_init`

Message ID 20230406065546.787669-1-y86-dev@protonmail.com
State New
Headers
Series [v6.1] rust: types: add `Opaque::pin_init` |

Commit Message

y86-dev April 6, 2023, 6:56 a.m. UTC
  Add support for pin-init in combination with `Opaque<T>`, the `pin_init`
function initializes the contents via a user-supplied initializer for
`T`.

Signed-off-by: Benno Lossin <y86-dev@protonmail.com>
Cc: Alice Ryhl <aliceryhl@google.com>
Cc: Andreas Hindborg <a.hindborg@samsung.com>
Cc: Gary Guo <gary@garyguo.net>
---
 rust/kernel/init.rs  |  3 +++
 rust/kernel/types.rs | 18 ++++++++++++++++++
 2 files changed, 21 insertions(+)

--
2.39.2
  

Patch

diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs
index ffd539e2f5ef..23d879e53b26 100644
--- a/rust/kernel/init.rs
+++ b/rust/kernel/init.rs
@@ -177,6 +177,9 @@ 
 //! }
 //! ```
 //!
+//! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
+//! the `kernel` crate. The [`sync`] module is a good starting point.
+//!
 //! [`sync`]: kernel::sync
 //! [pinning]: https://doc.rust-lang.org/std/pin/index.html
 //! [structurally pinned fields]:
diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index ff2b2fac951d..cf1cbd6a1447 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -2,6 +2,7 @@ 

 //! Kernel types.

+use crate::init::{self, PinInit};
 use alloc::boxed::Box;
 use core::{
     cell::UnsafeCell,
@@ -234,6 +235,23 @@  impl<T> Opaque<T> {
         Self(MaybeUninit::uninit())
     }

+    /// Creates a pin-initializer for `Opaque<T>`.
+    ///
+    /// # Safety
+    ///
+    /// [`PinInit<T, E>`] promises that the [`Pin` `Drop` guarantee] is upheld for the type `T` if
+    /// initialization succeeds. `Opaque` is a wrapper that allows holding uninitialized values of
+    /// `T`, so it does not drop the `T` when it is dropped. When calling this function the caller
+    /// needs to guarantee that:
+    /// - either `T` does not have drop glue ([`core::mem::needs_drop`] retuns `false`),
+    /// - or the caller ensures the drop guarantee manually.
+    ///
+    /// [`Pin` `Drop` guarantee]: https://doc.rust-lang.org/core/pin/index.html#drop-guarantee
+    pub unsafe fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
+        // SAFETY: `init` initializes the only field of this struct.
+        unsafe { init::pin_init_from_closure(|slot| init.__pinned_init(Self::raw_get(slot))) }
+    }
+
     /// Returns a raw pointer to the opaque data.
     pub fn get(&self) -> *mut T {
         UnsafeCell::raw_get(self.0.as_ptr())