[PATCH v3 0/2] rust: add NonEmpty
From: Lorenzo Delgado
Date: Wed Oct 14 2026 - 04:37:41 EST
Some functions check that a container is not empty and later rely on it
through `unwrap_unchecked()`, `unwrap()` or an error path that can't be
taken. Gary suggested a non-empty type for this while reviewing Thorsten
Blum's uaccess patch [1], and Miguel filed it as #1262 [2].
Patch 1 adds `NonEmpty<C>` in `kernel::non_empty`, with only what the
first user needs: slices, `try_from_mut()`, `from_mut()` for arrays
and `last_mut()`. Patch 2 makes `strcpy_into_buf()` take a
`NonEmpty<[u8]>`, which drops an `unsafe` block and the `EINVAL` case.
Some notes:
- `IsEmpty` is a safe trait. Unsafe code only relies on the
implementations in `kernel::non_empty`, and the docs require the
result not to change while the container is only reachable through a
shared reference. If a generic accessor ever needs to rely on it, it
can become an `unsafe trait` then.
- Since APIs aren't added without users, other accessors (`first()`,
`try_from_ref()`, ...) and containers are left for later. I plan to
send follow-ups for `net/phy.rs` and `scatterlist.rs`, which both
reject an empty slice and then rely on it.
- I put it in its own `kernel::non_empty` module. Would a broader home
like `kernel::collections` be better?
Francis Laniel posted a slice-only RFC [3]. Following Gary's suggestion
on the issue, this version is generic over the container.
[1] https://lore.kernel.org/rust-for-linux/DM0D9TERQAM3.2Y3HV6P68E2N8@xxxxxxxxxxx/
[2] https://github.com/Rust-for-Linux/linux/issues/1262
[3] https://lore.kernel.org/rust-for-linux/20261011191540.56199-1-laniel_francis@xxxxxxx/
Signed-off-by: Lorenzo Delgado <lnsdev@xxxxxxxxx>
---
Changes in v3:
- Replace `from_array_mut()` with a `const fn from_mut()` on
`NonEmpty<[T; N]>`, and get `NonEmpty<[T]>` from it by unsize
coercion instead of a slice pointer cast (Gary).
- Link to v2: https://patch.msgid.link/20261012-nonempty-slice-v2-0-0f2b67d9463e@xxxxxxxxx
Changes in v2:
- Take `&mut NonEmpty<[u8]>` in `strcpy_into_buf()` and drop the
`EINVAL` case for an empty buffer (Miguel).
- Add `NonEmpty::from_array_mut()`, which checks the array length at
compile time, so callers of `strcpy_into_buf()` with an array buffer
need no runtime check.
- Link to v1: https://patch.msgid.link/20261012-nonempty-slice-v1-0-37d1fecff82c@xxxxxxxxx
---
Lorenzo Delgado (2):
rust: non_empty: add NonEmpty
rust: uaccess: use NonEmpty in strcpy_into_buf()
rust/kernel/lib.rs | 1 +
rust/kernel/non_empty.rs | 123 +++++++++++++++++++++++++++++++++++++++++++++++
rust/kernel/uaccess.rs | 15 ++----
3 files changed, 129 insertions(+), 10 deletions(-)
---
base-commit: 2dee3d3adcadcc57d62ba6608cd02f50b0c10264
change-id: 20261011-nonempty-slice-022084ba9a5a
Best regards,
--
Lorenzo Delgado <lnsdev@xxxxxxxxx>