Re: [PATCH v3 0/2] rust: add NonEmpty
From: Gary Guo
Date: Thu Oct 15 2026 - 10:29:00 EST
On Thu Oct 15, 2026 at 1:57 PM BST, Alexandre Courbot wrote:
> On Wed Oct 14, 2026 at 5:30 PM JST, Lorenzo Delgado wrote:
>> 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.
>
> Having `last` without `first` is weird. Please add the minimal set that
> makes sense from the get-go, these are `pub` anyway so clippy won't
> complain if they are unused.
>
>>
>> - I put it in its own `kernel::non_empty` module. Would a broader home
>> like `kernel::collections` be better?
>
> `kernel::types` sounds like a proper place? Or if we want a dedicated
> module, `kernel::slice` to match the standard library? `non_empty` is
> too ad-hoc and specific.
`kernel::types` is too generic and becomes a dumping ground of things. I wonder
if we should group things that are new types with just range restrictions
(together things like NonZero, Bounded, and perhaps eventually Range, NonNeg and
others).
Best,
Gary