Skip to main content

nonempty_collections/
vector.rs

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