[v6.1] rust: types: add `Opaque::pin_init`
Commit Message
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
@@ -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]:
@@ -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())