Re: [PATCH v2 1/2] rust: non_empty: add NonEmpty

From: Gary Guo

Date: Tue Oct 13 2026 - 10:24:49 EST


On Tue Oct 13, 2026 at 2:49 PM BST, Lorenzo Delgado wrote:
> Some functions reject an empty container up front and later rely on it
> having at least one element. The type system does not see that check,
> so the later access ends up as an `unwrap_unchecked()` with a SAFETY
> comment pointing back at it, or as an `unwrap()` or an error path that
> can never be taken. `strcpy_into_buf()` in uaccess is one such case.
>
> Add `NonEmpty<C>`, a transparent wrapper that can only be created from
> a container its `IsEmpty` implementation reports as non-empty. It
> dereferences to the container, and a method whose `Option` only exists
> for the empty case can be shadowed by a version that returns the value
> directly.
>
> `DerefMut` is implemented per container, only where a mutable reference
> cannot change the length. For a growable container it would let
> `clear()` break the invariant.
>
> For now only slices are supported. A slice of unknown length goes
> through `try_from_mut()`, which returns `None` if it is empty. An array
> goes through `from_array_mut()`, which checks the length at compile
> time instead of returning an `Option`, so a caller with a fixed-size
> buffer needs no runtime check. The only accessor is `last_mut()`,
> which uaccess needs. Other containers and accessors can follow with
> their users.
>
> Suggested-by: Gary Guo <gary@xxxxxxxxxxx>
> Link: https://lore.kernel.org/rust-for-linux/DM0D9TERQAM3.2Y3HV6P68E2N8@xxxxxxxxxxx/
> Link: https://github.com/Rust-for-Linux/linux/issues/1262
> Signed-off-by: Lorenzo Delgado <lnsdev@xxxxxxxxx>
> ---
> rust/kernel/lib.rs | 1 +
> rust/kernel/non_empty.rs | 122 +++++++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 123 insertions(+)
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 7225abc64084..8e1928deac35 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
>
> +impl<T> NonEmpty<[T]> {
> + /// Creates a [`NonEmpty`] slice from a mutable reference to an array.
> + ///
> + /// Unlike [`NonEmpty::try_from_mut`], this does not return an [`Option`]: the array length is
> + /// checked at compile time, and using it with an empty array is a build error.
> + #[inline]
> + pub fn from_array_mut<const N: usize>(array: &mut [T; N]) -> &mut Self {

Construction of array should be of form

&&mut [T; N] --construct--> &mut NonEmpty<[T; N]> --unsize coercion--> &mut NonEmpty<[T]>

Best,
Gary

> + const_assert!(N > 0);
> +
> + let slice: &mut [T] = array;
> + // INVARIANT: `slice` has `N` elements, and `N > 0` was checked at compile time.
> + // SAFETY: `NonEmpty<[T]>` is transparent to `[T]`, so the cast keeps both the layout and
> + // the pointer metadata, and the pointer comes from a valid `&mut [T]` with the same
> + // lifetime.
> + unsafe { &mut *(core::ptr::from_mut(slice) as *mut Self) }
> + }