Re: [PATCH v3 1/2] rust: non_empty: add NonEmpty
From: Alexandre Courbot
Date: Thu Oct 15 2026 - 08:52:40 EST
On Wed Oct 14, 2026 at 11:25 PM JST, Gary Guo wrote:
> On Wed Oct 14, 2026 at 12:55 PM BST, Miguel Ojeda wrote:
>> On Wed, Oct 14, 2026 at 10:30 AM Lorenzo Delgado <lnsdev@xxxxxxxxx> wrote:
>>>
>>> +/// 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;
>>> +}
>>
>> Do we need this to be a safe trait? If it is unsafe, then we can
>> simplify the invariant and more easily think about the type, like
>> other `Non*`s, no?
>
> I think in this case the meaning of "empty" depends on the container itself.
> Unsafe code that relies on "is_empty" would be the `NonEmpty<Container>` itself,
> so it just needs to trust itself (as boundary of unsafe is module level).
>
> I think of almost all of the text above can be removed. The invariant of
> `NonEmpty` can just be "`IsEmpty::is_empty` has returned true" and how it is
> interpreted is up to the container type.
Is `IsEmpty` actually useful? It needs to be implemented for every
container we want to wrap with essentially the same boilerplate code,
which looks a bit overkill to me. Couldn't we just do:
impl<T, C: Deref<Target = [T]>> NonEmpty<C>
and have a single constructor method that supports all container types
by reusing the slice's `is_empty` method?
That way we could get rid of `IsEmpty` entirely. That would limit
`NonEmpty` to types that directly deref to `[T]`, but I guess we are
going to use it on slices most of the time, with the exception of when
we want to return an owned container that is not empty, and those we
have already deref to a slice.