The definitive non-empty slice/array/vec library for Rust.
Features
Nonempty-by-construction API
let mut my_vec = of; // construct once
my_vec.push; // continue using your normal APIs
let hello: &str = my_vec.first; // preserve the guarantee that there is at least one element
#[repr(transparent)] allows advanced usecases and guarantees optimum performance[^1]:
let src = &mut ;
let ne = new_mut.unwrap;
// ^ uses the same backing memory
let world: &str = ne.last;
Total API coverage.
For every impl of [From], [TryFrom], [PartialEq] and [PartialOrd] in [std][^2],
there is a corresponding impl in this library for [Slice], [Array] and [Vec].
This includes more exotic types:
let nun: = vec!.into;
let cow: = .into;
let arc: = cow.into_owned.into;
const-friendly API. Where possible, all methods are const.
const TWO: & = slice!;
const FIRST: &str = TWO.first;
const ONE: & = of;
Extensive feature gating supporting:
no-stdenvironments with no allocator.alloc-enabled environments.- full-
std-enabled environments. - interaction with crates like
serdeandarbitrary.
Iterator support:
Specialized [Iterator] methods remove branches to handle empty iterators,
and preserve invariants even when chaining combinators.
let v = vec!;
let _: = v.iter.last;
// ^ normally you have to handle the empty case
let _: &u8 = v.iter_ne.last;
// ^ but we know there is at least one element
let _: u8 = v.iter_ne.copied.last;
// ^ using this combinator preserves the invariant
Thoughtful design:
- [
NonZeroUsize] is inserted where appropriate. - Everything
Deref/DerefMuts down to a [NonEmpty<Slice<T>>], which in turnderef/muts down to a[T]. - Liberal applications of
cmp,borrow,converttraits. If there's a missing API that you'd like, please raise an issue!
[^1]: Other crates like nonempty
require an indirection.
[^2]: Barring impls on !#[fundamental] types like Arc.
Fun fact: our tests were generated from [std]'s rustdoc!