Struct nonempty::NonEmpty

source ·
pub struct NonEmpty<T> {
    pub head: T,
    pub tail: Vec<T>,
}

Fields§

§head: T§tail: Vec<T>

Implementations§

source§

impl<T> NonEmpty<T>

source

pub const fn new(e: T) -> Self

source

pub const fn singleton(head: T) -> Self

Create a new non-empty list with an initial element.

source

pub const fn is_empty(&self) -> bool

Always returns false.

source

pub const fn first(&self) -> &T

Get the first element. Never fails.

source

pub fn first_mut(&mut self) -> &mut T

Get the mutable reference to the first element. Never fails.

§Examples
use nonempty::NonEmpty;

let mut non_empty = NonEmpty::new(42);
let head = non_empty.first_mut();
*head += 1;
assert_eq!(non_empty.first(), &43);

let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
let head = non_empty.first_mut();
*head *= 42;
assert_eq!(non_empty.first(), &42);
source

pub fn tail(&self) -> &[T]

Get the possibly-empty tail of the list.

use nonempty::NonEmpty;

let non_empty = NonEmpty::new(42);
assert_eq!(non_empty.tail(), &[]);

let non_empty = NonEmpty::from((1, vec![4, 2, 3]));
assert_eq!(non_empty.tail(), &[4, 2, 3]);
source

pub fn push(&mut self, e: T)

Push an element to the end of the list.

source

pub fn pop(&mut self) -> Option<T>

Pop an element from the end of the list.

source

pub fn insert(&mut self, index: usize, element: T)

Inserts an element at position index within the vector, shifting all elements after it to the right.

§Panics

Panics if index > len.

§Examples
use nonempty::NonEmpty;

let mut non_empty = NonEmpty::from((1, vec![2, 3]));
non_empty.insert(1, 4);
assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3])));
non_empty.insert(4, 5);
assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3, 5])));
non_empty.insert(0, 42);
assert_eq!(non_empty, NonEmpty::from((42, vec![1, 4, 2, 3, 5])));
source

pub fn len(&self) -> usize

Get the length of the list.

source

pub fn capacity(&self) -> usize

Get the capacity of the list.

source

pub fn last(&self) -> &T

Get the last element. Never fails.

source

pub fn last_mut(&mut self) -> &mut T

Get the last element mutably.

source

pub fn contains(&self, x: &T) -> bool
where T: PartialEq,

Check whether an element is contained in the list.

use nonempty::NonEmpty;

let mut l = NonEmpty::from((42, vec![36, 58]));

assert!(l.contains(&42));
assert!(!l.contains(&101));
source

pub fn get(&self, index: usize) -> Option<&T>

Get an element by index.

source

pub fn get_mut(&mut self, index: usize) -> Option<&mut T>

Get an element by index, mutably.

source

pub fn truncate(&mut self, len: usize)

Truncate the list to a certain size. Must be greater than 0.

source

pub fn iter<'a>(&'a self) -> impl Iterator<Item = &T> + 'a

use nonempty::NonEmpty;

let mut l = NonEmpty::from((42, vec![36, 58]));

let mut l_iter = l.iter();

assert_eq!(l_iter.next(), Some(&42));
assert_eq!(l_iter.next(), Some(&36));
assert_eq!(l_iter.next(), Some(&58));
assert_eq!(l_iter.next(), None);
source

pub fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &mut T> + 'a

use nonempty::NonEmpty;

let mut l = NonEmpty::new(42);
l.push(36);
l.push(58);

for i in l.iter_mut() {
    *i *= 10;
}

let mut l_iter = l.iter();

assert_eq!(l_iter.next(), Some(&420));
assert_eq!(l_iter.next(), Some(&360));
assert_eq!(l_iter.next(), Some(&580));
assert_eq!(l_iter.next(), None);
source

pub fn from_slice(slice: &[T]) -> Option<NonEmpty<T>>
where T: Clone,

Often we have a Vec (or slice &[T]) but want to ensure that it is NonEmpty before proceeding with a computation. Using from_slice will give us a proof that we have a NonEmpty in the Some branch, otherwise it allows the caller to handle the None case.

§Example Use
use nonempty::NonEmpty;

let non_empty_vec = NonEmpty::from_slice(&[1, 2, 3, 4, 5]);
assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));

let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_slice(&[]);
assert!(empty_vec.is_none());
source

pub fn from_vec(vec: Vec<T>) -> Option<NonEmpty<T>>

Often we have a Vec (or slice &[T]) but want to ensure that it is NonEmpty before proceeding with a computation. Using from_vec will give us a proof that we have a NonEmpty in the Some branch, otherwise it allows the caller to handle the None case.

This version will consume the Vec you pass in. If you would rather pass the data as a slice then use NonEmpty::from_slice.

§Example Use
use nonempty::NonEmpty;

