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