nonempty/
lib.rs

1//! A Non-empty growable vector.
2//!
3//! Non-emptiness can be a powerful guarantee. If your main use of `Vec` is as
4//! an `Iterator`, then you may not need to distinguish on emptiness. But there
5//! are indeed times when the `Vec` you receive as as function argument needs to
6//! be non-empty or your function can't proceed. Similarly, there are times when
7//! the `Vec` you return to a calling user needs to promise it actually contains
8//! something.
9//!
10//! With `NonEmpty`, you're freed from the boilerplate of constantly needing to
11//! check `is_empty()` or pattern matching before proceeding, or erroring if you
12//! can't. So overall, code, type signatures, and logic become cleaner.
13//!
14//! Consider that unlike `Vec`, [`NonEmpty::first`] and [`NonEmpty::last`] don't
15//! return in `Option`, they always succeed.
16//!
17//! # Examples
18//!
19//! The simplest way to construct a [`NonEmpty`] is via the [`nonempty`] macro:
20//!
21//! ```
22//! # extern crate alloc;
23//! # use alloc::vec::Vec;
24//! use nonempty::{NonEmpty, nonempty};
25//!
26//! let l: NonEmpty<u32> = nonempty![1, 2, 3];
27//! assert_eq!(l.head, 1);
28//! ```
29//!
30//! Unlike the familiar `vec!` macro, `nonempty!` requires at least one element:
31//!
32//! ```
33//! # extern crate alloc;
34//! # use alloc::vec::Vec;
35//! use nonempty::nonempty;
36//!
37//! let l = nonempty![1];
38//!
39//! // Doesn't compile!
40//! // let l = nonempty![];
41//! ```
42//!
43//! Like `Vec`, you can also construct a [`NonEmpty`] the old fashioned way with
44//! [`NonEmpty::new`] or its constructor:
45//!
46//! ```
47//! # extern crate alloc;
48//! # use alloc::vec::Vec;
49//! use nonempty::NonEmpty;
50//!
51//! let mut l = NonEmpty { head: 42, tail: vec![36, 58] };
52//! assert_eq!(l.head, 42);
53//!
54//! l.push(9001);
55//! assert_eq!(l.last(), &9001);
56//! ```
57//!
58//! And if necessary, you're free to convert to and from `Vec`:
59//!
60//! ```
61//! use nonempty::{NonEmpty, nonempty};
62//!
63//! let l: NonEmpty<u32> = nonempty![42, 36, 58, 9001];
64//! let v: Vec<u32> = l.into();
65//! assert_eq!(v, vec![42, 36, 58, 9001]);
66//!
67//! let u: Option<NonEmpty<u32>> = NonEmpty::from_vec(v);
68//! assert_eq!(Some(nonempty![42, 36, 58, 9001]), u);
69//! ```
70//!
71//! # Caveats
72//!
73//! Since `NonEmpty` must have a least one element, it is not possible to
74//! implement the [`FromIterator`] trait for it. We can't know, in general, if
75//! any given [`Iterator`] actually contains something.
76
77#![no_std]
78
79//! # Features
80//!
81//! * `serialize`: `serde` support.
82//! * `arbitrary`: `arbitrary` support.
83//! * `bincode`" `bincode` support.
84#[cfg(feature = "arbitrary")]
85use arbitrary::Arbitrary;
86#[cfg(feature = "bincode")]
87use bincode::{Decode, Encode};
88#[cfg(feature = "serialize")]
89use serde::{
90    ser::{SerializeSeq, Serializer},
91    Deserialize, Serialize,
92};
93
94use core::iter;
95use core::mem;
96use core::{cmp::Ordering, num::NonZeroUsize};
97
98#[cfg(feature = "std")]
99extern crate std;
100
101#[cfg_attr(test, macro_use)]
102extern crate alloc;
103use alloc::vec::{self, Vec};
104
105pub mod nonzero;
106
107#[doc(hidden)]
108pub mod __macro_support {
109    pub use alloc::vec;
110}
111
112/// Like the `vec!` macro, but enforces at least one argument. A nice short-hand
113/// for constructing [`NonEmpty`] values.
114///
115/// ```
116/// # extern crate alloc;
117/// # use alloc::vec::Vec;
118/// use nonempty::{NonEmpty, nonempty};
119///
120/// let v = nonempty![1, 2, 3];
121/// assert_eq!(v, NonEmpty { head: 1, tail: vec![2, 3] });
122///
123/// let v = nonempty![1];
124/// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() });
125///
126/// // Accepts trailing commas
127/// let v = nonempty![1,];
128/// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() });
129///
130/// // Doesn't compile!
131/// // let v = nonempty![];
132/// ```
133#[macro_export]
134macro_rules! nonempty {
135    ($h:expr, $( $x:expr ),* $(,)?) => {{
136        let tail = $crate::__macro_support::vec![$($x),*];
137        $crate::NonEmpty { head: $h, tail }
138    }};
139    ($h:expr) => {
140        $crate::NonEmpty {
141            head: $h,
142            tail: $crate::__macro_support::vec![],
143        }
144    };
145}
146
147/// Non-empty vector.
148#[cfg_attr(feature = "serialize", derive(Deserialize))]
149#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
150#[cfg_attr(feature = "serialize", serde(try_from = "Vec<T>"))]
151#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
152#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
153pub struct NonEmpty<T> {
154    pub head: T,
155    pub tail: Vec<T>,
156}
157
158// Nb. `Serialize` is implemented manually, as serde's `into` container attribute
159// requires a `T: Clone` bound which we'd like to avoid.
160#[cfg(feature = "serialize")]
161impl<T> Serialize for NonEmpty<T>
162where
163    T: Serialize,
164{
165    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166    where
167        S: Serializer,
168    {
169        let mut seq = serializer.serialize_seq(Some(self.len()))?;
170        for e in self {
171            seq.serialize_element(e)?;
172        }
173        seq.end()
174    }
175}
176
177pub struct Iter<'a, T> {
178    head: Option<&'a T>,
179    tail: &'a [T],
180}
181
182impl<'a, T> Iterator for Iter<'a, T> {
183    type Item = &'a T;
184
185    fn next(&mut self) -> Option<Self::Item> {
186        if let Some(value) = self.head.take() {
187            Some(value)
188        } else if let Some((first, rest)) = self.tail.split_first() {
189            self.tail = rest;
190            Some(first)
191        } else {
192            None
193        }
194    }
195}
196
197impl<T> DoubleEndedIterator for Iter<'_, T> {
198    fn next_back(&mut self) -> Option<Self::Item> {
199        if let Some((last, rest)) = self.tail.split_last() {
200            self.tail = rest;
201            Some(last)
202        } else if let Some(first_value) = self.head.take() {
203            Some(first_value)
204        } else {
205            None
206        }
207    }
208}
209
210impl<T> ExactSizeIterator for Iter<'_, T> {
211    fn len(&self) -> usize {
212        self.tail.len() + self.head.map_or(0, |_| 1)
213    }
214}
215
216impl<T> core::iter::FusedIterator for Iter<'_, T> {}
217
218impl<T> NonEmpty<T> {
219    /// Alias for [`NonEmpty::singleton`].
220    pub const fn new(e: T) -> Self {
221        Self::singleton(e)
222    }
223
224    /// Converts from `&NonEmpty<T>` to `NonEmpty<&T>`.
225    pub fn as_ref(&self) -> NonEmpty<&T> {
226        NonEmpty {
227            head: &self.head,
228            tail: self.tail.iter().collect(),
229        }
230    }
231
232    /// Attempt to convert an iterator into a `NonEmpty` vector.
233    /// Returns `None` if the iterator was empty.
234    pub fn collect<I>(iter: I) -> Option<NonEmpty<T>>
235    where
236        I: IntoIterator<Item = T>,
237    {
238        let mut iter = iter.into_iter();
239        let head = iter.next()?;
240        Some(Self {
241            head,
242            tail: iter.collect(),
243        })
244    }
245
246    /// Create a new non-empty list with an initial element.
247    pub const fn singleton(head: T) -> Self {
248        NonEmpty {
249            head,
250            tail: Vec::new(),
251        }
252    }
253
254    /// Always returns false.
255    pub const fn is_empty(&self) -> bool {
256        false
257    }
258
259    /// Get the first element. Never fails.
260    pub const fn first(&self) -> &T {
261        &self.head
262    }
263
264    /// Get the mutable reference to the first element. Never fails.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use nonempty::NonEmpty;
270    ///
271    /// let mut non_empty = NonEmpty::new(42);
272    /// let head = non_empty.first_mut();
273    /// *head += 1;
274    /// assert_eq!(non_empty.first(), &43);
275    ///
276    /// let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
277    /// let head = non_empty.first_mut();
278    /// *head *= 42;
279    /// assert_eq!(non_empty.first(), &42);
280    /// ```
281    pub fn first_mut(&mut self) -> &mut T {
282        &mut self.head
283    }
284
285    /// Get the possibly-empty tail of the list.
286    ///
287    /// ```
288    /// use nonempty::NonEmpty;
289    ///
290    /// let non_empty = NonEmpty::new(42);
291    /// assert_eq!(non_empty.tail(), &[]);
292    ///
293    /// let non_empty = NonEmpty::from((1, vec![4, 2, 3]));
294    /// assert_eq!(non_empty.tail(), &[4, 2, 3]);
295    /// ```
296    pub fn tail(&self) -> &[T] {
297        &self.tail
298    }
299
300    /// Push an element to the end of the list.
301    pub fn push(&mut self, e: T) {
302        self.tail.push(e)
303    }
304
305    /// Pop an element from the end of the list.
306    pub fn pop(&mut self) -> Option<T> {
307        self.tail.pop()
308    }
309
310    /// Inserts an element at position index within the vector, shifting all elements after it to the right.
311    ///
312    /// # Panics
313    ///
314    /// Panics if index > len.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use nonempty::NonEmpty;
320    ///
321    /// let mut non_empty = NonEmpty::from((1, vec![2, 3]));
322    /// non_empty.insert(1, 4);
323    /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3])));
324    /// non_empty.insert(4, 5);
325    /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3, 5])));
326    /// non_empty.insert(0, 42);
327    /// assert_eq!(non_empty, NonEmpty::from((42, vec![1, 4, 2, 3, 5])));
328    /// ```
329    pub fn insert(&mut self, index: usize, element: T) {
330        let len = self.len();
331        assert!(index <= len);
332
333        if index == 0 {
334            let head = mem::replace(&mut self.head, element);
335            self.tail.insert(0, head);
336        } else {
337            self.tail.insert(index - 1, element);
338        }
339    }
340
341    /// Get the length of the list.
342    pub fn len(&self) -> usize {
343        self.tail.len() + 1
344    }
345
346    /// Gets the length of the list as a NonZeroUsize.
347    pub fn len_nonzero(&self) -> NonZeroUsize {
348        unsafe { NonZeroUsize::new_unchecked(self.tail.len().saturating_add(1)) }
349    }
350
351    /// Get the capacity of the list.
352    pub fn capacity(&self) -> NonZeroUsize {
353        NonZeroUsize::MIN.saturating_add(self.tail.capacity())
354    }
355
356    /// Get the last element. Never fails.
357    pub fn last(&self) -> &T {
358        match self.tail.last() {
359            None => &self.head,
360            Some(e) => e,
361        }
362    }
363
364    /// Get the last element mutably.
365    pub fn last_mut(&mut self) -> &mut T {
366        match self.tail.last_mut() {
367            None => &mut self.head,
368            Some(e) => e,
369        }
370    }
371
372    /// Check whether an element is contained in the list.
373    ///
374    /// ```
375    /// use nonempty::NonEmpty;
376    ///
377    /// let mut l = NonEmpty::from((42, vec![36, 58]));
378    ///
379    /// assert!(l.contains(&42));
380    /// assert!(!l.contains(&101));
381    /// ```
382    pub fn contains(&self, x: &T) -> bool
383    where
384        T: PartialEq,
385    {
386        self.iter().any(|e| e == x)
387    }
388
389    /// Get an element by index.
390    pub fn get(&self, index: usize) -> Option<&T> {
391        if index == 0 {
392            Some(&self.head)
393        } else {
394            self.tail.get(index - 1)
395        }
396    }
397
398    /// Get an element by index, mutably.
399    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
400        if index == 0 {
401            Some(&mut self.head)
402        } else {
403            self.tail.get_mut(index - 1)
404        }
405    }
406
407    /// Truncate the list to a certain size. Must be greater than `0`.
408    pub fn truncate(&mut self, len: usize) {
409        assert!(len >= 1);
410        self.tail.truncate(len - 1);
411    }
412
413    /// ```
414    /// use nonempty::NonEmpty;
415    ///
416    /// let mut l = NonEmpty::from((42, vec![36, 58]));
417    ///
418    /// let mut l_iter = l.iter();
419    ///
420    /// assert_eq!(l_iter.len(), 3);
421    /// assert_eq!(l_iter.next(), Some(&42));
422    /// assert_eq!(l_iter.next(), Some(&36));
423    /// assert_eq!(l_iter.next(), Some(&58));
424    /// assert_eq!(l_iter.next(), None);
425    /// ```
426    pub fn iter(&self) -> Iter<T> {
427        Iter {
428            head: Some(&self.head),
429            tail: &self.tail,
430        }
431    }
432
433    /// ```
434    /// use nonempty::NonEmpty;
435    ///
436    /// let mut l = NonEmpty::new(42);
437    /// l.push(36);
438    /// l.push(58);
439    ///
440    /// for i in l.iter_mut() {
441    ///     *i *= 10;
442    /// }
443    ///
444    /// let mut l_iter = l.iter();
445    ///
446    /// assert_eq!(l_iter.next(), Some(&420));
447    /// assert_eq!(l_iter.next(), Some(&360));
448    /// assert_eq!(l_iter.next(), Some(&580));
449    /// assert_eq!(l_iter.next(), None);
450    /// ```
451    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
452        iter::once(&mut self.head).chain(self.tail.iter_mut())
453    }
454
455    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
456    /// proceeding with a computation. Using `from_slice` will give us a proof
457    /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
458    /// the caller to handle the `None` case.
459    ///
460    /// # Example Use
461    ///
462    /// ```
463    /// use nonempty::NonEmpty;
464    ///
465    /// let non_empty_vec = NonEmpty::from_slice(&[1, 2, 3, 4, 5]);
466    /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
467    ///
468    /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_slice(&[]);
469    /// assert!(empty_vec.is_none());
470    /// ```
471    pub fn from_slice(slice: &[T]) -> Option<NonEmpty<T>>
472    where
473        T: Clone,
474    {
475        slice.split_first().map(|(h, t)| NonEmpty {
476            head: h.clone(),
477            tail: t.into(),
478        })
479    }
480
481    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
482    /// proceeding with a computation. Using `from_vec` will give us a proof
483    /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
484    /// the caller to handle the `None` case.
485    ///
486    /// This version will consume the `Vec` you pass in. If you would rather pass the data as a
487    /// slice then use `NonEmpty::from_slice`.
488    ///
489    /// # Example Use
490    ///
491    /// ```
492    /// use nonempty::NonEmpty;
493    ///
494    /// let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]);
495    /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
496    ///
497    /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_vec(vec![]);
498    /// assert!(empty_vec.is_none());
499    /// ```
500    pub fn from_vec(mut vec: Vec<T>) -> Option<NonEmpty<T>> {
501        if vec.is_empty() {
502            None
503        } else {
504            let head = vec.remove(0);
505            Some(NonEmpty { head, tail: vec })
506        }
507    }
508
509    /// Deconstruct a `NonEmpty` into its head and tail.
510    /// This operation never fails since we are guaranteed
511    /// to have a head element.
512    ///
513    /// # Example Use
514    ///
515    /// ```
516    /// use nonempty::NonEmpty;
517    ///
518    /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
519    ///
520    /// // Guaranteed to have the head and we also get the tail.
521    /// assert_eq!(non_empty.split_first(), (&1, &[2, 3, 4, 5][..]));
522    ///
523    /// let non_empty = NonEmpty::new(1);
524    ///
525    /// // Guaranteed to have the head element.
526    /// assert_eq!(non_empty.split_first(), (&1, &[][..]));
527    /// ```
528    pub fn split_first(&self) -> (&T, &[T]) {
529        (&self.head, &self.tail)
530    }
531
532    /// Deconstruct a `NonEmpty` into its first, last, and
533    /// middle elements, in that order.
534    ///
535    /// If there is only one element then last is `None`.
536    ///
537    /// # Example Use
538    ///
539    /// ```
540    /// use nonempty::NonEmpty;
541    ///
542    /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
543    ///
544    /// // When there are two or more elements, the last element is represented
545    /// // as a `Some`. Elements preceding it, except for the first, are returned
546    /// // in the middle.
547    /// assert_eq!(non_empty.split(), (&1, &[2, 3, 4][..], Some(&5)));
548    ///
549    /// let non_empty = NonEmpty::new(1);
550    ///
551    /// // The last element is `None` when there's only one element.
552    /// assert_eq!(non_empty.split(), (&1, &[][..], None));
553    /// ```
554    pub fn split(&self) -> (&T, &[T], Option<&T>) {
555        match self.tail.split_last() {
556            None => (&self.head, &[], None),
557            Some((last, middle)) => (&self.head, middle, Some(last)),
558        }
559    }
560
561    /// Append a `Vec` to the tail of the `NonEmpty`.
562    ///
563    /// # Example Use
564    ///
565    /// ```
566    /// use nonempty::NonEmpty;
567    ///
568    /// let mut non_empty = NonEmpty::new(1);
569    /// let mut vec = vec![2, 3, 4, 5];
570    /// non_empty.append(&mut vec);
571    ///
572    /// let mut expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
573    ///
574    /// assert_eq!(non_empty, expected);
575    /// ```
576    pub fn append(&mut self, other: &mut Vec<T>) {
577        self.tail.append(other)
578    }
579
580    /// A structure preserving `map`. This is useful for when
581    /// we wish to keep the `NonEmpty` structure guaranteeing
582    /// that there is at least one element. Otherwise, we can
583    /// use `nonempty.iter().map(f)`.
584    ///
585    /// # Examples
586    ///
587    /// ```
588    /// use nonempty::NonEmpty;
589    ///
590    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
591    ///
592    /// let squares = non_empty.map(|i| i * i);
593    ///
594    /// let expected = NonEmpty::from((1, vec![4, 9, 16, 25]));
595    ///
596    /// assert_eq!(squares, expected);
597    /// ```
598    pub fn map<U, F>(self, mut f: F) -> NonEmpty<U>
599    where
600        F: FnMut(T) -> U,
601    {
602        NonEmpty {
603            head: f(self.head),
604            tail: self.tail.into_iter().map(f).collect(),
605        }
606    }
607
608    /// A structure preserving, fallible mapping function.
609    pub fn try_map<E, U, F>(self, mut f: F) -> Result<NonEmpty<U>, E>
610    where
611        F: FnMut(T) -> Result<U, E>,
612    {
613        Ok(NonEmpty {
614            head: f(self.head)?,
615            tail: self.tail.into_iter().map(f).collect::<Result<_, _>>()?,
616        })
617    }
618
619    /// When we have a function that goes from some `T` to a `NonEmpty<U>`,
620    /// we may want to apply it to a `NonEmpty<T>` but keep the structure flat.
621    /// This is where `flat_map` shines.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// use nonempty::NonEmpty;
627    ///
628    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
629    ///
630    /// let windows = non_empty.flat_map(|i| {
631    ///     let mut next = NonEmpty::new(i + 5);
632    ///     next.push(i + 6);
633    ///     next
634    /// });
635    ///
636    /// let expected = NonEmpty::from((6, vec![7, 7, 8, 8, 9, 9, 10, 10, 11]));
637    ///
638    /// assert_eq!(windows, expected);
639    /// ```
640    pub fn flat_map<U, F>(self, mut f: F) -> NonEmpty<U>
641    where
642        F: FnMut(T) -> NonEmpty<U>,
643    {
644        let mut heads = f(self.head);
645        let mut tails = self
646            .tail
647            .into_iter()
648            .flat_map(|t| f(t).into_iter())
649            .collect();
650        heads.append(&mut tails);
651        heads
652    }
653
654    /// Flatten nested `NonEmpty`s into a single one.
655    ///
656    /// # Examples
657    ///
658    /// ```
659    /// use nonempty::NonEmpty;
660    ///
661    /// let non_empty = NonEmpty::from((
662    ///     NonEmpty::from((1, vec![2, 3])),
663    ///     vec![NonEmpty::from((4, vec![5]))],
664    /// ));
665    ///
666    /// let expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
667    ///
668    /// assert_eq!(NonEmpty::flatten(non_empty), expected);
669    /// ```
670    pub fn flatten(full: NonEmpty<NonEmpty<T>>) -> Self {
671        full.flat_map(|n| n)
672    }
673
674    /// Binary searches this sorted non-empty vector for a given element.
675    ///
676    /// If the value is found then Result::Ok is returned, containing the index of the matching element.
677    /// If there are multiple matches, then any one of the matches could be returned.
678    ///
679    /// If the value is not found then Result::Err is returned, containing the index where a
680    /// matching element could be inserted while maintaining sorted order.
681    ///
682    /// # Examples
683    ///
684    /// ```
685    /// use nonempty::NonEmpty;
686    ///
687    /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
688    /// assert_eq!(non_empty.binary_search(&0),   Ok(0));
689    /// assert_eq!(non_empty.binary_search(&13),  Ok(9));
690    /// assert_eq!(non_empty.binary_search(&4),   Err(7));
691    /// assert_eq!(non_empty.binary_search(&100), Err(13));
692    /// let r = non_empty.binary_search(&1);
693    /// assert!(match r { Ok(1..=4) => true, _ => false, });
694    /// ```
695    ///
696    /// If you want to insert an item to a sorted non-empty vector, while maintaining sort order:
697    ///
698    /// ```
699    /// use nonempty::NonEmpty;
700    ///
701    /// let mut non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
702    /// let num = 42;
703    /// let idx = non_empty.binary_search(&num).unwrap_or_else(|x| x);
704    /// non_empty.insert(idx, num);
705    /// assert_eq!(non_empty, NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55])));
706    /// ```
707    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
708    where
709        T: Ord,
710    {
711        self.binary_search_by(|p| p.cmp(x))
712    }
713
714    /// Binary searches this sorted non-empty with a comparator function.
715    ///
716    /// The comparator function should implement an order consistent with the sort order of the underlying slice,
717    /// returning an order code that indicates whether its argument is Less, Equal or Greater the desired target.
718    ///
719    /// If the value is found then Result::Ok is returned, containing the index of the matching element.
720    /// If there are multiple matches, then any one of the matches could be returned.
721    /// If the value is not found then Result::Err is returned, containing the index where a matching element could be
722    /// inserted while maintaining sorted order.
723    ///
724    /// # Examples
725    ///
726    /// Looks up a series of four elements. The first is found, with a uniquely determined
727    /// position; the second and third are not found; the fourth could match any position in `[1,4]`.
728    ///
729    /// ```
730    /// use nonempty::NonEmpty;
731    ///
732    /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
733    /// let seek = 0;
734    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
735    /// let seek = 13;
736    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
737    /// let seek = 4;
738    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
739    /// let seek = 100;
740    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
741    /// let seek = 1;
742    /// let r = non_empty.binary_search_by(|probe| probe.cmp(&seek));
743    /// assert!(match r { Ok(1..=4) => true, _ => false, });
744    /// ```
745    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
746    where
747        F: FnMut(&'a T) -> Ordering,
748    {
749        match f(&self.head) {
750            Ordering::Equal => Ok(0),
751            Ordering::Greater => Err(0),
752            Ordering::Less => self
753                .tail
754                .binary_search_by(f)
755                .map(|index| index + 1)
756                .map_err(|index| index + 1),
757        }
758    }
759
760    /// Binary searches this sorted non-empty vector with a key extraction function.
761    ///
762    /// Assumes that the vector is sorted by the key.
763    ///
764    /// If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches,
765    /// then any one of the matches could be returned. If the value is not found then Result::Err is returned,
766    /// containing the index where a matching element could be inserted while maintaining sorted order.
767    ///
768    /// # Examples
769    ///
770    /// Looks up a series of four elements in a non-empty vector of pairs sorted by their second elements.
771    /// The first is found, with a uniquely determined position; the second and third are not found;
772    /// the fourth could match any position in [1, 4].
773    ///
774    /// ```
775    /// use nonempty::NonEmpty;
776    ///
777    /// let non_empty = NonEmpty::from((
778    ///     (0, 0),
779    ///     vec![(2, 1), (4, 1), (5, 1), (3, 1),
780    ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
781    ///          (1, 21), (2, 34), (4, 55)]
782    /// ));
783    ///
784    /// assert_eq!(non_empty.binary_search_by_key(&0, |&(a,b)| b),  Ok(0));
785    /// assert_eq!(non_empty.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
786    /// assert_eq!(non_empty.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
787    /// assert_eq!(non_empty.binary_search_by_key(&100, |&(a,b)| b), Err(13));
788    /// let r = non_empty.binary_search_by_key(&1, |&(a,b)| b);
789    /// assert!(match r { Ok(1..=4) => true, _ => false, });
790    /// ```
791    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
792    where
793        B: Ord,
794        F: FnMut(&'a T) -> B,
795    {
796        self.binary_search_by(|k| f(k).cmp(b))
797    }
798
799    /// Returns the maximum element in the non-empty vector.
800    ///
801    /// This will return the first item in the vector if the tail is empty.
802    ///
803    /// # Examples
804    ///
805    /// ```
806    /// use nonempty::NonEmpty;
807    ///
808    /// let non_empty = NonEmpty::new(42);
809    /// assert_eq!(non_empty.maximum(), &42);
810    ///
811    /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
812    /// assert_eq!(non_empty.maximum(), &76);
813    /// ```
814    pub fn maximum(&self) -> &T
815    where
816        T: Ord,
817    {
818        self.maximum_by(|i, j| i.cmp(j))
819    }
820
821    /// Returns the minimum element in the non-empty vector.
822    ///
823    /// This will return the first item in the vector if the tail is empty.
824    ///
825    /// # Examples
826    ///
827    /// ```
828    /// use nonempty::NonEmpty;
829    ///
830    /// let non_empty = NonEmpty::new(42);
831    /// assert_eq!(non_empty.minimum(), &42);
832    ///
833    /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
834    /// assert_eq!(non_empty.minimum(), &-34);
835    /// ```
836    pub fn minimum(&self) -> &T
837    where
838        T: Ord,
839    {
840        self.minimum_by(|i, j| i.cmp(j))
841    }
842
843    /// Returns the element that gives the maximum value with respect to the specified comparison function.
844    ///
845    /// This will return the first item in the vector if the tail is empty.
846    ///
847    /// # Examples
848    ///
849    /// ```
850    /// use nonempty::NonEmpty;
851    ///
852    /// let non_empty = NonEmpty::new((0, 42));
853    /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
854    ///
855    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
856    /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(4, 42));
857    /// ```
858    pub fn maximum_by<F>(&self, mut compare: F) -> &T
859    where
860        F: FnMut(&T, &T) -> Ordering,
861    {
862        let mut max = &self.head;
863        for i in self.tail.iter() {
864            max = match compare(max, i) {
865                Ordering::Equal => max,
866                Ordering::Less => i,
867                Ordering::Greater => max,
868            };
869        }
870        max
871    }
872
873    /// Returns the element that gives the minimum value with respect to the specified comparison function.
874    ///
875    /// This will return the first item in the vector if the tail is empty.
876    ///
877    /// ```
878    /// use nonempty::NonEmpty;
879    ///
880    /// let non_empty = NonEmpty::new((0, 42));
881    /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
882    ///
883    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
884    /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 76));
885    /// ```
886    pub fn minimum_by<F>(&self, mut compare: F) -> &T
887    where
888        F: FnMut(&T, &T) -> Ordering,
889    {
890        self.maximum_by(|a, b| compare(a, b).reverse())
891    }
892
893    /// Returns the element that gives the maximum value with respect to the specified function.
894    ///
895    /// This will return the first item in the vector if the tail is empty.
896    ///
897    /// # Examples
898    ///
899    /// ```
900    /// use nonempty::NonEmpty;
901    ///
902    /// let non_empty = NonEmpty::new((0, 42));
903    /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(0, 42));
904    ///
905    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
906    /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(4, 42));
907    /// assert_eq!(non_empty.maximum_by_key(|(k, _)| -k), &(0, 76));
908    /// ```
909    pub fn maximum_by_key<U, F>(&self, mut f: F) -> &T
910    where
911        U: Ord,
912        F: FnMut(&T) -> U,
913    {
914        self.maximum_by(|i, j| f(i).cmp(&f(j)))
915    }
916
917    /// Returns the element that gives the minimum value with respect to the specified function.
918    ///
919    /// This will return the first item in the vector if the tail is empty.
920    ///
921    /// # Examples
922    ///
923    /// ```
924    /// use nonempty::NonEmpty;
925    ///
926    /// let non_empty = NonEmpty::new((0, 42));
927    /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 42));
928    ///
929    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
930    /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 76));
931    /// assert_eq!(non_empty.minimum_by_key(|(k, _)| -k), &(4, 42));
932    /// ```
933    pub fn minimum_by_key<U, F>(&self, mut f: F) -> &T
934    where
935        U: Ord,
936        F: FnMut(&T) -> U,
937    {
938        self.minimum_by(|i, j| f(i).cmp(&f(j)))
939    }
940
941    /// Sorts the nonempty.
942    ///
943    /// The implementation uses [`slice::sort`](slice::sort) for the tail and then checks where the
944    /// head belongs. If the head is already the smallest element, this should be as fast as sorting a
945    /// slice. However, if the head needs to be inserted, then it incurs extra cost for removing
946    /// the new head from the tail and adding the old head at the correct index.
947    ///
948    /// # Examples
949    ///
950    /// ```
951    /// use nonempty::nonempty;
952    ///
953    /// let mut non_empty = nonempty![-5, 4, 1, -3, 2];
954    ///
955    /// non_empty.sort();
956    /// assert!(non_empty == nonempty![-5, -3, 1, 2, 4]);
957    /// ```
958    pub fn sort(&mut self)
959    where
960        T: Ord,
961    {
962        self.tail.sort();
963        let index = match self.tail.binary_search(&self.head) {
964            Ok(index) => index,
965            Err(index) => index,
966        };
967
968        if index != 0 {
969            let new_head = self.tail.remove(0);
970            let head = mem::replace(&mut self.head, new_head);
971            self.tail.insert(index - 1, head);
972        }
973    }
974}
975
976impl<T: Default> Default for NonEmpty<T> {
977    fn default() -> Self {
978        Self::new(T::default())
979    }
980}
981
982impl<T> From<NonEmpty<T>> for Vec<T> {
983    /// Turns a non-empty list into a Vec.
984    fn from(nonempty: NonEmpty<T>) -> Vec<T> {
985        iter::once(nonempty.head).chain(nonempty.tail).collect()
986    }
987}
988
989impl<T> From<NonEmpty<T>> for (T, Vec<T>) {
990    /// Turns a non-empty list into a Vec.
991    fn from(nonempty: NonEmpty<T>) -> (T, Vec<T>) {
992        (nonempty.head, nonempty.tail)
993    }
994}
995
996impl<T> From<(T, Vec<T>)> for NonEmpty<T> {
997    /// Turns a pair of an element and a Vec into
998    /// a NonEmpty.
999    fn from((head, tail): (T, Vec<T>)) -> Self {
1000        NonEmpty { head, tail }
1001    }
1002}
1003
1004impl<T> IntoIterator for NonEmpty<T> {
1005    type Item = T;
1006    type IntoIter = iter::Chain<iter::Once<T>, vec::IntoIter<Self::Item>>;
1007
1008    fn into_iter(self) -> Self::IntoIter {
1009        iter::once(self.head).chain(self.tail)
1010    }
1011}
1012
1013impl<'a, T> IntoIterator for &'a NonEmpty<T> {
1014    type Item = &'a T;
1015    type IntoIter = iter::Chain<iter::Once<&'a T>, core::slice::Iter<'a, T>>;
1016
1017    fn into_iter(self) -> Self::IntoIter {
1018        iter::once(&self.head).chain(self.tail.iter())
1019    }
1020}
1021
1022impl<T> core::ops::Index<usize> for NonEmpty<T> {
1023    type Output = T;
1024
1025    /// ```
1026    /// use nonempty::NonEmpty;
1027    ///
1028    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
1029    ///
1030    /// assert_eq!(non_empty[0], 1);
1031    /// assert_eq!(non_empty[1], 2);
1032    /// assert_eq!(non_empty[3], 4);
1033    /// ```
1034    fn index(&self, index: usize) -> &T {
1035        if index > 0 {
1036            &self.tail[index - 1]
1037        } else {
1038            &self.head
1039        }
1040    }
1041}
1042
1043impl<T> core::ops::IndexMut<usize> for NonEmpty<T> {
1044    fn index_mut(&mut self, index: usize) -> &mut T {
1045        if index > 0 {
1046            &mut self.tail[index - 1]
1047        } else {
1048            &mut self.head
1049        }
1050    }
1051}
1052
1053impl<A> Extend<A> for NonEmpty<A> {
1054    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
1055        self.tail.extend(iter)
1056    }
1057}
1058
1059#[cfg(feature = "serialize")]
1060pub mod serialize {
1061    use core::{convert::TryFrom, fmt};
1062
1063    use alloc::vec::Vec;
1064
1065    use super::NonEmpty;
1066
1067    #[derive(Debug)]
1068    pub enum Error {
1069        Empty,
1070    }
1071
1072    impl fmt::Display for Error {
1073        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1074            match self {
1075                Self::Empty => f.write_str(
1076                    "the vector provided was empty, NonEmpty needs at least one element",
1077                ),
1078            }
1079        }
1080    }
1081
1082    impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
1083        type Error = Error;
1084
1085        fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1086            NonEmpty::from_vec(vec).ok_or(Error::Empty)
1087        }
1088    }
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use alloc::{string::String, vec::Vec};
1094
1095    use crate::NonEmpty;
1096
1097    #[test]
1098    fn test_from_conversion() {
1099        let result = NonEmpty::from((1, vec![2, 3, 4, 5]));
1100        let expected = NonEmpty {
1101            head: 1,
1102            tail: vec![2, 3, 4, 5],
1103        };
1104        assert_eq!(result, expected);
1105    }
1106
1107    #[test]
1108    fn test_into_iter() {
1109        let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1110        for (i, n) in nonempty.into_iter().enumerate() {
1111            assert_eq!(i as i32, n);
1112        }
1113    }
1114
1115    #[test]
1116    fn test_iter_syntax() {
1117        let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1118        for n in &nonempty {
1119            let _ = *n; // Prove that we're dealing with references.
1120        }
1121        for _ in nonempty {}
1122    }
1123
1124    #[test]
1125    fn test_iter_both_directions() {
1126        let mut nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1127        assert_eq!(nonempty.iter().cloned().collect::<Vec<_>>(), [0, 1, 2, 3]);
1128        assert_eq!(
1129            nonempty.iter().rev().cloned().collect::<Vec<_>>(),
1130            [3, 2, 1, 0]
1131        );
1132        assert_eq!(
1133            nonempty.iter_mut().rev().collect::<Vec<_>>(),
1134            [&mut 3, &mut 2, &mut 1, &mut 0]
1135        );
1136    }
1137
1138    #[test]
1139    fn test_iter_both_directions_at_once() {
1140        let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1141        let mut i = nonempty.iter();
1142        assert_eq!(i.next(), Some(&0));
1143        assert_eq!(i.next_back(), Some(&3));
1144        assert_eq!(i.next(), Some(&1));
1145        assert_eq!(i.next_back(), Some(&2));
1146        assert_eq!(i.next(), None);
1147        assert_eq!(i.next_back(), None);
1148    }
1149
1150    #[test]
1151    fn test_mutate_head() {
1152        let mut non_empty = NonEmpty::new(42);
1153        non_empty.head += 1;
1154        assert_eq!(non_empty.head, 43);
1155
1156        let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
1157        non_empty.head *= 42;
1158        assert_eq!(non_empty.head, 42);
1159    }
1160
1161    #[test]
1162    fn test_to_nonempty() {
1163        use core::iter::{empty, once};
1164
1165        assert_eq!(NonEmpty::<()>::collect(empty()), None);
1166        assert_eq!(NonEmpty::<()>::collect(once(())), Some(NonEmpty::new(())));
1167        assert_eq!(
1168            NonEmpty::<u8>::collect(once(1).chain(once(2))),
1169            Some(nonempty!(1, 2))
1170        );
1171    }
1172
1173    #[test]
1174    fn test_try_map() {
1175        assert_eq!(
1176            nonempty!(1, 2, 3, 4).try_map(Ok::<_, String>),
1177            Ok(nonempty!(1, 2, 3, 4))
1178        );
1179        assert_eq!(
1180            nonempty!(1, 2, 3, 4).try_map(|i| if i % 2 == 0 { Ok(i) } else { Err("not even") }),
1181            Err("not even")
1182        );
1183    }
1184
1185    #[test]
1186    fn test_nontrivial_minimum_by_key() {
1187        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1188        struct Position {
1189            x: i32,
1190            y: i32,
1191        }
1192        impl Position {
1193            pub fn distance_squared(&self, other: Position) -> u32 {
1194                let dx = self.x - other.x;
1195                let dy = self.y - other.y;
1196                (dx * dx + dy * dy) as u32
1197            }
1198        }
1199        let positions = nonempty![
1200            Position { x: 1, y: 1 },
1201            Position { x: 0, y: 0 },
1202            Position { x: 3, y: 4 }
1203        ];
1204        let target = Position { x: 1, y: 2 };
1205        let closest = positions.minimum_by_key(|position| position.distance_squared(target));
1206        assert_eq!(closest, &Position { x: 1, y: 1 });
1207    }
1208
1209    #[test]
1210    fn test_sort() {
1211        let mut numbers = nonempty![1];
1212        numbers.sort();
1213        assert_eq!(numbers, nonempty![1]);
1214
1215        let mut numbers = nonempty![2, 1, 3];
1216        numbers.sort();
1217        assert_eq!(numbers, nonempty![1, 2, 3]);
1218
1219        let mut numbers = nonempty![1, 3, 2];
1220        numbers.sort();
1221        assert_eq!(numbers, nonempty![1, 2, 3]);
1222
1223        let mut numbers = nonempty![3, 2, 1];
1224        numbers.sort();
1225        assert_eq!(numbers, nonempty![1, 2, 3]);
1226    }
1227
1228    #[cfg(feature = "serialize")]
1229    mod serialize {
1230        use crate::NonEmpty;
1231        use alloc::boxed::Box;
1232        use serde::{Deserialize, Serialize};
1233
1234        #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
1235        pub struct SimpleSerializable(pub i32);
1236
1237        #[test]
1238        fn test_simple_round_trip() -> Result<(), Box<dyn core::error::Error>> {
1239            // Given
1240            let mut non_empty = NonEmpty::new(SimpleSerializable(42));
1241            non_empty.push(SimpleSerializable(777));
1242
1243            // When
1244            let res = serde_json::from_str::<'_, NonEmpty<SimpleSerializable>>(
1245                &serde_json::to_string(&non_empty)?,
1246            )?;
1247
1248            // Then
1249            assert_eq!(res, non_empty);
1250
1251            Ok(())
1252        }
1253
1254        #[test]
1255        fn test_serialization() -> Result<(), Box<dyn core::error::Error>> {
1256            let ne = nonempty![1, 2, 3, 4, 5];
1257            let ve = vec![1, 2, 3, 4, 5];
1258
1259            assert_eq!(serde_json::to_string(&ne)?, serde_json::to_string(&ve)?);
1260
1261            Ok(())
1262        }
1263    }
1264
1265    #[cfg(feature = "bincode")]
1266    mod bincode {
1267        use crate::NonEmpty;
1268        use alloc::boxed::Box;
1269
1270        #[derive(Clone, Debug, Eq, PartialEq, bincode::Encode, bincode::Decode)]
1271        pub struct SimpleSerializable(pub i32);
1272
1273        #[test]
1274        fn test_simple_round_trip() -> Result<(), Box<dyn core::error::Error>> {
1275            // Given
1276            let mut non_empty = NonEmpty::new(SimpleSerializable(42));
1277            non_empty.push(SimpleSerializable(777));
1278
1279            // When
1280            let config = bincode::config::standard();
1281            let (res, _) = bincode::decode_from_slice::<NonEmpty<SimpleSerializable>, _>(
1282                &bincode::encode_to_vec(non_empty.clone(), config)?,
1283                config,
1284            )?;
1285
1286            // Then
1287            assert_eq!(res, non_empty);
1288
1289            Ok(())
1290        }
1291    }
1292
1293    #[cfg(feature = "arbitrary")]
1294    mod arbitrary {
1295        use crate::NonEmpty;
1296        use arbitrary::{Arbitrary, Unstructured};
1297
1298        #[test]
1299        fn test_arbitrary_empty_tail() -> arbitrary::Result<()> {
1300            let mut u = Unstructured::new(&[1, 2, 3, 4]);
1301            let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1302            assert!(!ne.is_empty());
1303            assert_eq!(
1304                ne,
1305                NonEmpty {
1306                    head: 67305985,
1307                    tail: vec![],
1308                }
1309            );
1310            Ok(())
1311        }
1312
1313        #[test]
1314        fn test_arbitrary_with_tail() -> arbitrary::Result<()> {
1315            let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
1316            let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1317            assert!(!ne.is_empty());
1318            assert_eq!(
1319                ne,
1320                NonEmpty {
1321                    head: 67305985,
1322                    tail: vec![526086],
1323                }
1324            );
1325            Ok(())
1326        }
1327
1328        #[test]
1329        fn test_arbitrary_with_split() -> arbitrary::Result<()> {
1330            let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
1331            let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1332            let (head, middle, last) = ne.split();
1333            let mut tail = middle.to_vec();
1334            tail.extend(last);
1335            assert_eq!(ne, NonEmpty { head: *head, tail });
1336            Ok(())
1337        }
1338    }
1339}