mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Lorenzo Delgado <lnsdev@proton.me>
Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	Thorsten Blum <blum@kernel.org>,
	Francis Laniel <laniel_francis@npnm.eu>,
	Lorenzo Delgado <lnsdev@proton.me>
Subject: [PATCH 1/2] rust: non_empty: add NonEmpty
Date: Mon, 12 Oct 2026 11:46:26 +0000	[thread overview]
Message-ID: <20261012-nonempty-slice-v1-1-4a15dee398dd@proton.me> (raw)
In-Reply-To: <20261012-nonempty-slice-v1-0-4a15dee398dd@proton.me>

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, with the one constructor and
accessor that the uaccess conversion needs. Other containers and
accessors can follow with their users.

Suggested-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/rust-for-linux/DM0D9TERQAM3.2Y3HV6P68E2N8@garyguo.net/
Link: https://github.com/Rust-for-Linux/linux/issues/1262
Signed-off-by: Lorenzo Delgado <lnsdev@proton.me>
---
 rust/kernel/lib.rs       |   1 +
 rust/kernel/non_empty.rs | 100 +++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 101 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..9617414f51f9
--- /dev/null
+++ b/rust/kernel/non_empty.rs
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Containers that are known not to be empty.
+
+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 container types
+/// whose [`IsEmpty`] implementation is in this module.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::non_empty::NonEmpty;
+///
+/// let mut buf = [1u8, 2, 3];
+/// let slice = NonEmpty::try_from_mut(&mut buf[..]).ok_or(EINVAL)?;
+/// *slice.last_mut() = 0;
+/// assert_eq!(slice.len(), 3);
+/// assert_eq!(buf, [1, 2, 0]);
+///
+/// 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> 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



  reply	other threads:[~2026-10-12 11:46 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-10-12 11:46 [PATCH 0/2] rust: " Lorenzo Delgado
2026-10-12 11:46 ` Lorenzo Delgado [this message]
2026-10-12 11:46 ` [PATCH 2/2] rust: uaccess: use NonEmpty in strcpy_into_buf() Lorenzo Delgado
2026-10-12 11:53 [PATCH 0/2] rust: add NonEmpty Lorenzo Delgado
2026-10-12 11:53 ` [PATCH 1/2] rust: non_empty: " Lorenzo Delgado

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261012-nonempty-slice-v1-1-4a15dee398dd@proton.me \
    --to=lnsdev@proton.me \
    --cc=blum@kernel.org \
    --cc=laniel_francis@npnm.eu \
    --cc=linux-kernel@vger.kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®