[PATCH v3 1/2] rust: non_empty: add NonEmpty

From: Lorenzo Delgado

Date: Wed Oct 14 2026 - 04:38:42 EST


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 whose constructors check that
the container is not 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 and arrays are supported. A slice of unknown
length goes through `try_from_mut()`, which returns `None` if it is
empty. An array goes through `from_mut()`, which checks the length at
compile time instead of returning an `Option`. The resulting
`&mut NonEmpty<[T; N]>` coerces to `&mut NonEmpty<[T]>`, so a caller
with a fixed-size buffer needs no runtime check and no extra cast. 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 | 123 +++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 124 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
@@ -105,6 +105,7 @@
pub mod module_param;
#[cfg(CONFIG_NET)]
pub mod net;
+pub mod non_empty;
pub mod num;
pub mod of;
#[cfg(CONFIG_PM_OPP)]
diff --git a/rust/kernel/non_empty.rs b/rust/kernel/non_empty.rs
new file mode 100644
index 000000000000..5eec67a4f8a7
--- /dev/null
+++ b/rust/kernel/non_empty.rs
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Containers that are known not to be empty.
+
+use crate::build_assert::const_assert;
+use core::ops::{
+ Deref,
+ DerefMut, //
+};
+
+/// A container that can report whether it holds any element.
+///
+/// The result must not change while the container is only reachable through a shared reference.
+///
+/// Unsafe code may only rely on the result for a container type whose implementation it trusts,
+/// such as the ones in this module, since a safe implementation can return anything.
+pub trait IsEmpty {
+ /// Returns `true` if the container holds no element.
+ fn is_empty(&self) -> bool;
+}
+
+impl<T> IsEmpty for [T] {
+ #[inline]
+ fn is_empty(&self) -> bool {
+ <[T]>::is_empty(self)
+ }
+}
+
+/// A container that holds at least one element.
+///
+/// [`NonEmpty`] dereferences to the container it wraps, so the container's API stays available.
+/// Methods whose result is only optional because the container could be empty can be shadowed by
+/// versions that return the result directly. They are added as users need them. For now that is
+/// only [`NonEmpty::last_mut`] on a slice, which returns `&mut T` instead of `Option<&mut T>`.
+///
+/// # Invariants
+///
+/// The wrapped container is not empty. Unsafe code may rely on this only for arrays and for
+/// container types whose [`IsEmpty`] implementation is in this module.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::non_empty::NonEmpty;
+///
+/// let mut buf = [1u8, 2, 3];
+/// let slice: &mut NonEmpty<[u8]> = NonEmpty::from_mut(&mut buf);
+/// *slice.last_mut() = 0;
+/// assert_eq!(slice.len(), 3);
+/// assert_eq!(buf, [1, 2, 0]);
+///
+/// let mut buf = [1u8, 2, 3];
+/// let slice = NonEmpty::try_from_mut(&mut buf[..2]).ok_or(EINVAL)?;
+/// *slice.last_mut() = 0;
+/// assert_eq!(buf, [1, 0, 3]);
+///
+/// let mut empty: [u8; 0] = [];
+/// assert!(NonEmpty::try_from_mut(&mut empty[..]).is_none());
+/// # Ok::<(), Error>(())
+/// ```
+#[repr(transparent)]
+#[derive(Debug)]
+pub struct NonEmpty<C: ?Sized>(C);
+
+impl<C: ?Sized + IsEmpty> NonEmpty<C> {
+ /// Creates a [`NonEmpty`] from a mutable reference to a container, or returns [`None`] if the
+ /// container is empty.
+ #[inline]
+ pub fn try_from_mut(container: &mut C) -> Option<&mut Self> {
+ if container.is_empty() {
+ return None;
+ }
+
+ // INVARIANT: `container` was checked to be non-empty above.
+ // SAFETY: `NonEmpty<C>` is transparent to `C`, so the cast keeps both the layout and the
+ // pointer metadata, and the pointer comes from a valid `&mut C` with the same lifetime.
+ Some(unsafe { &mut *(core::ptr::from_mut(container) as *mut Self) })
+ }
+}
+
+impl<T, const N: usize> NonEmpty<[T; N]> {
+ /// Creates a [`NonEmpty`] array 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. The result
+ /// coerces to a [`NonEmpty`] slice, which is where its accessors are.
+ #[inline]
+ pub const fn from_mut(array: &mut [T; N]) -> &mut Self {
+ const_assert!(N > 0);
+
+ // INVARIANT: `array` has `N` elements, and `N > 0` was checked at compile time.
+ // SAFETY: `NonEmpty<[T; N]>` is transparent to `[T; N]`, so the cast keeps the layout, and
+ // the pointer comes from a valid `&mut [T; N]` with the same lifetime.
+ unsafe { &mut *core::ptr::from_mut(array).cast::<Self>() }
+ }
+}
+
+impl<T> NonEmpty<[T]> {
+ /// Returns a mutable reference to the last element of the slice.
+ #[inline]
+ pub fn last_mut(&mut self) -> &mut T {
+ // SAFETY: By the type invariant, the slice is not empty, so it has a last element.
+ unsafe { self.0.last_mut().unwrap_unchecked() }
+ }
+}
+
+impl<C: ?Sized> Deref for NonEmpty<C> {
+ type Target = C;
+
+ #[inline]
+ fn deref(&self) -> &C {
+ &self.0
+ }
+}
+
+// `DerefMut` is only sound for containers whose length cannot change through a mutable
+// reference. For a growable container such as `KVec`, `clear()` would empty it.
+impl<T> DerefMut for NonEmpty<[T]> {
+ #[inline]
+ fn deref_mut(&mut self) -> &mut [T] {
+ &mut self.0
+ }
+}

--
2.55.0