#![no_std]
#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;
#[cfg(feature = "bincode")]
use bincode::{Decode, Encode};
#[cfg(feature = "serialize")]
use serde::{
ser::{SerializeSeq, Serializer},
Deserialize, Serialize,
};
use core::iter;
use core::mem;
use core::{cmp::Ordering, num::NonZeroUsize};
#[cfg(feature = "std")]
extern crate std;
#[cfg_attr(test, macro_use)]
extern crate alloc;
use alloc::vec::{self, Vec};
pub mod nonzero;
#[doc(hidden)]
pub mod __macro_support {
pub use alloc::vec;
}
#[macro_export]
macro_rules! nonempty {
($h:expr, $( $x:expr ),* $(,)?) => {{
let tail = $crate::__macro_support::vec![$($x),*];
$crate::NonEmpty { head: $h, tail }
}};
($h:expr) => {
$crate::NonEmpty {
head: $h,
tail: $crate::__macro_support::vec![],
}
};
}
#[cfg_attr(feature = "serialize", derive(Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serialize", serde(try_from = "Vec<T>"))]
#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NonEmpty<T> {
pub head: T,
pub tail: Vec<T>,
}
#[cfg(feature = "serialize")]
impl<T> Serialize for NonEmpty<T>
where
T: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for e in self {
seq.serialize_element(e)?;
}
seq.end()
}
}
pub struct Iter<'a, T> {
head: Option<&'a T>,
tail: &'a [T],
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(value) = self.head.take() {
Some(value)
} else if let Some((first, rest)) = self.tail.split_first() {
self.tail = rest;
Some(first)
} else {
None
}
}
}
impl<T> DoubleEndedIterator for Iter<'_, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if let Some((last, rest)) = self.tail.split_last() {
self.tail = rest;
Some(last)
} else if let Some(first_value) = self.head.take() {
Some(first_value)
} else {
None
}
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {
fn len(&self) -> usize {
self.tail.len() + self.head.map_or(0, |_| 1)
}
}
impl<T> core::iter::FusedIterator for Iter<'_, T> {}
impl<T> NonEmpty<T> {
pub const fn new(e: T) -> Self {
Self::singleton(e)
}
pub fn as_ref(&self) -> NonEmpty<&T> {
NonEmpty {
head: &self.head,
tail: self.tail.iter().collect(),
}
}
pub fn collect<I>(iter: I) -> Option<NonEmpty<T>>
where
I: IntoIterator<Item = T>,
{
let mut iter = iter.into_iter();
let head = iter.next()?;
Some(Self {
head,
tail: iter.collect(),
})
}
pub const fn singleton(head: T) -> Self {
NonEmpty {
head,
tail: Vec::new(),
}
}
pub const fn is_empty(&self) -> bool {
false
}
pub const fn first(&self) -> &T {
&self.head
}
pub fn first_mut(&mut self) -> &mut T {
&mut self.head
}
pub fn tail(&self) -> &[T] {
&self.tail
}
pub fn push(&mut self, e: T) {
self.tail.push(e)
}
pub fn pop(&mut self) -> Option<T> {
self.tail.pop()
}
pub fn insert(&mut self, index: usize, element: T) {
let len = self.len();
assert!(index <= len);
if index == 0 {
let head = mem::replace(&mut self.head, element);
self.tail.insert(0, head);
} else {
self.tail.insert(index - 1, element);
}
}
pub fn len(&self) -> usize {
self.tail.len() + 1
}
pub fn len_nonzero(&self) -> NonZeroUsize {
unsafe { NonZeroUsize::new_unchecked(self.tail.len().saturating_add(1)) }
}
pub fn capacity(&self) -> NonZeroUsize {
NonZeroUsize::MIN.saturating_add(self.tail.capacity())
}
pub fn last(&self) -> &T {
match self.tail.last() {
None => &self.head,
Some(e) => e,
}
}
pub fn last_mut(&mut self) -> &mut T {
match self.tail.last_mut() {
None => &mut self.head,
Some(e) => e,
}
}
pub fn contains(&self, x: &T) -> bool
where
T: PartialEq,
{
self.iter().any(|e| e == x)
}
pub fn get(&self, index: usize) -> Option<&T> {
if index == 0 {
Some(&self.head)
} else {
self.tail.get(index - 1)
}
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if index == 0 {
Some(&mut self.head)
} else {
self.tail.get_mut(index - 1)
}
}
pub fn truncate(&mut self, len: usize) {
assert!(len >= 1);
self.tail.truncate(len - 1);
}
pub fn iter(&self) -> Iter<T> {
Iter {
head: Some(&self.head),
tail: &self.tail,
}
}
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
iter::once(&mut self.head).chain(self.tail.iter_mut())
}
pub fn from_slice(slice: &[T]) -> Option<NonEmpty<T>>
where
T: Clone,
{
slice.split_first().map(|(h, t)| NonEmpty {
head: h.clone(),
tail: t.into(),
})
}
pub fn from_vec(mut vec: Vec<T>) -> Option<NonEmpty<T>> {
if vec.is_empty() {
None
} else {
let head = vec.remove(0);
Some(NonEmpty { head, tail: vec })
}
}
pub fn split_first(&self) -> (&T, &[T]) {
(&self.head, &self.tail)
}
pub fn split(&self) -> (&T, &[T], Option<&T>) {
match self.tail.split_last() {
None => (&self.head, &[], None),
Some((last, middle)) => (&self.head, middle, Some(last)),
}
}
pub fn append(&mut self, other: &mut Vec<T>) {
self.tail.append(other)
}
pub fn map<U, F>(self, mut f: F) -> NonEmpty<U>
where
F: FnMut(T) -> U,
{
NonEmpty {
head: f(self.head),
tail: self.tail.into_iter().map(f).collect(),
}
}
pub fn try_map<E, U, F>(self, mut f: F) -> Result<NonEmpty<U>, E>
where
F: FnMut(T) -> Result<U, E>,
{
Ok(NonEmpty {
head: f(self.head)?,
tail: self.tail.into_iter().map(f).collect::<Result<_, _>>()?,
})
}
pub fn flat_map<U, F>(self, mut f: F) -> NonEmpty<U>
where
F: FnMut(T) -> NonEmpty<U>,
{
let mut heads = f(self.head);
let mut tails = self
.tail
.into_iter()
.flat_map(|t| f(t).into_iter())
.collect();
heads.append(&mut tails);
heads
}
pub fn flatten(full: NonEmpty<NonEmpty<T>>) -> Self {
full.flat_map(|n| n)
}
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where
T: Ord,
{
self.binary_search_by(|p| p.cmp(x))
}
pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
where
F: FnMut(&'a T) -> Ordering,
{
match f(&self.head) {
Ordering::Equal => Ok(0),
Ordering::Greater => Err(0),
Ordering::Less => self
.tail
.binary_search_by(f)
.map(|index| index + 1)
.map_err(|index| index + 1),
}
}
pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
where
B: Ord,
F: FnMut(&'a T) -> B,
{
self.binary_search_by(|k| f(k).cmp(b))
}
pub fn maximum(&self) -> &T
where
T: Ord,
{
self.maximum_by(|i, j| i.cmp(j))
}
pub fn minimum(&self) -> &T
where
T: Ord,
{
self.minimum_by(|i, j| i.cmp(j))
}
pub fn maximum_by<F>(&self, mut compare: F) -> &T
where
F: FnMut(&T, &T) -> Ordering,
{
let mut max = &self.head;
for i in self.tail.iter() {
max = match compare(max, i) {
Ordering::Equal => max,
Ordering::Less => i,
Ordering::Greater => max,
};
}
max
}
pub fn minimum_by<F>(&self, mut compare: F) -> &T
where
F: FnMut(&T, &T) -> Ordering,
{
self.maximum_by(|a, b| compare(a, b).reverse())
}
pub fn maximum_by_key<U, F>(&self, mut f: F) -> &T
where
U: Ord,
F: FnMut(&T) -> U,
{
self.maximum_by(|i, j| f(i).cmp(&f(j)))
}
pub fn minimum_by_key<U, F>(&self, mut f: F) -> &T
where
U: Ord,
F: FnMut(&T) -> U,
{
self.minimum_by(|i, j| f(i).cmp(&f(j)))
}
pub fn sort(&mut self)
where
T: Ord,
{
self.tail.sort();
let index = match self.tail.binary_search(&self.head) {
Ok(index) => index,
Err(index) => index,
};
if index != 0 {
let new_head = self.tail.remove(0);
let head = mem::replace(&mut self.head, new_head);
self.tail.insert(index - 1, head);
}
}
}
impl<T: Default> Default for NonEmpty<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> From<NonEmpty<T>> for Vec<T> {
fn from(nonempty: NonEmpty<T>) -> Vec<T> {
iter::once(nonempty.head).chain(nonempty.tail).collect()
}
}
impl<T> From<NonEmpty<T>> for (T, Vec<T>) {
fn from(nonempty: NonEmpty<T>) -> (T, Vec<T>) {
(nonempty.head, nonempty.tail)
}
}
impl<T> From<(T, Vec<T>)> for NonEmpty<T> {
fn from((head, tail): (T, Vec<T>)) -> Self {
NonEmpty { head, tail }
}
}
impl<T> IntoIterator for NonEmpty<T> {
type Item = T;
type IntoIter = iter::Chain<iter::Once<T>, vec::IntoIter<Self::Item>>;
fn into_iter(self) -> Self::IntoIter {
iter::once(self.head).chain(self.tail)
}
}
impl<'a, T> IntoIterator for &'a NonEmpty<T> {
type Item = &'a T;
type IntoIter = iter::Chain<iter::Once<&'a T>, core::slice::Iter<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
iter::once(&self.head).chain(self.tail.iter())
}
}
impl<T> core::ops::Index<usize> for NonEmpty<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
if index > 0 {
&self.tail[index - 1]
} else {
&self.head
}
}
}
impl<T> core::ops::IndexMut<usize> for NonEmpty<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
if index > 0 {
&mut self.tail[index - 1]
} else {
&mut self.head
}
}
}
impl<A> Extend<A> for NonEmpty<A> {
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
self.tail.extend(iter)
}
}
#[cfg(feature = "serialize")]
pub mod serialize {
use core::{convert::TryFrom, fmt};
use alloc::vec::Vec;
use super::NonEmpty;
#[derive(Debug)]
pub enum Error {
Empty,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str(
"the vector provided was empty, NonEmpty needs at least one element",
),
}
}
}
impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
type Error = Error;
fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
NonEmpty::from_vec(vec).ok_or(Error::Empty)
}
}
}
#[cfg(test)]
mod tests {
use alloc::{string::String, vec::Vec};
use crate::NonEmpty;
#[test]
fn test_from_conversion() {
let result = NonEmpty::from((1, vec![2, 3, 4, 5]));
let expected = NonEmpty {
head: 1,
tail: vec![2, 3, 4, 5],
};
assert_eq!(result, expected);
}
#[test]
fn test_into_iter() {
let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
for (i, n) in nonempty.into_iter().enumerate() {
assert_eq!(i as i32, n);
}
}
#[test]
fn test_iter_syntax() {
let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
for n in &nonempty {
let _ = *n; }
for _ in nonempty {}
}
#[test]
fn test_iter_both_directions() {
let mut nonempty = NonEmpty::from((0, vec![1, 2, 3]));
assert_eq!(nonempty.iter().cloned().collect::<Vec<_>>(), [0, 1, 2, 3]);
assert_eq!(
nonempty.iter().rev().cloned().collect::<Vec<_>>(),
[3, 2, 1, 0]
);
assert_eq!(
nonempty.iter_mut().rev().collect::<Vec<_>>(),
[&mut 3, &mut 2, &mut 1, &mut 0]
);
}
#[test]
fn test_iter_both_directions_at_once() {
let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
let mut i = nonempty.iter();
assert_eq!(i.next(), Some(&0));
assert_eq!(i.next_back(), Some(&3));
assert_eq!(i.next(), Some(&1));
assert_eq!(i.next_back(), Some(&2));
assert_eq!(i.next(), None);
assert_eq!(i.next_back(), None);
}
#[test]
fn test_mutate_head() {
let mut non_empty = NonEmpty::new(42);
non_empty.head += 1;
assert_eq!(non_empty.head, 43);
let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
non_empty.head *= 42;
assert_eq!(non_empty.head, 42);
}
#[test]
fn test_to_nonempty() {
use core::iter::{empty, once};
assert_eq!(NonEmpty::<()>::collect(empty()), None);
assert_eq!(NonEmpty::<()>::collect(once(())), Some(NonEmpty::new(())));
assert_eq!(
NonEmpty::<u8>::collect(once(1).chain(once(2))),
Some(nonempty!(1, 2))
);
}
#[test]
fn test_try_map() {
assert_eq!(
nonempty!(1, 2, 3, 4).try_map(Ok::<_, String>),
Ok(nonempty!(1, 2, 3, 4))
);
assert_eq!(
nonempty!(1, 2, 3, 4).try_map(|i| if i % 2 == 0 { Ok(i) } else { Err("not even") }),
Err("not even")
);
}
#[test]
fn test_nontrivial_minimum_by_key() {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Position {
x: i32,
y: i32,
}
impl Position {
pub fn distance_squared(&self, other: Position) -> u32 {
let dx = self.x - other.x;
let dy = self.y - other.y;
(dx * dx + dy * dy) as u32
}
}
let positions = nonempty![
Position { x: 1, y: 1 },
Position { x: 0, y: 0 },
Position { x: 3, y: 4 }
];
let target = Position { x: 1, y: 2 };
let closest = positions.minimum_by_key(|position| position.distance_squared(target));
assert_eq!(closest, &Position { x: 1, y: 1 });
}
#[test]
fn test_sort() {
let mut numbers = nonempty![1];
numbers.sort();
assert_eq!(numbers, nonempty![1]);
let mut numbers = nonempty![2, 1, 3];
numbers.sort();
assert_eq!(numbers, nonempty![1, 2, 3]);
let mut numbers = nonempty![1, 3, 2];
numbers.sort();
assert_eq!(numbers, nonempty![1, 2, 3]);
let mut numbers = nonempty![3, 2, 1];
numbers.sort();
assert_eq!(numbers, nonempty![1, 2, 3]);
}
#[cfg(feature = "serialize")]
mod serialize {
use crate::NonEmpty;
use alloc::boxed::Box;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SimpleSerializable(pub i32);
#[test]
fn test_simple_round_trip() -> Result<(), Box<dyn core::error::Error>> {
let mut non_empty = NonEmpty::new(SimpleSerializable(42));
non_empty.push(SimpleSerializable(777));
let res = serde_json::from_str::<'_, NonEmpty<SimpleSerializable>>(
&serde_json::to_string(&non_empty)?,
)?;
assert_eq!(res, non_empty);
Ok(())
}
#[test]
fn test_serialization() -> Result<(), Box<dyn core::error::Error>> {
let ne = nonempty![1, 2, 3, 4, 5];
let ve = vec![1, 2, 3, 4, 5];
assert_eq!(serde_json::to_string(&ne)?, serde_json::to_string(&ve)?);
Ok(())
}
}
#[cfg(feature = "bincode")]
mod bincode {
use crate::NonEmpty;
use alloc::boxed::Box;
#[derive(Clone, Debug, Eq, PartialEq, bincode::Encode, bincode::Decode)]
pub struct SimpleSerializable(pub i32);
#[test]
fn test_simple_round_trip() -> Result<(), Box<dyn core::error::Error>> {
let mut non_empty = NonEmpty::new(SimpleSerializable(42));
non_empty.push(SimpleSerializable(777));
let config = bincode::config::standard();
let (res, _) = bincode::decode_from_slice::<NonEmpty<SimpleSerializable>, _>(
&bincode::encode_to_vec(non_empty.clone(), config)?,
config,
)?;
assert_eq!(res, non_empty);
Ok(())
}
}
#[cfg(feature = "arbitrary")]
mod arbitrary {
use crate::NonEmpty;
use arbitrary::{Arbitrary, Unstructured};
#[test]
fn test_arbitrary_empty_tail() -> arbitrary::Result<()> {
let mut u = Unstructured::new(&[1, 2, 3, 4]);
let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
assert!(!ne.is_empty());
assert_eq!(
ne,
NonEmpty {
head: 67305985,
tail: vec![],
}
);
Ok(())
}
#[test]
fn test_arbitrary_with_tail() -> arbitrary::Result<()> {
let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
assert!(!ne.is_empty());
assert_eq!(
ne,
NonEmpty {
head: 67305985,
tail: vec![526086],
}
);
Ok(())
}
#[test]
fn test_arbitrary_with_split() -> arbitrary::Result<()> {
let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
let (head, middle, last) = ne.split();
let mut tail = middle.to_vec();
tail.extend(last);
assert_eq!(ne, NonEmpty { head: *head, tail });
Ok(())
}
}
}