Re: [RFC PATCH v1 1/2] rust: add NonEmptySlice
From: Alexandre Courbot
Date: Mon Oct 12 2026 - 11:42:21 EST
Looks like we are converging towards the series sent by Lorenzo, but
wanted to share a couple a quick comments nonetheless:
On Mon Oct 12, 2026 at 4:15 AM JST, Francis Laniel wrote:
> Add NonEmptySlice<T>, a [T] wrapper that is guaranteed to contain at
> least one element.
> This lets methods such as last_mut() return a plain reference instead
> of an Option, so callers that have already checked for emptiness no
> longer need unwrap() or unwrap_unchecked().
>
> Suggested-by: Gary Guo <gary@xxxxxxxxxxx>
> Signed-off-by: Francis Laniel <laniel_francis@xxxxxxx>
> ---
> rust/kernel/lib.rs | 1 +
> rust/kernel/slice.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 77 insertions(+)
> create mode 100644 rust/kernel/slice.rs
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 7225abc64084..8cc01aceb3b2 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -130,6 +130,7 @@
> #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
> pub mod serdev;
> pub mod sizes;
> +pub mod slice;
> #[cfg(CONFIG_SOC_BUS)]
> pub mod soc;
> #[doc(hidden)]
> diff --git a/rust/kernel/slice.rs b/rust/kernel/slice.rs
> new file mode 100644
> index 000000000000..7e467cb952c3
> --- /dev/null
> +++ b/rust/kernel/slice.rs
> @@ -0,0 +1,76 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Slice abstractions to ease development.
> +
> +use core::ops::{Deref, DerefMut};
> +
> +/// A slice that is guaranteed to contain at least one element.
> +///
> +/// # Invariants
> +///
> +/// `self.0` is not empty.
> +#[repr(transparent)]
> +pub struct NonEmptySlice<T>([T]);
> +
> +impl<T> NonEmptySlice<T> {
> + /// Returns `None` if `s` is empty.
This is not a standard doccomment. Doccomments first start by stating
what the function does before explaining the return value.
> + pub fn new(s: &mut [T]) -> Option<&Self> {
It looks strange to take a `&mut` and return a `&Self`. There should be
no reason to take a mutable reference here, and you can use
`ptr::from_ref` to create the reference.
> + if s.is_empty() {
> + return None;
> + }
> + // SAFETY: `Self` is `repr(transparent)` over `[T]`, so the cast keeps the slice length.
> + // INVARIANT: `s` is not empty, checked above.
> + Some(unsafe { &*(core::ptr::from_mut(s) as *const Self) })
> + }
> +
> + /// Returns `None` if `s` is empty.
> + pub fn new_mut(s: &mut [T]) -> Option<&mut Self> {
> + if s.is_empty() {
> + return None;
> + }
> + // SAFETY: `Self` is `repr(transparent)` over `[T]`, so the cast keeps the slice length.
> + // INVARIANT: `s` is not empty, checked above.
> + Some(unsafe { &mut *(core::ptr::from_mut(s) as *mut Self) })
> + }
> +
> + /// Returns a reference to the first element.
> + pub fn first(&mut self) -> &T {
Same here, `first` and `last` should take a non-mutable reference as
their standard library counterparts do. They do not allow to mutate the
slice.