rust: alloc: allow different error types in KBox::pin_slice

Previously, `KBox::pin_slice` required the initializer error type to match
the return error type via `E: From<AllocError>`. This prevented using
infallible initializers like `new_mutex!` inside `pin_slice`, because
`Infallible` does not implement `From<AllocError>`.

Introduce a separate type parameter `E2` for the initializer error type
and require `E: From<AllocError>` and `E: From<E2>` instead. This allows
the initializer to return a different error type that can be converted
into the final error type, enabling use of infallible pin initializers
in fallible allocation contexts.

Link: https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/.E2.9C.94.20Constructing.20Mutex.20from.20PinInit.3CT.2C.20Error.3E
Co-developed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Link: https://patch.msgid.link/20260605-pin-slice-init-v2-1-b197e84040ba@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
This commit is contained in:
Andreas Hindborg 2026-06-05 12:56:31 +02:00 committed by Danilo Krummrich
parent 82134823a0
commit d190aa2094

View File

@ -345,7 +345,7 @@ pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
/// }
///
/// // Allocate a boxed slice of 10 `Example`s.
/// let s = KBox::pin_slice(
/// let s = KBox::pin_slice::<_, _, Error, _>(
/// | _i | Example::new(),
/// 10,
/// GFP_KERNEL
@ -355,15 +355,16 @@ pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
/// assert_eq!(s[3].d.lock().a, 20);
/// # Ok::<(), Error>(())
/// ```
pub fn pin_slice<Func, Item, E>(
pub fn pin_slice<Func, Item, E, E2>(
mut init: Func,
len: usize,
flags: Flags,
) -> Result<Pin<Box<[T], A>>, E>
where
Func: FnMut(usize) -> Item,
Item: PinInit<T, E>,
Item: PinInit<T, E2>,
E: From<AllocError>,
E: From<E2>,
{
let mut buffer = super::Vec::<T, A>::with_capacity(len, flags)?;
for i in 0..len {