nonempty_collections/
vector.rs

1//! Non-empty Vectors.
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;
13
14#[cfg(feature = "serde")]
15use serde::Deserialize;
16#[cfg(feature = "serde")]
17use serde::Serialize;
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        // SAFETY: `self.inner` is non-empty by the invariant of `NEVec`
812        unsafe { crate::NESlice::from_slice_unchecked(self.inner.as_slice()) }
813    }
814
815    /// Removes all but the first of consecutive elements in the vector that
816    /// resolve to the same key.
817    ///
818    /// If the vector is sorted, this removes all duplicates.
819    ///
820    /// # Examples
821    ///
822    /// ```
823    /// use nonempty_collections::nev;
824    /// let mut v = nev![10, 20, 21, 30, 20];
825    ///
826    /// v.dedup_by_key(|i| *i / 10);
827    ///
828    /// assert_eq!(nev![10, 20, 30, 20], v);
829    /// ```
830    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
831    where
832        F: FnMut(&mut T) -> K,
833        K: PartialEq,
834    {
835        self.dedup_by(|a, b| key(a) == key(b));
836    }
837
838    /// Removes all but the first of consecutive elements in the vector
839    /// satisfying a given equality relation.
840    ///
841    /// The `same_bucket` function is passed references to two elements from the
842    /// vector and must determine if the elements compare equal. The
843    /// elements are passed in opposite order from their order in the slice,
844    /// so if `same_bucket(a, b)` returns `true`, `a` is removed.
845    ///
846    /// If the vector is sorted, this removes all duplicates.
847    ///
848    /// # Examples
849    ///
850    /// ```
851    /// use nonempty_collections::nev;
852    /// let mut v = nev!["foo", "Foo", "foo", "bar", "Bar", "baz", "bar"];
853    ///
854    /// v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
855    ///
856    /// assert_eq!(nev!["foo", "bar", "baz", "bar"], v);
857    /// ```
858    pub fn dedup_by<F>(&mut self, same_bucket: F)
859    where
860        F: FnMut(&mut T, &mut T) -> bool,
861    {
862        self.inner.dedup_by(same_bucket);
863    }
864
865    /// Returns a non-empty iterator over `chunk_size` elements of the `NEVec`
866    /// at a time, starting at the beginning of the `NEVec`.
867    ///
868    /// ```
869    /// use std::num::NonZeroUsize;
870    ///
871    /// use nonempty_collections::*;
872    ///
873    /// let v = nev![1, 2, 3, 4, 5, 6];
874    /// let n = NonZeroUsize::new(2).unwrap();
875    /// let r = v.nonempty_chunks(n).collect::<NEVec<_>>();
876    ///
877    /// let a = nev![1, 2];
878    /// let b = nev![3, 4];
879    /// let c = nev![5, 6];
880    ///
881    /// assert_eq!(
882    ///     r,
883    ///     nev![
884    ///         a.as_nonempty_slice(),
885    ///         b.as_nonempty_slice(),
886    ///         c.as_nonempty_slice()
887    ///     ]
888    /// );
889    /// ```
890    pub fn nonempty_chunks(&self, chunk_size: NonZeroUsize) -> NEChunks<'_, T> {
891        NEChunks {
892            inner: self.inner.chunks(chunk_size.get()),
893        }
894    }
895
896    /// Returns the index of the partition point according to the given
897    /// predicate (the index of the first element of the second partition).
898    ///
899    /// The vector is assumed to be partitioned according to the given
900    /// predicate. This means that all elements for which the predicate
901    /// returns true are at the start of the vector and all elements for
902    /// which the predicate returns false are at the end. For example, `[7,
903    /// 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
904    /// (all odd numbers are at the start, all even at the end).
905    ///
906    /// If this vector is not partitioned, the returned result is unspecified
907    /// and meaningless, as this method performs a kind of binary search.
908    ///
909    /// See also [`NEVec::binary_search`], [`NEVec::binary_search_by`], and
910    /// [`NEVec::binary_search_by_key`].
911    ///
912    /// # Examples
913    ///
914    /// ```
915    /// # use nonempty_collections::*;
916    /// #
917    /// let v = nev![1, 2, 3, 3, 5, 6, 7];
918    /// let i = v.partition_point(|&x| x < 5);
919    ///
920    /// assert_eq!(i, 4);
921    /// ```
922    ///
923    /// If all elements of the non-empty vector match the predicate, then the
924    /// length of the vector will be returned:
925    ///
926    /// ```
927    /// # use nonempty_collections::*;
928    /// #
929    /// let a = nev![2, 4, 8];
930    /// assert_eq!(a.partition_point(|&x| x < 100), a.len().get());
931    /// ```
932    ///
933    /// If you want to insert an item to a sorted vector, while maintaining
934    /// sort order:
935    ///
936    /// ```
937    /// # use nonempty_collections::*;
938    /// #
939    /// let mut s = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
940    /// let num = 42;
941    /// let idx = s.partition_point(|&x| x < num);
942    /// s.insert(idx, num);
943    /// assert_eq!(s, nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
944    /// ```
945    #[must_use]
946    pub fn partition_point<P>(&self, mut pred: P) -> usize
947    where
948        P: FnMut(&T) -> bool,
949    {
950        self.binary_search_by(|x| {
951            if pred(x) {
952                Ordering::Less
953            } else {
954                Ordering::Greater
955            }
956        })
957        .unwrap_or_else(|i| i)
958    }
959}
960
961impl<T: PartialEq> NEVec<T> {
962    /// Removes consecutive repeated elements in the vector according to the
963    /// [`PartialEq`] trait implementation.
964    ///
965    /// If the vector is sorted, this removes all duplicates.
966    ///
967    /// # Examples
968    ///
969    /// ```
970    /// use nonempty_collections::nev;
971    /// let mut v = nev![1, 1, 1, 2, 3, 2, 2, 1];
972    /// v.dedup();
973    /// assert_eq!(nev![1, 2, 3, 2, 1], v);
974    /// ```
975    pub fn dedup(&mut self) {
976        self.dedup_by(|a, b| a == b);
977    }
978}
979
980impl<T> From<NEVec<T>> for Vec<T> {
981    /// Turns a non-empty list into a `Vec`.
982    fn from(nonempty: NEVec<T>) -> Vec<T> {
983        nonempty.inner
984    }
985}
986
987impl<T> From<(T, Vec<T>)> for NEVec<T> {
988    /// Turns a pair of an element and a `Vec` into
989    /// a `NEVec`.
990    fn from((head, tail): (T, Vec<T>)) -> Self {
991        let mut vec = vec![head];
992        vec.extend(tail);
993        NEVec { inner: vec }
994    }
995}
996
997impl<T> AsRef<Vec<T>> for NEVec<T> {
998    fn as_ref(&self) -> &Vec<T> {
999        self.inner.as_ref()
1000    }
1001}
1002
1003impl<T> AsMut<Vec<T>> for NEVec<T> {
1004    fn as_mut(&mut self) -> &mut Vec<T> {
1005        self.inner.as_mut()
1006    }
1007}
1008
1009/// ```
1010/// use nonempty_collections::*;
1011///
1012/// let v0 = nev![1, 2, 3];
1013/// let v1: NEVec<_> = v0.nonempty_iter().cloned().collect();
1014/// assert_eq!(v0, v1);
1015/// ```
1016impl<T> FromNonEmptyIterator<T> for NEVec<T> {
1017    fn from_nonempty_iter<I>(iter: I) -> Self
1018    where
1019        I: IntoNonEmptyIterator<Item = T>,
1020    {
1021        NEVec {
1022            inner: iter.into_nonempty_iter().into_iter().collect(),
1023        }
1024    }
1025}
1026
1027/// A non-empty iterator over the values of an [`NEVec`].
1028#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1029pub struct Iter<'a, T: 'a> {
1030    iter: std::slice::Iter<'a, T>,
1031}
1032
1033impl<T> NonEmptyIterator for Iter<'_, T> {}
1034
1035impl<'a, T> IntoIterator for Iter<'a, T> {
1036    type Item = &'a T;
1037
1038    type IntoIter = std::slice::Iter<'a, T>;
1039
1040    fn into_iter(self) -> Self::IntoIter {
1041        self.iter
1042    }
1043}
1044
1045// FIXME(#26925) Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
1046impl<T> Clone for Iter<'_, T> {
1047    fn clone(&self) -> Self {
1048        Iter {
1049            iter: self.iter.clone(),
1050        }
1051    }
1052}
1053
1054impl<T: Debug> Debug for Iter<'_, T> {
1055    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1056        self.iter.fmt(f)
1057    }
1058}
1059
1060/// A non-empty iterator over mutable values from an [`NEVec`].
1061#[derive(Debug)]
1062#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1063pub struct IterMut<'a, T: 'a> {
1064    inner: std::slice::IterMut<'a, T>,
1065}
1066
1067impl<T> NonEmptyIterator for IterMut<'_, T> {}
1068
1069impl<'a, T> IntoIterator for IterMut<'a, T> {
1070    type Item = &'a mut T;
1071
1072    type IntoIter = std::slice::IterMut<'a, T>;
1073
1074    fn into_iter(self) -> Self::IntoIter {
1075        self.inner
1076    }
1077}
1078
1079/// An owned non-empty iterator over values from an [`NEVec`].
1080#[derive(Clone)]
1081#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1082pub struct IntoIter<T> {
1083    inner: std::vec::IntoIter<T>,
1084}
1085
1086impl<T> NonEmptyIterator for IntoIter<T> {}
1087
1088impl<T> IntoIterator for IntoIter<T> {
1089    type Item = T;
1090
1091    type IntoIter = std::vec::IntoIter<T>;
1092
1093    fn into_iter(self) -> Self::IntoIter {
1094        self.inner
1095    }
1096}
1097
1098impl<T: Debug> Debug for IntoIter<T> {
1099    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1100        self.inner.fmt(f)
1101    }
1102}
1103
1104impl<T> IntoNonEmptyIterator for NEVec<T> {
1105    type IntoNEIter = IntoIter<T>;
1106
1107    fn into_nonempty_iter(self) -> Self::IntoNEIter {
1108        IntoIter {
1109            inner: self.inner.into_iter(),
1110        }
1111    }
1112}
1113
1114impl<'a, T> IntoNonEmptyIterator for &'a NEVec<T> {
1115    type IntoNEIter = Iter<'a, T>;
1116
1117    fn into_nonempty_iter(self) -> Self::IntoNEIter {
1118        self.nonempty_iter()
1119    }
1120}
1121
1122impl<T> IntoIterator for NEVec<T> {
1123    type Item = T;
1124    type IntoIter = std::vec::IntoIter<Self::Item>;
1125
1126    fn into_iter(self) -> Self::IntoIter {
1127        self.inner.into_iter()
1128    }
1129}
1130
1131impl<'a, T> IntoIterator for &'a NEVec<T> {
1132    type Item = &'a T;
1133    type IntoIter = std::slice::Iter<'a, T>;
1134
1135    fn into_iter(self) -> Self::IntoIter {
1136        self.iter()
1137    }
1138}
1139
1140impl<'a, T> IntoIterator for &'a mut NEVec<T> {
1141    type Item = &'a mut T;
1142    type IntoIter = std::slice::IterMut<'a, T>;
1143
1144    fn into_iter(self) -> Self::IntoIter {
1145        self.iter_mut()
1146    }
1147}
1148
1149impl<T> std::ops::Index<usize> for NEVec<T> {
1150    type Output = T;
1151
1152    /// ```
1153    /// use nonempty_collections::nev;
1154    ///
1155    /// let v = nev![1, 2, 3, 4, 5];
1156    ///
1157    /// assert_eq!(v[0], 1);
1158    /// assert_eq!(v[1], 2);
1159    /// assert_eq!(v[3], 4);
1160    /// ```
1161    fn index(&self, index: usize) -> &T {
1162        self.inner.index(index)
1163    }
1164}
1165
1166impl<T> std::ops::IndexMut<usize> for NEVec<T> {
1167    fn index_mut(&mut self, index: usize) -> &mut T {
1168        self.inner.index_mut(index)
1169    }
1170}
1171
1172impl<T: Debug> Debug for NEVec<T> {
1173    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1174        self.inner.fmt(f)
1175    }
1176}
1177
1178impl<T> TryFrom<Vec<T>> for NEVec<T> {
1179    type Error = crate::Error;
1180
1181    fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1182        NEVec::try_from_vec(vec).ok_or(crate::Error::Empty)
1183    }
1184}
1185
1186impl<T> Extend<T> for NEVec<T> {
1187    fn extend<I>(&mut self, iter: I)
1188    where
1189        I: IntoIterator<Item = T>,
1190    {
1191        self.inner.extend(iter);
1192    }
1193}
1194
1195impl<T> Singleton for NEVec<T> {
1196    type Item = T;
1197
1198    /// ```
1199    /// use nonempty_collections::{NEVec, Singleton, nev};
1200    ///
1201    /// let v = NEVec::singleton(1);
1202    /// assert_eq!(nev![1], v);
1203    /// ```
1204    fn singleton(item: T) -> NEVec<T> {
1205        NEVec::new(item)
1206    }
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211    use crate::nev;
1212    use crate::NEVec;
1213
1214    #[derive(Debug, Clone, PartialEq)]
1215    struct Foo {
1216        user: String,
1217    }
1218
1219    #[test]
1220    fn macro_usage() {
1221        let a = Foo {
1222            user: "a".to_string(),
1223        };
1224        let b = Foo {
1225            user: "b".to_string(),
1226        };
1227
1228        let v = nev![a, b];
1229        assert_eq!("a", v.first().user);
1230    }
1231
1232    #[test]
1233    fn macro_semicolon() {
1234        let a = Foo {
1235            user: "a".to_string(),
1236        };
1237        let v = nev![a.clone(); 3];
1238
1239        let expected = NEVec { inner: vec![a; 3] };
1240        assert_eq!(v, expected);
1241    }
1242
1243    #[test]
1244    fn test_from_conversion() {
1245        let result = NEVec::from((1, vec![2, 3, 4, 5]));
1246        let expected = NEVec {
1247            inner: vec![1, 2, 3, 4, 5],
1248        };
1249        assert_eq!(result, expected);
1250    }
1251
1252    #[test]
1253    fn test_into_iter() {
1254        let nonempty = NEVec::from((0usize, vec![1, 2, 3]));
1255        for (i, n) in nonempty.into_iter().enumerate() {
1256            assert_eq!(i, n);
1257        }
1258    }
1259
1260    #[test]
1261    fn test_iter_syntax() {
1262        let nonempty = NEVec::from((0, vec![1, 2, 3]));
1263        for n in &nonempty {
1264            assert_eq!(*n, *n); // Prove that we're dealing with references.
1265        }
1266        for _ in nonempty {}
1267    }
1268
1269    #[cfg(feature = "serde")]
1270    mod serialize {
1271        use serde::Deserialize;
1272        use serde::Serialize;
1273
1274        use crate::NEVec;
1275
1276        #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1277        struct SimpleSerializable(i32);
1278
1279        #[test]
1280        fn test_simple_round_trip() -> Result<(), Box<dyn std::error::Error>> {
1281            // Given
1282            let mut v = NEVec::new(SimpleSerializable(42));
1283            v.push(SimpleSerializable(777));
1284            let expected_value = v.clone();
1285
1286            // When
1287            let res =
1288                serde_json::from_str::<'_, NEVec<SimpleSerializable>>(&serde_json::to_string(&v)?)?;
1289
1290            // Then
1291            assert_eq!(res, expected_value);
1292
1293            Ok(())
1294        }
1295    }
1296
1297    #[test]
1298    fn test_result_collect() {
1299        use crate::IntoNonEmptyIterator;
1300        use crate::NonEmptyIterator;
1301
1302        let nonempty = nev![2, 4, 8];
1303        let output = nonempty
1304            .into_nonempty_iter()
1305            .map(|n| {
1306                if n % 2 == 0 {
1307                    Ok(n)
1308                } else {
1309                    Err("odd number!")
1310                }
1311            })
1312            .collect::<Result<NEVec<u32>, &'static str>>();
1313
1314        assert_eq!(output, Ok(nev![2, 4, 8]));
1315
1316        let nonempty = nev![2, 1, 8];
1317        let output = nonempty
1318            .into_nonempty_iter()
1319            .map(|n| {
1320                if n % 2 == 0 {
1321                    Ok(n)
1322                } else {
1323                    Err("odd number!")
1324                }
1325            })
1326            .collect::<Result<NEVec<u32>, &'static str>>();
1327
1328        assert_eq!(output, Err("odd number!"));
1329    }
1330
1331    #[test]
1332    fn test_as_slice() {
1333        let nonempty = NEVec::from((0, vec![1, 2, 3]));
1334        assert_eq!(
1335            crate::NESlice::try_from_slice(&[0, 1, 2, 3]).unwrap(),
1336            nonempty.as_nonempty_slice(),
1337        );
1338    }
1339
1340    #[test]
1341    fn debug_impl() {
1342        let actual = format!("{:?}", nev![0, 1, 2, 3]);
1343        let expected = format!("{:?}", vec![0, 1, 2, 3]);
1344        assert_eq!(expected, actual);
1345    }
1346
1347    #[test]
1348    fn sorting() {
1349        let mut n = nev![1, 5, 4, 3, 2, 1];
1350        n.sort();
1351        assert_eq!(nev![1, 1, 2, 3, 4, 5], n);
1352
1353        let mut m = nev![1];
1354        m.sort();
1355        assert_eq!(nev![1], m);
1356    }
1357
1358    #[test]
1359    fn extend() {
1360        let mut n = nev![1, 2, 3];
1361        let v = vec![4, 5, 6];
1362        n.extend(v);
1363
1364        assert_eq!(n, nev![1, 2, 3, 4, 5, 6]);
1365    }
1366
1367    #[test]
1368    fn iter_mut() {
1369        let mut v = nev![0, 1, 2, 3];
1370
1371        v.iter_mut().for_each(|x| {
1372            *x += 1;
1373        });
1374
1375        assert_eq!(nev![1, 2, 3, 4], v);
1376
1377        for x in &mut v {
1378            *x -= 1;
1379        }
1380        assert_eq!(nev![0, 1, 2, 3], v);
1381    }
1382
1383    #[test]
1384    fn retain() {
1385        // retain all
1386        let v = nev![0, 1, 2, 3];
1387        let result = v.retain(|_| true);
1388        assert_eq!(
1389            Ok(nev![0, 1, 2, 3]),
1390            result,
1391            "retaining all values should not change anything"
1392        );
1393        // retain none
1394        let v = nev![0, 1, 2, 3];
1395        let result = v.retain(|_| false);
1396        assert_eq!(
1397            Err(vec![]),
1398            result,
1399            "removing all values should return a regular vec"
1400        );
1401        // retain one
1402        let v = nev![3, 7];
1403        let result = v.retain_mut(|x| *x == 3);
1404        assert_eq!(Ok(nev![3]), result, "only 3 should remain");
1405    }
1406
1407    #[test]
1408    fn retain_mut() {
1409        // retain all
1410        let v = nev![0, 1, 2, 3];
1411        let result = v.retain_mut(|x| {
1412            *x += 1;
1413            true
1414        });
1415        assert_eq!(
1416            Ok(nev![1, 2, 3, 4]),
1417            result,
1418            "each value must be incremented by 1"
1419        );
1420        let v = nev![0, 1, 2, 3];
1421        // retain none
1422        let result = v.retain_mut(|x| {
1423            *x += 1;
1424            false
1425        });
1426        assert_eq!(
1427            Err(vec![]),
1428            result,
1429            "removing all values should return a regular vec"
1430        );
1431        // retain one
1432        let v = nev![3, 7];
1433        let result = v.retain_mut(|x| {
1434            if *x == 3 {
1435                *x += 1;
1436                true
1437            } else {
1438                false
1439            }
1440        });
1441        assert_eq!(Ok(nev![4]), result, "only 3+1 = 4 should remain");
1442    }
1443}