[PATCH 0/2] rust: add NonEmpty
From: Lorenzo Delgado
Date: Mon Oct 12 2026 - 08:02:20 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()` and `last_mut()`. Patch 2
uses it in `strcpy_into_buf()`, which drops an `unsafe` block.
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>
---
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 | 100 +++++++++++++++++++++++++++++++++++++++++++++++
rust/kernel/uaccess.rs | 11 ++----
3 files changed, 105 insertions(+), 7 deletions(-)
---
base-commit: 2dee3d3adcadcc57d62ba6608cd02f50b0c10264
change-id: 20261011-nonempty-slice-022084ba9a5a
Best regards,
--
Lorenzo Delgado <lnsdev@xxxxxxxxx>