nonempty_collections/
vector.rs

1//! Non-empty Vectors.
2
3use core::fmt;
4use std::cmp::Ordering;
5use std::fmt::Debug;
6use std::fmt::Formatter;
7use std::num::NonZeroUsize;
8
9#[cfg(feature = "serde")]
10use serde::Deserialize;
11#[cfg(feature = "serde")]
12use serde::Serialize;
13
14use crate::iter::FromNonEmptyIterator;
15use crate::iter::IntoNonEmptyIterator;
16use crate::iter::NonEmptyIterator;
17use crate::slice::NEChunks;
18
19/// Like the [`vec!`] macro, but enforces at least one argument. A nice
20/// short-hand for constructing [`NEVec`] values.
21///
22/// ```
23/// use nonempty_collections::nev;
24/// use nonempty_collections::NEVec;
25///
26/// let v = nev![1, 2, 3];
27/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
28///
29/// let v = nev![1];
30/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1]);
31///
32/// let v = nev![1; 3];
33/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1; 3]);
34/// ```
35///
36/// This won't compile!
37/// ``` compile_fail
38/// use nonempty_collections::nev;
39/// let v = nev![];
40/// ```
41///
42/// Neither will this.
43/// ``` compile_fail
44/// use nonempty_collections::nev;
45/// let v = nev![1; 0];
46/// ```
47///
48/// Consider also [`crate::nem!`] and [`crate::nes!`].
49#[macro_export]
50macro_rules! nev {
51    () => {compile_error!("An NEVec cannot be empty")};
52    ($h:expr, $( $x:expr ),* $(,)?) => {{
53        let mut v = $crate::NEVec::new($h);
54        $( v.push($x); )*
55        v
56    }};
57    ($h:expr) => {
58        $crate::NEVec::new($h)
59    };
60    ($elem:expr; $n:expr) => {{
61        let n = const { ::std::num::NonZero::new($n).expect("Length cannot be 0") };
62        $crate::vector::from_elem($elem, n)
63    }};
64}
65
66#[doc(hidden)]
67pub fn from_elem<T: Clone>(elem: T, n: NonZeroUsize) -> NEVec<T> {
68    NEVec {
69        inner: vec![elem; n.get()],
70    }
71}
72
73/// A non-empty, growable Vector.
74///
75/// The first element can always be accessed in constant time. Similarly,
76/// certain functions like [`NEVec::first`] and [`NEVec::last`] always succeed:
77///
78/// ```
79/// use nonempty_collections::nev;
80///
81/// let s = nev!["Fëanor", "Fingolfin", "Finarfin"];
82/// assert_eq!(&"Fëanor", s.first()); // There is always a first element.
83/// assert_eq!(&"Finarfin", s.last()); // There is always a last element.
84/// ```
85#[cfg_attr(
86    feature = "serde",
87    derive(Deserialize, Serialize),
88    serde(bound(serialize = "T: Clone + Serialize")),
89    serde(into = "Vec<T>", try_from = "Vec<T>")
90)]
91#[allow(clippy::unsafe_derive_deserialize)] // the non-empty invariant is enforced by the deserialize implementation
92#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct NEVec<T> {
94    inner: Vec<T>,
95}
96
97impl<T> NEVec<T> {
98    /// Create a new non-empty list with an initial element.
99    #[must_use]
100    pub fn new(head: T) -> Self {
101        NEVec { inner: vec![head] }
102    }
103
104    /// Creates a new `NEVec` with a single element and specified capacity.
105    #[must_use]
106    pub fn with_capacity(capacity: NonZeroUsize, head: T) -> Self {
107        let mut inner = Vec::with_capacity(capacity.get());
108        inner.push(head);
109        NEVec { inner }
110    }
111
112    /// Get the first element. Never fails.
113    #[must_use]
114    pub fn first(&self) -> &T {
115        unsafe { self.inner.get_unchecked(0) }
116    }
117
118    /// Get the mutable reference to the first element. Never fails.
119    ///
120    /// # Examples
121    ///
122    /// ```
123    /// use nonempty_collections::nev;
124    ///
125    /// let mut v = nev![42];
126    /// let head = v.first_mut();
127    /// *head += 1;
128    /// assert_eq!(v.first(), &43);
129    ///
130    /// let mut v = nev![1, 4, 2, 3];
131    /// let head = v.first_mut();
132    /// *head *= 42;
133    /// assert_eq!(v.first(), &42);
134    /// ```
135    #[must_use]
136    pub fn first_mut(&mut self) -> &mut T {
137        unsafe { self.inner.get_unchecked_mut(0) }
138    }
139
140    /// Push an element to the end of the list.
141    pub fn push(&mut self, e: T) {
142        self.inner.push(e);
143    }
144
145    /// Pop an element from the end of the list. Is a no-op when [`Self::len()`]
146    /// is 1.
147    ///
148    /// ```
149    /// use nonempty_collections::nev;
150    ///
151    /// let mut v = nev![1, 2];
152    /// assert_eq!(Some(2), v.pop());
153    /// assert_eq!(None, v.pop());
154    /// ```
155    pub fn pop(&mut self) -> Option<T> {
156        if self.len() > NonZeroUsize::MIN {
157            self.inner.pop()
158        } else {
159            None
160        }
161    }
162
163    /// Removes and returns the element at position `index` within the vector,
164    /// shifting all elements after it to the left.
165    ///
166    /// If this [`NEVec`] contains only one element, no removal takes place and
167    /// `None` will be returned. If there are more elements, the item at the
168    /// `index` is removed and returned.
169    ///
170    /// Note: Because this shifts over the remaining elements, it has a
171    /// worst-case performance of *O*(*n*). If you don't need the order of
172    /// elements to be preserved, use [`swap_remove`] instead.
173    ///
174    /// [`swap_remove`]: NEVec::swap_remove
175    ///
176    /// # Panics
177    ///
178    /// Panics if `index` is out of bounds and `self.len() > 1`
179    ///
180    /// # Examples
181    ///
182    /// ```
183    /// use nonempty_collections::nev;
184    ///
185    /// let mut v = nev![1, 2, 3];
186    /// assert_eq!(v.remove(1), Some(2));
187    /// assert_eq!(nev![1, 3], v);
188    /// ```
189    pub fn remove(&mut self, index: usize) -> Option<T> {
190        (self.len() > NonZeroUsize::MIN).then(|| self.inner.remove(index))
191    }
192
193    /// Removes an element from the vector and returns it.
194    ///
195    /// If this [`NEVec`] contains only one element, no removal takes place and
196    /// `None` will be returned. If there are more elements, the item at the
197    /// `index` is removed and returned.
198    ///
199    /// The removed element is replaced by the last element of the vector.
200    ///
201    /// This does not preserve ordering of the remaining elements, but is
202    /// *O*(1). If you need to preserve the element order, use [`remove`]
203    /// instead.
204    ///
205    /// [`remove`]: NEVec::remove
206    ///
207    /// # Panics
208    ///
209    /// Panics if `index` is out of bounds and `self.len() > 1`
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use nonempty_collections::nev;
215    ///
216    /// let mut v = nev![1, 2, 3, 4];
217    /// assert_eq!(v.swap_remove(1), Some(2));
218    /// assert_eq!(nev![1, 4, 3], v);
219    /// ```
220    pub fn swap_remove(&mut self, index: usize) -> Option<T> {
221        (self.len() > NonZeroUsize::MIN).then(|| self.inner.swap_remove(index))
222    }
223
224    /// Retains only the elements specified by the predicate.
225    ///
226    /// In other words, remove all elements `e` for which `f(&e)` returns
227    /// `false`. This method operates in place, visiting each element
228    /// exactly once in the original order, and preserves the order of the
229    /// retained elements.
230    ///
231    /// If there are one or more items retained `Ok(Self)` is returned with the
232    /// remaining items. If all items are removed, the inner `Vec` is returned
233    /// to allowed for reuse of the claimed memory.
234    ///
235    /// # Errors
236    /// Returns `Err` if no elements are retained.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use nonempty_collections::nev;
242    ///
243    /// let vec = nev![1, 2, 3, 4];
244    /// let vec = vec.retain(|&x| x % 2 == 0);
245    /// assert_eq!(Ok(nev![2, 4]), vec);
246    /// ```
247    pub fn retain<F>(self, mut f: F) -> Result<Self, Vec<T>>
248    where
249        F: FnMut(&T) -> bool,
250    {
251        self.retain_mut(|item| f(item))
252    }
253
254    /// Retains only the elements specified by the predicate, passing a mutable
255    /// reference to it.
256    ///
257    /// In other words, remove all elements `e` such that `f(&mut e)` returns
258    /// `false`. This method operates in place, visiting each element
259    /// exactly once in the original order, and preserves the order of the
260    /// retained elements.
261    ///
262    /// If there are one or more items retained `Ok(Self)` is returned with the
263    /// remaining items. If all items are removed, the inner `Vec` is returned
264    /// to allowed for reuse of the claimed memory.
265    ///
266    /// # Errors
267    /// Returns `Err` if no elements are retained.
268    ///
269    /// # Examples
270    ///
271    /// ```
272    /// use nonempty_collections::nev;
273    ///
274    /// let vec = nev![1, 2, 3, 4];
275    /// let vec = vec.retain_mut(|x| {
276    ///     if *x <= 3 {
277    ///         *x += 1;
278    ///         true
279    ///     } else {
280    ///         false
281    ///     }
282    /// });
283    /// assert_eq!(Ok(nev![2, 3, 4]), vec);
284    /// ```
285    pub fn retain_mut<F>(mut self, f: F) -> Result<Self, Vec<T>>
286    where
287        F: FnMut(&mut T) -> bool,
288    {
289        self.inner.retain_mut(f);
290        if self.inner.is_empty() {
291            Err(self.inner)
292        } else {
293            Ok(self)
294        }
295    }
296
297    /// Inserts an element at position index within the vector, shifting all
298    /// elements after it to the right.
299    ///
300    /// # Panics
301    ///
302    /// Panics if index > len.
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// use nonempty_collections::nev;
308    ///
309    /// let mut v = nev![1, 2, 3];
310    /// v.insert(1, 4);
311    /// assert_eq!(v, nev![1, 4, 2, 3]);
312    /// v.insert(4, 5);
313    /// assert_eq!(v, nev![1, 4, 2, 3, 5]);
314    /// v.insert(0, 42);
315    /// assert_eq!(v, nev![42, 1, 4, 2, 3, 5]);
316    /// ```
317    pub fn insert(&mut self, index: usize, element: T) {
318        self.inner.insert(index, element);
319    }
320
321    /// Get the length of the list.
322    #[must_use]
323    pub fn len(&self) -> NonZeroUsize {
324        unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
325    }
326
327    /// A `NEVec` is never empty.
328    #[deprecated(since = "0.1.0", note = "A NEVec is never empty.")]
329    #[must_use]
330    pub const fn is_empty(&self) -> bool {
331        false
332    }
333
334    /// Get the capacity of the list.
335    #[must_use]
336    pub fn capacity(&self) -> NonZeroUsize {
337        unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
338    }
339
340    /// Get the last element. Never fails.
341    #[must_use]
342    #[allow(clippy::missing_panics_doc)] // never fails
343    pub fn last(&self) -> &T {
344        self.inner.last().unwrap()
345    }
346
347    /// Get the last element mutably.
348    #[must_use]
349    #[allow(clippy::missing_panics_doc)] // never fails
350    pub fn last_mut(&mut self) -> &mut T {
351        self.inner.last_mut().unwrap()
352    }
353
354    /// Check whether an element is contained in the list.
355    ///
356    /// ```
357    /// use nonempty_collections::nev;
358    ///
359    /// let mut l = nev![42, 36, 58];
360    ///
361    /// assert!(l.contains(&42));
362    /// assert!(!l.contains(&101));
363    /// ```
364    #[must_use]
365    pub fn contains(&self, x: &T) -> bool
366    where
367        T: PartialEq,
368    {
369        self.inner.contains(x)
370    }
371
372    /// Get an element by index.
373    #[must_use]
374    pub fn get(&self, index: usize) -> Option<&T> {
375        self.inner.get(index)
376    }
377
378    /// Get an element by index, mutably.
379    #[must_use]
380    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
381        self.inner.get_mut(index)
382    }
383
384    /// Truncate the list to a certain size.
385    pub fn truncate(&mut self, len: NonZeroUsize) {
386        self.inner.truncate(len.get());
387    }
388
389    /// Returns a regular iterator over the values in this non-empty vector.
390    ///
391    /// For a `NonEmptyIterator` see `Self::nonempty_iter()`.
392    pub fn iter(&self) -> std::slice::Iter<'_, T> {
393        self.inner.iter()
394    }
395
396    /// Returns a regular mutable iterator over the values in this non-empty
397    /// vector.
398    ///
399    /// For a `NonEmptyIterator` see `Self::nonempty_iter_mut()`.
400    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
401        self.inner.iter_mut()
402    }
403
404    /// ```
405    /// use nonempty_collections::*;
406    ///
407    /// let mut l = nev![42, 36, 58];
408    ///
409    /// let mut iter = l.nonempty_iter();
410    /// let (first, mut rest_iter) = iter.next();
411    ///
412    /// assert_eq!(first, &42);
413    /// assert_eq!(rest_iter.next(), Some(&36));
414    /// assert_eq!(rest_iter.next(), Some(&58));
415    /// assert_eq!(rest_iter.next(), None);
416    /// ```
417    pub fn nonempty_iter(&self) -> Iter<'_, T> {
418        Iter {
419            iter: self.inner.iter(),
420        }
421    }
422
423    /// Returns an iterator that allows modifying each value.
424    ///
425    /// # Examples
426    ///
427    ///  ```
428    /// use nonempty_collections::*;
429    ///
430    /// let mut l = nev![42, 36, 58];
431    ///
432    /// for i in l.nonempty_iter_mut() {
433    ///     *i *= 10;
434    /// }
435    ///
436    /// let mut iter = l.nonempty_iter();
437    /// let (first, mut rest_iter) = iter.next();
438    ///
439    /// assert_eq!(first, &420);
440    /// assert_eq!(rest_iter.next(), Some(&360));
441    /// assert_eq!(rest_iter.next(), Some(&580));
442    /// assert_eq!(rest_iter.next(), None);
443    /// ```
444    pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, T> {
445        IterMut {
446            inner: self.inner.iter_mut(),
447        }
448    }
449
450    /// Creates a new non-empty vec by cloning the elements from the slice if it
451    /// is non-empty, returns `None` otherwise.
452    ///
453    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is
454    /// `NEVec` before proceeding with a computation. Using `try_from_slice`
455    /// will give us a proof that we have a `NEVec` in the `Some` branch,
456    /// otherwise it allows the caller to handle the `None` case.
457    ///
458    /// # Example use
459    ///
460    /// ```
461    /// use nonempty_collections::nev;
462    /// use nonempty_collections::NEVec;
463    ///
464    /// let v_vec = NEVec::try_from_slice(&[1, 2, 3, 4, 5]);
465    /// assert_eq!(v_vec, Some(nev![1, 2, 3, 4, 5]));
466    ///
467    /// let empty_vec: Option<NEVec<&u32>> = NEVec::try_from_slice(&[]);
468    /// assert!(empty_vec.is_none());
469    /// ```
470    #[must_use]
471    pub fn try_from_slice(slice: &[T]) -> Option<NEVec<T>>
472    where
473        T: Clone,
474    {
475        if slice.is_empty() {
476            None
477        } else {
478            Some(NEVec {
479                inner: slice.to_vec(),
480            })
481        }
482    }
483
484    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is
485    /// `NEVec` before proceeding with a computation. Using `try_from_vec` will
486    /// give us a proof that we have a `NEVec` in the `Some` branch,
487    /// otherwise it allows the caller to handle the `None` case.
488    ///
489    /// This version will consume the `Vec` you pass in. If you would rather
490    /// pass the data as a slice then use [`NEVec::try_from_slice`].
491    ///
492    /// # Example Use
493    ///
494    /// ```
495    /// use nonempty_collections::nev;
496    /// use nonempty_collections::NEVec;
497    ///
498    /// let v_vec = NEVec::try_from_vec(vec![1, 2, 3, 4, 5]);
499    /// assert_eq!(v_vec, Some(nev![1, 2, 3, 4, 5]));
500    ///
501    /// let empty_vec: Option<NEVec<&u32>> = NEVec::try_from_vec(vec![]);
502    /// assert!(empty_vec.is_none());
503    /// ```
504    #[must_use]
505    pub fn try_from_vec(vec: Vec<T>) -> Option<NEVec<T>> {
506        if vec.is_empty() {
507            None
508        } else {
509            Some(NEVec { inner: vec })
510        }
511    }
512
513    /// Deconstruct a `NEVec` into its head and tail. This operation never fails
514    /// since we are guaranteed to have a head element.
515    ///
516    /// # Example Use
517    ///
518    /// ```
519    /// use nonempty_collections::nev;
520    ///
521    /// let mut v = nev![1, 2, 3, 4, 5];
522    ///
523    /// // Guaranteed to have the head and we also get the tail.
524    /// assert_eq!(v.split_first(), (&1, &[2, 3, 4, 5][..]));
525    ///
526    /// let v = nev![1];
527    ///
528    /// // Guaranteed to have the head element.
529    /// assert_eq!(v.split_first(), (&1, &[][..]));
530    /// ```
531    #[must_use]
532    #[allow(clippy::missing_panics_doc)] // never fails
533    pub fn split_first(&self) -> (&T, &[T]) {
534        self.inner.split_first().unwrap()
535    }
536
537    /// Deconstruct a `NEVec` into its first, last, and
538    /// middle elements, in that order.
539    ///
540    /// If there is only one element then first == last.
541    ///
542    /// # Example Use
543    ///
544    /// ```
545    /// use nonempty_collections::nev;
546    ///
547    /// let mut v = nev![1, 2, 3, 4, 5];
548    ///
549    /// // Guaranteed to have the last element and the elements
550    /// // preceding it.
551    /// assert_eq!(v.split(), (&1, &[2, 3, 4][..], &5));
552    ///
553    /// let v = nev![1];
554    ///
555    /// // Guaranteed to have the last element.
556    /// assert_eq!(v.split(), (&1, &[][..], &1));
557    /// ```
558    #[must_use]
559    pub fn split(&self) -> (&T, &[T], &T) {
560        let (first, rest) = self.split_first();
561        if let Some((last, middle)) = rest.split_last() {
562            (first, middle, last)
563        } else {
564            (first, &[], first)
565        }
566    }
567
568    /// Append a `Vec` to the tail of the `NEVec`.
569    ///
570    /// # Example Use
571    ///
572    /// ```
573    /// use nonempty_collections::nev;
574    ///
575    /// let mut v = nev![1];
576    /// let mut vec = vec![2, 3, 4, 5];
577    /// v.append(&mut vec);
578    ///
579    /// let mut expected = nev![1, 2, 3, 4, 5];
580    /// assert_eq!(v, expected);
581    /// ```
582    pub fn append(&mut self, other: &mut Vec<T>) {
583        self.inner.append(other);
584    }
585
586    /// Binary searches this sorted non-empty vector for a given element.
587    ///
588    /// If the value is found then `Result::Ok` is returned, containing the
589    /// index of the matching element. If there are multiple matches, then any
590    /// one of the matches could be returned.
591    ///
592    /// # Errors
593    ///
594    /// If the value is not found then `Result::Err` is returned, containing the
595    /// index where a matching element could be inserted while maintaining
596    /// sorted order.
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// use nonempty_collections::nev;
602    ///
603    /// let v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
604    /// assert_eq!(v.binary_search(&0), Ok(0));
605    /// assert_eq!(v.binary_search(&13), Ok(9));
606    /// assert_eq!(v.binary_search(&4), Err(7));
607    /// assert_eq!(v.binary_search(&100), Err(13));
608    /// let r = v.binary_search(&1);
609    /// assert!(match r {
610    ///     Ok(1..=4) => true,
611    ///     _ => false,
612    /// });
613    /// ```
614    ///
615    /// If you want to insert an item to a sorted non-empty vector, while
616    /// maintaining sort order:
617    ///
618    /// ```
619    /// use nonempty_collections::nev;
620    ///
621    /// let mut v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
622    /// let num = 42;
623    /// let idx = v.binary_search(&num).unwrap_or_else(|x| x);
624    /// v.insert(idx, num);
625    /// assert_eq!(v, nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
626    /// ```
627    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
628    where
629        T: Ord,
630    {
631        self.binary_search_by(|p| p.cmp(x))
632    }
633
634    /// Binary searches this sorted non-empty with a comparator function.
635    ///
636    /// The comparator function should implement an order consistent with the
637    /// sort order of the underlying slice, returning an order code that
638    /// indicates whether its argument is Less, Equal or Greater the desired
639    /// target.
640    ///
641    /// If the value is found then `Result::Ok` is returned, containing the
642    /// index of the matching element. If there are multiple matches, then any
643    /// one of the matches could be returned.
644    ///
645    /// # Errors
646    /// If the value is not found then `Result::Err` is returned, containing the
647    /// index where a matching element could be inserted while maintaining
648    /// sorted order.
649    ///
650    /// # Examples
651    ///
652    /// Looks up a series of four elements. The first is found, with a uniquely
653    /// determined position; the second and third are not found; the fourth
654    /// could match any position from 1 to 4.
655    ///
656    /// ```
657    /// use nonempty_collections::nev;
658    ///
659    /// let v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
660    /// let seek = 0;
661    /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
662    /// let seek = 13;
663    /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
664    /// let seek = 4;
665    /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
666    /// let seek = 100;
667    /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
668    /// let seek = 1;
669    /// let r = v.binary_search_by(|probe| probe.cmp(&seek));
670    /// assert!(match r {
671    ///     Ok(1..=4) => true,
672    ///     _ => false,
673    /// });
674    /// ```
675    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
676    where
677        F: FnMut(&'a T) -> Ordering,
678    {
679        self.inner.binary_search_by(f)
680    }
681
682    /// Binary searches this sorted non-empty vector with a key extraction
683    /// function.
684    ///
685    /// Assumes that the vector is sorted by the key.
686    ///
687    /// If the value is found then `Result::Ok` is returned, containing the
688    /// index of the matching element. If there are multiple matches, then any
689    /// one of the matches could be returned.
690    ///
691    /// # Errors
692    /// If the value is not found then `Result::Err` is returned, containing the
693    /// index where a matching element could be inserted while maintaining
694    /// sorted order.
695    ///
696    /// # Examples
697    ///
698    /// Looks up a series of four elements in a non-empty vector of pairs sorted
699    /// by their second elements. The first is found, with a uniquely determined
700    /// position; the second and third are not found; the fourth could match any
701    /// position in [1, 4].
702    ///
703    /// ```
704    /// use nonempty_collections::nev;
705    ///
706    /// let v = nev![
707    ///     (0, 0),
708    ///     (2, 1),
709    ///     (4, 1),
710    ///     (5, 1),
711    ///     (3, 1),
712    ///     (1, 2),
713    ///     (2, 3),
714    ///     (4, 5),
715    ///     (5, 8),
716    ///     (3, 13),
717    ///     (1, 21),
718    ///     (2, 34),
719    ///     (4, 55)
720    /// ];
721    ///
722    /// assert_eq!(v.binary_search_by_key(&0, |&(a, b)| b), Ok(0));
723    /// assert_eq!(v.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
724    /// assert_eq!(v.binary_search_by_key(&4, |&(a, b)| b), Err(7));
725    /// assert_eq!(v.binary_search_by_key(&100, |&(a, b)| b), Err(13));
726    /// let r = v.binary_search_by_key(&1, |&(a, b)| b);
727    /// assert!(match r {
728    ///     Ok(1..=4) => true,
729    ///     _ => false,
730    /// });
731    /// ```
732    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
733    where
734        B: Ord,
735        F: FnMut(&'a T) -> B,
736    {
737        self.binary_search_by(|k| f(k).cmp(b))
738    }
739
740    /// Sorts the `NEVec` in place.
741    ///
742    /// See also [`slice::sort`].
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// use nonempty_collections::nev;
748    ///
749    /// let mut n = nev![5, 4, 3, 2, 1];
750    /// n.sort();
751    /// assert_eq!(nev![1, 2, 3, 4, 5], n);
752    ///
753    /// // Naturally, sorting a sorted result should remain the same.
754    /// n.sort();
755    /// assert_eq!(nev![1, 2, 3, 4, 5], n);
756    /// ```
757    pub fn sort(&mut self)
758    where
759        T: Ord,
760    {
761        self.inner.sort();
762    }
763
764    /// Like [`NEVec::sort`], but sorts the `NEVec` with a given comparison
765    /// function.
766    ///
767    /// See also [`slice::sort_by`].
768    ///
769    /// ```
770    /// use nonempty_collections::nev;
771    ///
772    /// let mut n = nev!["Sirion", "Gelion", "Narog"];
773    /// n.sort_by(|a, b| b.cmp(&a));
774    /// assert_eq!(nev!["Sirion", "Narog", "Gelion"], n);
775    /// ```
776    pub fn sort_by<F>(&mut self, f: F)
777    where
778        F: FnMut(&T, &T) -> Ordering,
779    {
780        self.inner.sort_by(f);
781    }
782
783    /// Like [`NEVec::sort`], but sorts the `NEVec` after first transforming
784    /// each element into something easily comparable. Beware of expensive key
785    /// functions, as the results of each call are not cached.
786    ///
787    /// See also [`slice::sort_by_key`].
788    ///
789    /// ```
790    /// use nonempty_collections::nev;
791    ///
792    /// let mut n = nev![-5, 4, -3, 2, 1];
793    /// n.sort_by_key(|x| x * x);
794    /// assert_eq!(nev![1, 2, -3, 4, -5], n);
795    ///
796    /// // Naturally, sorting a sorted result should remain the same.
797    /// n.sort_by_key(|x| x * x);
798    /// assert_eq!(nev![1, 2, -3, 4, -5], n);
799    /// ```
800    pub fn sort_by_key<K, F>(&mut self, f: F)
801    where
802        F: FnMut(&T) -> K,
803        K: Ord,
804    {
805        self.inner.sort_by_key(f);
806    }
807
808    /// Yields a `NESlice`.
809    #[must_use]
810    pub fn as_nonempty_slice(&self) -> crate::NESlice<'_, T> {
811        crate::NESlice::from_slice_unchecked(self.inner.as_slice())
812    }
813
814    /// Removes all but the first of consecutive elements in the vector that
815    /// resolve to the same key.
816    ///
817    /// If the vector is sorted, this removes all duplicates.
818    ///
819    /// # Examples
820    ///
821    /// ```
822    /// use nonempty_collections::nev;
823    /// let mut v = nev![10, 20, 21, 30, 20];
824    ///
825    /// v.dedup_by_key(|i| *i / 10);
826    ///
827    /// assert_eq!(nev![10, 20, 30, 20], v);
828    /// ```
829    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
830    where
831        F: FnMut(&mut T) -> K,
832        K: PartialEq,
833    {
834        self.dedup_by(|a, b| key(a) == key(b));
835    }
836
837    /// Removes all but the first of consecutive elements in the vector
838    /// satisfying a given equality relation.
839    ///
840    /// The `same_bucket` function is passed references to two elements from the
841    /// vector and must determine if the elements compare equal. The
842    /// elements are passed in opposite order from their order in the slice,
843    /// so if `same_bucket(a, b)` returns `true`, `a` is removed.
844    ///
845    /// If the vector is sorted, this removes all duplicates.
846    ///
847    /// # Examples
848    ///
849    /// ```
850    /// use nonempty_collections::nev;
851    /// let mut v = nev!["foo", "Foo", "foo", "bar", "Bar", "baz", "bar"];
852    ///
853    /// v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
854    ///
855    /// assert_eq!(nev!["foo", "bar", "baz", "bar"], v);
856    /// ```
857    pub fn dedup_by<F>(&mut self, same_bucket: F)
858    where
859        F: FnMut(&mut T, &mut T) -> bool,
860    {
861        self.inner.dedup_by(same_bucket);
862    }
863
864    /// Returns a non-empty iterator over `chunk_size` elements of the `NEVec`
865    /// at a time, starting at the beginning of the `NEVec`.
866    ///
867    /// ```
868    /// use std::num::NonZeroUsize;
869    ///
870    /// use nonempty_collections::*;
871    ///
872    /// let v = nev![1, 2, 3, 4, 5, 6];
873    /// let n = NonZeroUsize::new(2).unwrap();
874    /// let r = v.nonempty_chunks(n).collect::<NEVec<_>>();
875    ///
876    /// let a = nev![1, 2];
877    /// let b = nev![3, 4];
878    /// let c = nev![5, 6];
879    ///
880    /// assert_eq!(
881    ///     r,
882    ///     nev![
883    ///         a.as_nonempty_slice(),
884    ///         b.as_nonempty_slice(),
885    ///         c.as_nonempty_slice()
886    ///     ]
887    /// );
888    /// ```
889    pub fn nonempty_chunks(&self, chunk_size: NonZeroUsize) -> NEChunks<'_, T> {
890        NEChunks {
891            inner: self.inner.chunks(chunk_size.get()),
892        }
893    }
894
895    /// Returns the index of the partition point according to the given
896    /// predicate (the index of the first element of the second partition).
897    ///
898    /// The vector is assumed to be partitioned according to the given
899    /// predicate. This means that all elements for which the predicate
900    /// returns true are at the start of the vector and all elements for
901    /// which the predicate returns false are at the end. For example, `[7,
902    /// 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
903    /// (all odd numbers are at the start, all even at the end).
904    ///
905    /// If this vector is not partitioned, the returned result is unspecified
906    /// and meaningless, as this method performs a kind of binary search.
907    ///
908    /// See also [`NEVec::binary_search`], [`NEVec::binary_search_by`], and
909    /// [`NEVec::binary_search_by_key`].
910    ///
911    /// # Examples
912    ///
913    /// ```
914    /// # use nonempty_collections::*;
915    /// #
916    /// let v = nev![1, 2, 3, 3, 5, 6, 7];
917    /// let i = v.partition_point(|&x| x < 5);
918    ///
919    /// assert_eq!(i, 4);
920    /// ```
921    ///
922    /// If all elements of the non-empty vector match the predicate, then the
923    /// length of the vector will be returned:
924    ///
925    /// ```
926    /// # use nonempty_collections::*;
927    /// #
928    /// let a = nev![2, 4, 8];
929    /// assert_eq!(a.partition_point(|&x| x < 100), a.len().get());
930    /// ```
931    ///
932    /// If you want to insert an item to a sorted vector, while maintaining
933    /// sort order:
934    ///
935    /// ```
936    /// # use nonempty_collections::*;
937    /// #
938    /// let mut s = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
939    /// let num = 42;
940    /// let idx = s.partition_point(|&x| x < num);
941    /// s.insert(idx, num);
942    /// assert_eq!(s, nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
943    /// ```
944    #[must_use]
945    pub fn partition_point<P>(&self, mut pred: P) -> usize
946    where
947        P: FnMut(&T) -> bool,
948    {
949        self.binary_search_by(|x| {
950            if pred(x) {
951                Ordering::Less
952            } else {
953                Ordering::Greater
954            }
955        })
956        .unwrap_or_else(|i| i)
957    }
958}
959
960impl<T: PartialEq> NEVec<T> {
961    /// Removes consecutive repeated elements in the vector according to the
962    /// [`PartialEq`] trait implementation.
963    ///
964    /// If the vector is sorted, this removes all duplicates.
965    ///
966    /// # Examples
967    ///
968    /// ```
969    /// use nonempty_collections::nev;
970    /// let mut v = nev![1, 1, 1, 2, 3, 2, 2, 1];
971    /// v.dedup();
972    /// assert_eq!(nev![1, 2, 3, 2, 1], v);
973    /// ```
974    pub fn dedup(&mut self) {
975        self.dedup_by(|a, b| a == b);
976    }
977}
978
979impl<T> From<NEVec<T>> for Vec<T> {
980    /// Turns a non-empty list into a `Vec`.
981    fn from(nonempty: NEVec<T>) -> Vec<T> {
982        nonempty.inner
983    }
984}
985
986impl<T> From<(T, Vec<T>)> for NEVec<T> {
987    /// Turns a pair of an element and a `Vec` into
988    /// a `NEVec`.
989    fn from((head, tail): (T, Vec<T>)) -> Self {
990        let mut vec = vec![head];
991        vec.extend(tail);
992        NEVec { inner: vec }
993    }
994}
995
996/// ```
997/// use nonempty_collections::*;
998///
999/// let v0 = nev![1, 2, 3];
1000/// let v1: NEVec<_> = v0.nonempty_iter().cloned().collect();
1001/// assert_eq!(v0, v1);
1002/// ```
1003impl<T> FromNonEmptyIterator<T> for NEVec<T> {
1004    fn from_nonempty_iter<I>(iter: I) -> Self
1005    where
1006        I: IntoNonEmptyIterator<Item = T>,
1007    {
1008        NEVec {
1009            inner: iter.into_nonempty_iter().into_iter().collect(),
1010        }
1011    }
1012}
1013
1014/// A non-empty iterator over the values of an [`NEVec`].
1015#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1016pub struct Iter<'a, T: 'a> {
1017    iter: std::slice::Iter<'a, T>,
1018}
1019
1020impl<T> NonEmptyIterator for Iter<'_, T> {}
1021
1022impl<'a, T> IntoIterator for Iter<'a, T> {
1023    type Item = &'a T;
1024
1025    type IntoIter = std::slice::Iter<'a, T>;
1026
1027    fn into_iter(self) -> Self::IntoIter {
1028        self.iter
1029    }
1030}
1031
1032// FIXME(#26925) Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
1033impl<T> Clone for Iter<'_, T> {
1034    fn clone(&self) -> Self {
1035        Iter {
1036            iter: self.iter.clone(),
1037        }
1038    }
1039}
1040
1041impl<T: Debug> Debug for Iter<'_, T> {
1042    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1043        self.iter.fmt(f)
1044    }
1045}
1046
1047/// A non-empty iterator over mutable values from an [`NEVec`].
1048#[derive(Debug)]
1049#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1050pub struct IterMut<'a, T: 'a> {
1051    inner: std::slice::IterMut<'a, T>,
1052}
1053
1054impl<T> NonEmptyIterator for IterMut<'_, T> {}
1055
1056impl<'a, T> IntoIterator for IterMut<'a, T> {
1057    type Item = &'a mut T;
1058
1059    type IntoIter = std::slice::IterMut<'a, T>;
1060
1061    fn into_iter(self) -> Self::IntoIter {
1062        self.inner
1063    }
1064}
1065
1066/// An owned non-empty iterator over values from an [`NEVec`].
1067#[derive(Clone)]
1068#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1069pub struct IntoIter<T> {
1070    inner: std::vec::IntoIter<T>,
1071}
1072
1073impl<T> NonEmptyIterator for IntoIter<T> {}
1074
1075impl<T> IntoIterator for IntoIter<T> {
1076    type Item = T;
1077
1078    type IntoIter = std::vec::IntoIter<T>;
1079
1080    fn into_iter(self) -> Self::IntoIter {
1081        self.inner
1082    }
1083}
1084
1085impl<T: Debug> Debug for IntoIter<T> {
1086    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1087        self.inner.fmt(f)
1088    }
1089}
1090
1091impl<T> IntoNonEmptyIterator for NEVec<T> {
1092    type IntoNEIter = IntoIter<T>;
1093
1094    fn into_nonempty_iter(self) -> Self::IntoNEIter {
1095        IntoIter {
1096            inner: self.inner.into_iter(),
1097        }
1098    }
1099}
1100
1101impl<'a, T> IntoNonEmptyIterator for &'a NEVec<T> {
1102    type IntoNEIter = Iter<'a, T>;
1103
1104    fn into_nonempty_iter(self) -> Self::IntoNEIter {
1105        self.nonempty_iter()
1106    }
1107}
1108
1109impl<T> IntoIterator for NEVec<T> {
1110    type Item = T;
1111    type IntoIter = std::vec::IntoIter<Self::Item>;
1112
1113    fn into_iter(self) -> Self::IntoIter {
1114        self.inner.into_iter()
1115    }
1116}
1117
1118impl<'a, T> IntoIterator for &'a NEVec<T> {
1119    type Item = &'a T;
1120    type IntoIter = std::slice::Iter<'a, T>;
1121
1122    fn into_iter(self) -> Self::IntoIter {
1123        self.iter()
1124    }
1125}
1126
1127impl<'a, T> IntoIterator for &'a mut NEVec<T> {
1128    type Item = &'a mut T;
1129    type IntoIter = std::slice::IterMut<'a, T>;
1130
1131    fn into_iter(self) -> Self::IntoIter {
1132        self.iter_mut()
1133    }
1134}
1135
1136impl<T> std::ops::Index<usize> for NEVec<T> {
1137    type Output = T;
1138
1139    /// ```
1140    /// use nonempty_collections::nev;
1141    ///
1142    /// let v = nev![1, 2, 3, 4, 5];
1143    ///
1144    /// assert_eq!(v[0], 1);
1145    /// assert_eq!(v[1], 2);
1146    /// assert_eq!(v[3], 4);
1147    /// ```
1148    fn index(&self, index: usize) -> &T {
1149        self.inner.index(index)
1150    }
1151}
1152
1153impl<T> std::ops::IndexMut<usize> for NEVec<T> {
1154    fn index_mut(&mut self, index: usize) -> &mut T {
1155        self.inner.index_mut(index)
1156    }
1157}
1158
1159impl<T: Debug> Debug for NEVec<T> {
1160    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1161        self.inner.fmt(f)
1162    }
1163}
1164
1165impl<T> TryFrom<Vec<T>> for NEVec<T> {
1166    type Error = crate::Error;
1167
1168    fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1169        NEVec::try_from_vec(vec).ok_or(crate::Error::Empty)
1170    }
1171}
1172
1173impl<T> Extend<T> for NEVec<T> {
1174    fn extend<I>(&mut self, iter: I)
1175    where
1176        I: IntoIterator<Item = T>,
1177    {
1178        self.inner.extend(iter);
1179    }
1180}
1181
1182#[cfg(test)]
1183mod tests {
1184    use crate::nev;
1185    use crate::NEVec;
1186
1187    #[derive(Debug, Clone, PartialEq)]
1188    struct Foo {
1189        user: String,
1190    }
1191
1192    #[test]
1193    fn macro_usage() {
1194        let a = Foo {
1195            user: "a".to_string(),
1196        };
1197        let b = Foo {
1198            user: "b".to_string(),
1199        };
1200
1201        let v = nev![a, b];
1202        assert_eq!("a", v.first().user);
1203    }
1204
1205    #[test]
1206    fn macro_semicolon() {
1207        let a = Foo {
1208            user: "a".to_string(),
1209        };
1210        let v = nev![a.clone(); 3];
1211
1212        let expected = NEVec { inner: vec![a; 3] };
1213        assert_eq!(v, expected);
1214    }
1215
1216    #[test]
1217    fn test_from_conversion() {
1218        let result = NEVec::from((1, vec![2, 3, 4, 5]));
1219        let expected = NEVec {
1220            inner: vec![1, 2, 3, 4, 5],
1221        };
1222        assert_eq!(result, expected);
1223    }
1224
1225    #[test]
1226    fn test_into_iter() {
1227        let nonempty = NEVec::from((0usize, vec![1, 2, 3]));
1228        for (i, n) in nonempty.into_iter().enumerate() {
1229            assert_eq!(i, n);
1230        }
1231    }
1232
1233    #[test]
1234    fn test_iter_syntax() {
1235        let nonempty = NEVec::from((0, vec![1, 2, 3]));
1236        for n in &nonempty {
1237            assert_eq!(*n, *n); // Prove that we're dealing with references.
1238        }
1239        for _ in nonempty {}
1240    }
1241
1242    #[cfg(feature = "serde")]
1243    mod serialize {
1244        use serde::Deserialize;
1245        use serde::Serialize;
1246
1247        use crate::NEVec;
1248
1249        #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1250        struct SimpleSerializable(i32);
1251
1252        #[test]
1253        fn test_simple_round_trip() -> Result<(), Box<dyn std::error::Error>> {
1254            // Given
1255            let mut v = NEVec::new(SimpleSerializable(42));
1256            v.push(SimpleSerializable(777));
1257            let expected_value = v.clone();
1258
1259            // When
1260            let res =
1261                serde_json::from_str::<'_, NEVec<SimpleSerializable>>(&serde_json::to_string(&v)?)?;
1262
1263            // Then
1264            assert_eq!(res, expected_value);
1265
1266            Ok(())
1267        }
1268    }
1269
1270    #[test]
1271    fn test_result_collect() {
1272        use crate::IntoNonEmptyIterator;
1273        use crate::NonEmptyIterator;
1274
1275        let nonempty = nev![2, 4, 8];
1276        let output = nonempty
1277            .into_nonempty_iter()
1278            .map(|n| {
1279                if n % 2 == 0 {
1280                    Ok(n)
1281                } else {
1282                    Err("odd number!")
1283                }
1284            })
1285            .collect::<Result<NEVec<u32>, &'static str>>();
1286
1287        assert_eq!(output, Ok(nev![2, 4, 8]));
1288
1289        let nonempty = nev![2, 1, 8];
1290        let output = nonempty
1291            .into_nonempty_iter()
1292            .map(|n| {
1293                if n % 2 == 0 {
1294                    Ok(n)
1295                } else {
1296                    Err("odd number!")
1297                }
1298            })
1299            .collect::<Result<NEVec<u32>, &'static str>>();
1300
1301        assert_eq!(output, Err("odd number!"));
1302    }
1303
1304    #[test]
1305    fn test_as_slice() {
1306        let nonempty = NEVec::from((0, vec![1, 2, 3]));
1307        assert_eq!(
1308            crate::NESlice::try_from_slice(&[0, 1, 2, 3]).unwrap(),
1309            nonempty.as_nonempty_slice(),
1310        );
1311    }
1312
1313    #[test]
1314    fn debug_impl() {
1315        let actual = format!("{:?}", nev![0, 1, 2, 3]);
1316        let expected = format!("{:?}", vec![0, 1, 2, 3]);
1317        assert_eq!(expected, actual);
1318    }
1319
1320    #[test]
1321    fn sorting() {
1322        let mut n = nev![1, 5, 4, 3, 2, 1];
1323        n.sort();
1324        assert_eq!(nev![1, 1, 2, 3, 4, 5], n);
1325
1326        let mut m = nev![1];
1327        m.sort();
1328        assert_eq!(nev![1], m);
1329    }
1330
1331    #[test]
1332    fn extend() {
1333        let mut n = nev![1, 2, 3];
1334        let v = vec![4, 5, 6];
1335        n.extend(v);
1336
1337        assert_eq!(n, nev![1, 2, 3, 4, 5, 6]);
1338    }
1339
1340    #[test]
1341    fn iter_mut() {
1342        let mut v = nev![0, 1, 2, 3];
1343
1344        v.iter_mut().for_each(|x| {
1345            *x += 1;
1346        });
1347
1348        assert_eq!(nev![1, 2, 3, 4], v);
1349
1350        for x in &mut v {
1351            *x -= 1;
1352        }
1353        assert_eq!(nev![0, 1, 2, 3], v);
1354    }
1355
1356    #[test]
1357    fn retain() {
1358        // retain all
1359        let v = nev![0, 1, 2, 3];
1360        let result = v.retain(|_| true);
1361        assert_eq!(
1362            Ok(nev![0, 1, 2, 3]),
1363            result,
1364            "retaining all values should not change anything"
1365        );
1366        // retain none
1367        let v = nev![0, 1, 2, 3];
1368        let result = v.retain(|_| false);
1369        assert_eq!(
1370            Err(vec![]),
1371            result,
1372            "removing all values should return a regular vec"
1373        );
1374        // retain one
1375        let v = nev![3, 7];
1376        let result = v.retain_mut(|x| *x == 3);
1377        assert_eq!(Ok(nev![3]), result, "only 3 should remain");
1378    }
1379
1380    #[test]
1381    fn retain_mut() {
1382        // retain all
1383        let v = nev![0, 1, 2, 3];
1384        let result = v.retain_mut(|x| {
1385            *x += 1;
1386            true
1387        });
1388        assert_eq!(
1389            Ok(nev![1, 2, 3, 4]),
1390            result,
1391            "each value must be incremented by 1"
1392        );
1393        let v = nev![0, 1, 2, 3];
1394        // retain none
1395        let result = v.retain_mut(|x| {
1396            *x += 1;
1397            false
1398        });
1399        assert_eq!(
1400            Err(vec![]),
1401            result,
1402            "removing all values should return a regular vec"
1403        );
1404        // retain one
1405        let v = nev![3, 7];
1406        let result = v.retain_mut(|x| {
1407            if *x == 3 {
1408                *x += 1;
1409                true
1410            } else {
1411                false
1412            }
1413        });
1414        assert_eq!(Ok(nev![4]), result, "only 3+1 = 4 should remain");
1415    }
1416}