let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]);
assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));

let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_vec(vec![]);
assert!(empty_vec.is_none());
source

pub fn split_first(&self) -> (&T, &[T])

Deconstruct a NonEmpty into its head and tail. This operation never fails since we are guranteed to have a head element.

§Example Use
use nonempty::NonEmpty;

let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));

// Guaranteed to have the head and we also get the tail.
assert_eq!(non_empty.split_first(), (&1, &[2, 3, 4, 5][..]));

let non_empty = NonEmpty::new(1);

// Guaranteed to have the head element.
assert_eq!(non_empty.split_first(), (&1, &[][..]));
source

pub fn split(&self) -> (&T, &[T], &T)

Deconstruct a NonEmpty into its first, last, and middle elements, in that order.

If there is only one element then first == last.

§Example Use
use nonempty::NonEmpty;

let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));

// Guaranteed to have the last element and the elements
// preceding it.
assert_eq!(non_empty.split(), (&1, &[2, 3, 4][..], &5));

let non_empty = NonEmpty::new(1);

// Guaranteed to have the last element.
assert_eq!(non_empty.split(), (&1, &[][..], &1));
source

pub fn append(&mut self, other: &mut Vec<T>)

Append a Vec to the tail of the NonEmpty.

§Example Use
use nonempty::NonEmpty;

let mut non_empty = NonEmpty::new(1);
let mut vec = vec![2, 3, 4, 5];
non_empty.append(&mut vec);

let mut expected = NonEmpty::from((1, vec![2, 3, 4, 5]));

assert_eq!(non_empty, expected);
source

pub fn map<U, F>(self, f: F) -> NonEmpty<U>
where F: FnMut(T) -> U,

A structure preserving map. This is useful for when we wish to keep the NonEmpty structure guaranteeing that there is at least one element. Otherwise, we can use nonempty.iter().map(f).

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));

let squares = non_empty.map(|i| i * i);

let expected = NonEmpty::from((1, vec![4, 9, 16, 25]));

assert_eq!(squares, expected);
source

pub fn flat_map<U, F>(self, f: F) -> NonEmpty<U>
where F: FnMut(T) -> NonEmpty<U>,

When we have a function that goes from some T to a NonEmpty<U>, we may want to apply it to a NonEmpty<T> but keep the structure flat. This is where flat_map shines.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));

let windows = non_empty.flat_map(|i| {
    let mut next = NonEmpty::new(i + 5);
    next.push(i + 6);
    next
});

let expected = NonEmpty::from((6, vec![7, 7, 8, 8, 9, 9, 10, 10, 11]));

assert_eq!(windows, expected);
source

pub fn flatten(full: NonEmpty<NonEmpty<T>>) -> Self

Flatten nested NonEmptys into a single one.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::from((
    NonEmpty::from((1, vec![2, 3])),
    vec![NonEmpty::from((4, vec![5]))],
));

let expected = NonEmpty::from((1, vec![2, 3, 4, 5]));

assert_eq!(NonEmpty::flatten(non_empty), expected);

Binary searches this sorted non-empty vector for a given element.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned.

If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
assert_eq!(non_empty.binary_search(&0),   Ok(0));
assert_eq!(non_empty.binary_search(&13),  Ok(9));
assert_eq!(non_empty.binary_search(&4),   Err(7));
assert_eq!(non_empty.binary_search(&100), Err(13));
let r = non_empty.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });

If you want to insert an item to a sorted non-empty vector, while maintaining sort order:

use nonempty::NonEmpty;

let mut non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
let num = 42;
let idx = non_empty.binary_search(&num).unwrap_or_else(|x| x);
non_empty.insert(idx, num);
assert_eq!(non_empty, NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55])));
source

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
where F: FnMut(&'a T) -> Ordering,

Binary searches this sorted non-empty with a comparator function.

The comparator function should implement an order consistent with the sort order of the underlying slice, returning an order code that indicates whether its argument is Less, Equal or Greater the desired target.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

§Examples

Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1,4].

use nonempty::NonEmpty;

let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
let seek = 0;
assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
let seek = 13;
assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = non_empty.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
source

pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F, ) -> Result<usize, usize>
where B: Ord, F: FnMut(&'a T) -> B,

Binary searches this sorted non-empty vector with a key extraction function.

Assumes that the vector is sorted by the key.

If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

§Examples

Looks up a series of four elements in a non-empty vector of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1, 4].

use nonempty::NonEmpty;

let non_empty = NonEmpty::from((
    (0, 0),
    vec![(2, 1), (4, 1), (5, 1), (3, 1),
         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
         (1, 21), (2, 34), (4, 55)]
));

