Skip to content

Commit a69dc41

Browse files
Darksonngregkh
authored andcommitted
rust: types: add Opaque::try_ffi_init
This will be used by the miscdevice abstractions, as the C function `misc_register` is fallible. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Fiona Behrens <me@kloenk.dev> Link: https://lore.kernel.org/r/20241001-b4-miscdevice-v2-1-330d760041fa@google.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
1 parent 8cf0b93 commit a69dc41

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

rust/kernel/types.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,22 @@ impl<T> Opaque<T> {
299299
}
300300
}
301301

302+
/// Creates a fallible pin-initializer from the given initializer closure.
303+
///
304+
/// The returned initializer calls the given closure with the pointer to the inner `T` of this
305+
/// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
306+
///
307+
/// This function is safe, because the `T` inside of an `Opaque` is allowed to be
308+
/// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
309+
/// to verify at that point that the inner value is valid.
310+
pub fn try_ffi_init<E>(
311+
init_func: impl FnOnce(*mut T) -> Result<(), E>,
312+
) -> impl PinInit<Self, E> {
313+
// SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
314+
// initialize the `T`.
315+
unsafe { init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) }
316+
}
317+
302318
/// Returns a raw pointer to the opaque data.
303319
pub const fn get(&self) -> *mut T {
304320
UnsafeCell::get(&self.value).cast::<T>()

0 commit comments

Comments
 (0)