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