assert_eq!(non_empty.binary_search_by_key(&0, |&(a,b)| b),  Ok(0));
assert_eq!(non_empty.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
assert_eq!(non_empty.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
assert_eq!(non_empty.binary_search_by_key(&100, |&(a,b)| b), Err(13));
let r = non_empty.binary_search_by_key(&1, |&(a,b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
source

pub fn maximum(&self) -> &T
where T: Ord,

Returns the maximum element in the non-empty vector.

This will return the first item in the vector if the tail is empty.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::new(42);
assert_eq!(non_empty.maximum(), &42);

let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
assert_eq!(non_empty.maximum(), &76);
source

pub fn minimum(&self) -> &T
where T: Ord,

Returns the minimum element in the non-empty vector.

This will return the first item in the vector if the tail is empty.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::new(42);
assert_eq!(non_empty.minimum(), &42);

let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
assert_eq!(non_empty.minimum(), &-34);
source

pub fn maximum_by<F>(&self, compare: F) -> &T
where F: Fn(&T, &T) -> Ordering,

Returns the element that gives the maximum value with respect to the specified comparison function.

This will return the first item in the vector if the tail is empty.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::new((0, 42));
assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));

let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(4, 42));
source

pub fn minimum_by<F>(&self, compare: F) -> &T
where F: Fn(&T, &T) -> Ordering,

Returns the element that gives the minimum value with respect to the specified comparison function.

This will return the first item in the vector if the tail is empty.

use nonempty::NonEmpty;

let non_empty = NonEmpty::new((0, 42));
assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));

let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 76));
source

pub fn maximum_by_key<U, F>(&self, f: F) -> &T
where U: Ord, F: Fn(&T) -> &U,

Returns the element that gives the maximum value with respect to the specified function.

This will return the first item in the vector if the tail is empty.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::new((0, 42));
assert_eq!(non_empty.maximum_by_key(|(k, _)| k), &(0, 42));

let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
assert_eq!(non_empty.maximum_by_key(|(k, _)| k), &(4, 42));
source

pub fn minimum_by_key<U, F>(&self, f: F) -> &T
where U: Ord, F: Fn(&T) -> &U,

Returns the element that gives the minimum value with respect to the specified function.

This will return the first item in the vector if the tail is empty.

§Examples
use nonempty::NonEmpty;

let non_empty = NonEmpty::new((0, 42));
assert_eq!(non_empty.minimum_by_key(|(k, _)| k), &(0, 42));

let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
assert_eq!(non_empty.minimum_by_key(|(k, _)| k), &(0, 76));

Trait Implementations§

source§

impl<T: Clone> Clone for NonEmpty<T>

source§

fn clone(&self) -> NonEmpty<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug> Debug for NonEmpty<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T> From<(T, Vec<T>)> for NonEmpty<T>

source§

fn from((head, tail): (T, Vec<T>)) -> Self

Turns a pair of an element and a Vec into a NonEmpty.

source§

impl<T> From<NonEmpty<T>> for (T, Vec<T>)

source§

fn from(nonempty: NonEmpty<T>) -> (T, Vec<T>)

Turns a non-empty list into a Vec.

source§

impl<T> From<NonEmpty<T>> for Vec<T>

source§

fn from(nonempty: NonEmpty<T>) -> Vec<T>

Turns a non-empty list into a Vec.

source§

impl<T: Hash> Hash for NonEmpty<T>

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<T> Index<usize> for NonEmpty<T>

source§

fn index(&self, index: usize) -> &T

use nonempty::NonEmpty;

let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));

assert_eq!(non_empty[0], 1);
assert_eq!(non_empty[1], 2);
assert_eq!(non_empty[3], 4);
§

type Output = T

The returned type after indexing.
source§

impl<T> IndexMut<usize> for NonEmpty<T>

source§

fn index_mut(&mut self, index: usize) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, T> IntoIterator for &'a NonEmpty<T>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Chain<Once<&'a T>, Iter<'a, T>>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T> IntoIterator for NonEmpty<T>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = Chain<Once<T>, IntoIter<<NonEmpty<T> as IntoIterator>::Item>>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T: Ord> Ord for NonEmpty<T>

source§

fn cmp(&self, other: &NonEmpty<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<T: PartialEq> PartialEq for NonEmpty<T>

source§

fn eq(&self, other: &NonEmpty<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialOrd> PartialOrd for NonEmpty<T>

source§

fn partial_cmp(&self, other: &NonEmpty<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T: Eq> Eq for NonEmpty<T>

source§

impl<T> StructuralPartialEq for NonEmpty<T>

Auto Trait Implementations§

§

impl<T> Freeze for NonEmpty<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for NonEmpty<T>
where T: RefUnwindSafe,

§

impl<T> Send for NonEmpty<T>
where T: Send,

§

impl<T> Sync for NonEmpty<T>
where T: Sync,

§

impl<T> Unpin for NonEmpty<T>
where T: Unpin,

§

impl<T> UnwindSafe for NonEmpty<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.