nonempty_collections/
iter.rs

1//! Non-empty iterators.
2
3use std::cell::RefCell;
4use std::cmp::Ordering;
5use std::collections::HashMap;
6use std::collections::HashSet;
7use std::hash::BuildHasher;
8use std::hash::Hash;
9use std::iter::Peekable;
10use std::iter::Product;
11use std::iter::Sum;
12use std::num::NonZeroUsize;
13use std::rc::Rc;
14use std::result::Result;
15
16use crate::nev;
17use crate::NEVec;
18
19// Iterator structs which _always_ have something if the source iterator is
20// non-empty:
21//
22// - [x] Chain (if one, the other, or both are nonempty)
23// - [x] Cloned
24// - [x] Copied
25// - [ ] Cycle
26// - [x] Enumerate
27// - [x] Map
28// - [x] Once
29// - [ ] Scan
30// - [x] Take
31// - [x] Zip (if both are nonempty)
32
33/// Creates an iterator that yields an element exactly once.
34///
35/// See also [`std::iter::once`].
36pub fn once<T>(value: T) -> Once<T> {
37    Once::new(value)
38}
39
40/// An [`Iterator`] that is guaranteed to have at least one item.
41///
42/// By implementing `NonEmptyIterator` for a type the implementor is responsible
43/// for ensuring that non-emptiness holds. Violating this invariant may lead to
44/// panics and/or undefined behavior.
45pub trait NonEmptyIterator: IntoIterator {
46    /// Advances this non-empty iterator, consuming its ownership. Yields the
47    /// first item and a possibly empty iterator containing the rest of the
48    /// elements.
49    #[must_use]
50    fn next(self) -> (Self::Item, Self::IntoIter)
51    where
52        Self: Sized,
53    {
54        let mut iter = self.into_iter();
55        (iter.next().unwrap(), iter)
56    }
57
58    /// Tests if every element of the iterator matches a predicate.
59    ///
60    /// Because this function always advances the iterator at least once, the
61    /// non-empty guarantee is invalidated. Therefore, this function consumes
62    /// this `NonEmptyIterator`.
63    ///
64    /// See also [`Iterator::all`].
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// use nonempty_collections::*;
70    ///
71    /// let n = nev![2, 2, 2];
72    /// assert!(n.nonempty_iter().all(|n| n % 2 == 0));
73    /// assert!(n.iter().all(|n| n % 2 == 0));
74    /// ```
75    #[must_use]
76    fn all<F>(self, f: F) -> bool
77    where
78        Self: Sized,
79        F: FnMut(Self::Item) -> bool,
80    {
81        self.into_iter().all(f)
82    }
83
84    /// Tests if any element of the iterator matches a predicate.
85    ///
86    /// Because this function always advances the iterator at least once, the
87    /// non-empty guarantee is invalidated. Therefore, this function consumes
88    /// this `NonEmptyIterator`.
89    ///
90    /// See also [`Iterator::any`].
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// use nonempty_collections::*;
96    ///
97    /// let n = nev![1, 1, 1, 2, 1, 1];
98    /// assert!(n.nonempty_iter().any(|n| n % 2 == 0));
99    /// assert!(!n.nonempty_iter().any(|n| n % 3 == 0));
100    /// ```
101    #[must_use]
102    fn any<F>(self, f: F) -> bool
103    where
104        Self: Sized,
105        F: FnMut(Self::Item) -> bool,
106    {
107        self.into_iter().any(f)
108    }
109
110    /// Takes two iterators and creates a new non-empty iterator over both in
111    /// sequence.
112    ///
113    /// Note that the second iterator need not be empty.
114    ///
115    /// See also [`Iterator::chain`].
116    ///
117    /// ```
118    /// use nonempty_collections::*;
119    ///
120    /// let v = nev![1, 2, 3];
121    /// let s = nes![4, 5, 6];
122    /// let mut r: Vec<_> = v.into_nonempty_iter().chain(s).collect();
123    /// r.sort();
124    ///
125    /// assert_eq!(vec![1, 2, 3, 4, 5, 6], r);
126    /// ```
127    fn chain<U>(self, other: U) -> Chain<Self::IntoIter, U::IntoIter>
128    where
129        Self: Sized,
130        U: IntoIterator<Item = Self::Item>,
131    {
132        Chain {
133            inner: self.into_iter().chain(other),
134        }
135    }
136
137    /// Creates a non-empty iterator which clones all of its elements.
138    ///
139    /// This is useful when you have an iterator over `&T`, but you need an
140    /// iterator over `T`.
141    ///
142    /// See also [`Iterator::cloned`].
143    ///
144    /// ```
145    /// use nonempty_collections::NEVec;
146    /// use nonempty_collections::*;
147    ///
148    /// #[derive(Debug, Clone, PartialEq, Eq)]
149    /// enum Foo {
150    ///     A,
151    ///     B,
152    ///     C,
153    /// }
154    ///
155    /// let v0 = nev![Foo::A, Foo::B, Foo::C];
156    /// let v1: NEVec<_> = v0.nonempty_iter().collect();
157    /// let v2: NEVec<_> = v0.nonempty_iter().cloned().collect();
158    ///
159    /// assert_eq!(nev![&Foo::A, &Foo::B, &Foo::C], v1);
160    /// assert_eq!(nev![Foo::A, Foo::B, Foo::C], v2);
161    /// ```
162    fn cloned<'a, T>(self) -> Cloned<Self>
163    where
164        Self: Sized + NonEmptyIterator<Item = &'a T>,
165        T: Clone + 'a,
166    {
167        Cloned { iter: self }
168    }
169
170    /// Transforms an iterator into a collection, or some other concrete value.
171    ///
172    /// See also [`Iterator::collect`].
173    ///
174    /// ```
175    /// use nonempty_collections::*;
176    ///
177    /// let n0 = nev![1, 2, 3, 4];
178    /// let n1 = n0.into_nonempty_iter().collect();
179    /// assert_eq!(nev![1, 2, 3, 4], n1);
180    /// ```
181    #[must_use]
182    fn collect<B>(self) -> B
183    where
184        Self: Sized,
185        B: FromNonEmptyIterator<Self::Item>,
186    {
187        FromNonEmptyIterator::from_nonempty_iter(self)
188    }
189
190    /// Creates a non-empty iterator which copies all of its elements.
191    ///
192    /// See also [`Iterator::copied`].
193    ///
194    /// ```
195    /// use nonempty_collections::*;
196    ///
197    /// let n0 = nev![1, 2, 3, 4];
198    /// let n1 = n0.nonempty_iter().copied().collect();
199    /// assert_eq!(n0, n1);
200    /// ```
201    fn copied<'a, T>(self) -> Copied<Self::IntoIter>
202    where
203        Self: Sized + NonEmptyIterator<Item = &'a T>,
204        T: Copy + 'a,
205    {
206        Copied {
207            iter: self.into_iter().copied(),
208        }
209    }
210
211    /// Consumes the non-empty iterator, counting the number of iterations and
212    /// returning it.
213    ///
214    /// See also [`Iterator::count`].
215    ///
216    /// ```
217    /// use nonempty_collections::*;
218    ///
219    /// let n = nev![1];
220    /// assert_eq!(1, n.nonempty_iter().count().get());
221    ///
222    /// let n = nev![1, 2, 3, 4, 5, 6];
223    /// assert_eq!(6, n.nonempty_iter().count().get());
224    /// ````
225    #[must_use]
226    fn count(self) -> NonZeroUsize
227    where
228        Self: Sized,
229    {
230        unsafe { NonZeroUsize::new_unchecked(self.into_iter().count()) }
231    }
232
233    /// Creates a non-empty iterator which gives the current iteration count as
234    /// well as the next value.
235    ///
236    /// See also [`Iterator::enumerate`].
237    ///
238    /// ```
239    /// use nonempty_collections::*;
240    ///
241    /// let s = nes!["Doriath", "Gondolin", "Nargothrond"];
242    /// let total: usize = s.nonempty_iter().enumerate().map(|(c, _)| c).sum();
243    /// assert_eq!(3, total);
244    /// ```
245    fn enumerate(self) -> Enumerate<Self>
246    where
247        Self: Sized,
248    {
249        Enumerate { iter: self }
250    }
251
252    /// Creates an iterator which uses a closure to determine if an element
253    /// should be yielded.
254    ///
255    /// **Note:** The iterator returned by this method is **not** a
256    /// `NonEmptyIterator`, since there is never a guarantee that any element
257    /// will pass the predicate.
258    ///
259    /// See also [`Iterator::filter`].
260    ///
261    /// ```
262    /// use nonempty_collections::*;
263    ///
264    /// let n = nev![1, 2, 3, 4, 5, 6];
265    /// let v: Vec<_> = n
266    ///     .nonempty_iter()
267    ///     .map(|x| x * 2)
268    ///     .filter(|&x| x % 3 == 0)
269    ///     .collect();
270    /// assert_eq!(vec![6, 12], v);
271    /// ```
272    fn filter<P>(self, predicate: P) -> std::iter::Filter<<Self as IntoIterator>::IntoIter, P>
273    where
274        Self: Sized,
275        P: FnMut(&<Self as IntoIterator>::Item) -> bool,
276    {
277        self.into_iter().filter(predicate)
278    }
279
280    /// Creates an iterator that both filters and maps.
281    ///
282    /// **Note:** The iterator returned by this method is **not** a
283    /// `NonEmptyIterator`, since there is never a guarantee that any element
284    /// will yield `Some` from the given function.
285    ///
286    /// See also [`Iterator::filter_map`].
287    ///
288    /// ```
289    /// use nonempty_collections::*;
290    ///
291    /// let v = nev!["Frodo", "Sam", "", "Peregrin", "Meriadoc"];
292    /// let firsts: Vec<char> = v
293    ///     .into_nonempty_iter()
294    ///     .filter_map(|s| s.chars().next())
295    ///     .collect();
296    /// assert_eq!(vec!['F', 'S', 'P', 'M'], firsts);
297    /// ```
298    fn filter_map<B, F>(self, f: F) -> std::iter::FilterMap<<Self as IntoIterator>::IntoIter, F>
299    where
300        Self: Sized,
301        F: FnMut(<Self as IntoIterator>::Item) -> Option<B>,
302    {
303        self.into_iter().filter_map(f)
304    }
305
306    /// Searches for an element of an iterator that satisfies a predicate.
307    ///
308    /// Because this function always advances the iterator at least once, the
309    /// non-empty guarantee is invalidated. Therefore, this function consumes
310    /// this `NonEmptyIterator`.
311    ///
312    /// See also [`Iterator::find`].
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use nonempty_collections::*;
318    ///
319    /// let n = nev![1, 3, 5, 7, 9, 10];
320    /// assert_eq!(Some(&10), n.iter().find(|n| *n % 2 == 0));
321    /// assert_eq!(None, n.iter().find(|n| **n > 10));
322    /// ```
323    #[must_use]
324    fn find<P>(self, predicate: P) -> Option<Self::Item>
325    where
326        Self: Sized,
327        P: FnMut(&Self::Item) -> bool,
328    {
329        self.into_iter().find(predicate)
330    }
331
332    /// Creates an iterator that works like `map`, but flattens nested,
333    /// non-empty structure.
334    ///
335    /// See also [`Iterator::flat_map`].
336    ///
337    /// ```
338    /// use nonempty_collections::*;
339    ///
340    /// let v = nev![1, 2, 3];
341    /// let r = v.into_nonempty_iter().flat_map(|n| nev![n]).collect();
342    /// assert_eq!(nev![1, 2, 3], r);
343    /// ```
344    #[inline]
345    fn flat_map<U, F>(self, f: F) -> FlatMap<Self::IntoIter, U, F>
346    where
347        Self: Sized,
348        F: FnMut(Self::Item) -> U,
349        U: IntoNonEmptyIterator,
350    {
351        FlatMap {
352            inner: self.into_iter().flat_map(f),
353        }
354    }
355
356    // fn flatten<F, V>(self) -> FlatMap<Self, V, F>
357    // where
358    //     Self: Sized,
359    //     Self::Item: IntoNonEmptyIterator<IntoIter = V, Item = V::Item>,
360    //     V: NonEmptyIterator,
361    // {
362    //     self.flat_map(|ne| ne)
363    // }
364
365    /// Folds every element into an accumulator by applying an operation,
366    /// returning the final result.
367    ///
368    /// See also [`Iterator::fold`].
369    ///
370    /// ```
371    /// use nonempty_collections::*;
372    ///
373    /// let n = nev![1, 2, 3, 4];
374    /// let r = n.into_nonempty_iter().fold(0, |acc, x| acc + x);
375    /// assert_eq!(10, r);
376    /// ```
377    #[must_use]
378    fn fold<B, F>(self, init: B, f: F) -> B
379    where
380        Self: Sized,
381        F: FnMut(B, Self::Item) -> B,
382    {
383        self.into_iter().fold(init, f)
384    }
385
386    /// Group the non-empty input stream into concrete, non-empty subsections
387    /// via a given function. The cutoff criterion is whether the return value
388    /// of `f` changes between two consecutive elements.
389    ///
390    /// ```
391    /// use nonempty_collections::*;
392    ///
393    /// let n = nev![1, 1, 2, 3, 3];
394    /// let r: NEVec<_> = n.into_nonempty_iter().group_by(|n| *n).collect();
395    /// assert_eq!(r, nev![nev![1, 1], nev![2], nev![3, 3]]);
396    ///
397    /// let n = nev![2, 4, 6, 7, 9, 1, 2, 4, 6, 3];
398    /// let r: NEVec<_> = n.into_nonempty_iter().group_by(|n| n % 2 == 0).collect();
399    /// assert_eq!(
400    ///     r,
401    ///     nev![nev![2, 4, 6], nev![7, 9, 1], nev![2, 4, 6], nev![3]]
402    /// );
403    /// ```
404    fn group_by<K, F>(self, f: F) -> NEGroupBy<Self, F>
405    where
406        Self: Sized,
407        F: FnMut(&Self::Item) -> K,
408        K: PartialEq,
409    {
410        NEGroupBy { iter: self, f }
411    }
412
413    /// Takes a closure and creates a non-empty iterator which calls that
414    /// closure on each element.
415    ///
416    /// If `self` is a `NonEmptyIterator`, then so is [`Map`].
417    ///
418    /// See also [`Iterator::map`].
419    ///
420    /// ```
421    /// use nonempty_collections::NEVec;
422    /// use nonempty_collections::*;
423    ///
424    /// let s = nes![1, 2, 3];
425    /// let mut v: NEVec<_> = s.nonempty_iter().map(|n| n * 2).collect();
426    /// v.sort();
427    /// assert_eq!(nev![2, 4, 6], v);
428    /// ```
429    #[inline]
430    fn map<U, F>(self, f: F) -> Map<Self, F>
431    where
432        Self: Sized,
433        F: FnMut(Self::Item) -> U,
434    {
435        Map {
436            iter: self.into_iter().map(f),
437        }
438    }
439
440    /// Returns the maximum element of a non-empty iterator.
441    ///
442    /// Unlike [`Iterator::max`], this always yields a value.
443    ///
444    /// ```
445    /// use nonempty_collections::*;
446    ///
447    /// let v = nev![1, 1000, 2, 3];
448    /// assert_eq!(1000, v.into_nonempty_iter().max());
449    /// ```
450    #[must_use]
451    fn max(self) -> Self::Item
452    where
453        Self: Sized,
454        Self::Item: Ord,
455    {
456        self.max_by(Ord::cmp)
457    }
458
459    /// Returns the element that gives the maximum value with respect to the
460    /// given comparison function.
461    ///
462    /// Unlike [`Iterator::max_by`], this always yields a value.
463    #[must_use]
464    fn max_by<F>(self, compare: F) -> Self::Item
465    where
466        Self: Sized,
467        F: Fn(&Self::Item, &Self::Item) -> Ordering,
468    {
469        let (first, iter) = self.next();
470
471        iter.into_iter()
472            .fold(first, |acc, item| match compare(&acc, &item) {
473                Ordering::Less => item,
474                _ => acc,
475            })
476    }
477
478    /// Returns the element that gives the maximum value from the
479    /// specified function.
480    ///
481    /// There are two differences with [`Iterator::max_by_key`]:
482    /// - this function always yields a value while [`Iterator::max_by_key`]
483    ///   yields an `Option`.
484    /// - if several elements are equally maximum, the *first* element is
485    ///   returned (unlike [`Iterator::max_by_key`] which returns the last
486    ///   element).
487    ///
488    /// # Examples
489    ///
490    /// ```
491    /// use nonempty_collections::*;
492    /// let max = nev!["hi", "hey", "rust", "yolo"]
493    ///     .into_nonempty_iter()
494    ///     .max_by_key(|item| item.len());
495    /// assert_eq!("rust", max);
496    /// ```
497    #[must_use]
498    fn max_by_key<B, F>(self, mut key: F) -> Self::Item
499    where
500        Self: Sized,
501        B: Ord,
502        F: FnMut(&Self::Item) -> B,
503    {
504        self.map(|item| (key(&item), item))
505            .max_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key))
506            .1
507    }
508
509    /// Returns the minimum element of a non-empty iterator.
510    ///
511    /// Unlike [`Iterator::min`], this always yields a value.
512    ///
513    /// ```
514    /// use nonempty_collections::*;
515    ///
516    /// let v = nev![1000, 1, 2000, 3000];
517    /// assert_eq!(1, v.into_nonempty_iter().min());
518    /// ```
519    #[must_use]
520    fn min(self) -> Self::Item
521    where
522        Self: Sized,
523        Self::Item: Ord,
524    {
525        self.min_by(Ord::cmp)
526    }
527
528    /// Returns the element that gives the minimum value with respect to the
529    /// given comparison function.
530    ///
531    /// Unlike [`Iterator::min_by`], this always yields a value.
532    #[must_use]
533    fn min_by<F>(self, compare: F) -> Self::Item
534    where
535        Self: Sized,
536        F: Fn(&Self::Item, &Self::Item) -> Ordering,
537    {
538        let (first, iter) = self.next();
539
540        iter.into_iter()
541            .fold(first, |acc, item| match compare(&acc, &item) {
542                Ordering::Greater => item,
543                _ => acc,
544            })
545    }
546
547    /// Returns the element that gives the minimum value from the
548    /// specified function.
549    ///
550    /// There are two differences with [`Iterator::min_by_key`]:
551    /// - this function always yields a value while [`Iterator::min_by_key`]
552    ///   yields an `Option`.
553    /// - if several elements are equally minimum, the *first* element is
554    ///   returned (unlike [`Iterator::min_by_key`] which returns the last
555    ///   element).
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use nonempty_collections::*;
561    /// let min = nev!["hi", "hello", "greetings", "hy"]
562    ///     .into_nonempty_iter()
563    ///     .min_by_key(|item| item.len());
564    /// assert_eq!("hi", min);
565    /// ```
566    #[must_use]
567    fn min_by_key<B, F>(self, mut key: F) -> Self::Item
568    where
569        Self: Sized,
570        B: Ord,
571        F: FnMut(&Self::Item) -> B,
572    {
573        self.map(|item| (key(&item), item))
574            .min_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key))
575            .1
576    }
577
578    /// Sort all iterator elements into a new non-empty iterator in ascending
579    /// order.
580    ///
581    /// **Note:** This consumes the entire iterator, uses the
582    /// [`NEVec::sort_by_key`] method and returns the result as a new iterator
583    /// that owns its elements.
584    ///
585    /// This sort is stable (i.e., does not reorder equal elements).
586    ///
587    /// The sorted iterator, if directly collected to a `NEVec`, is converted
588    /// without any extra copying or allocation cost.
589    ///
590    /// ```
591    /// use nonempty_collections::*;
592    ///
593    /// // sort people in descending order by age
594    /// let people = nev![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 30)];
595    ///
596    /// let oldest_people_first = people
597    ///     .into_nonempty_iter()
598    ///     .sorted_by_key(|x| -x.1)
599    ///     .map(|(person, _age)| person)
600    ///     .collect::<NEVec<_>>();
601    ///
602    /// assert_eq!(nev!["Jill", "Jack", "Jane", "John"], oldest_people_first);
603    /// ```
604    fn sorted_by_key<K, F>(self, f: F) -> crate::vector::IntoIter<Self::Item>
605    where
606        Self: Sized,
607        K: Ord,
608        F: FnMut(&Self::Item) -> K,
609    {
610        let mut v = NEVec::from_nonempty_iter(self);
611        v.sort_by_key(f);
612        v.into_nonempty_iter()
613    }
614
615    /// Returns the `n`th element of the iterator.
616    ///
617    /// This function consumes this `NonEmptyIterator`. [`Self::next()`] can be
618    /// used for getting the first element and a reference to an iterator
619    /// over the remaining elements.
620    ///
621    /// See also [`Iterator::nth`].
622    ///
623    /// ```
624    /// use nonempty_collections::*;
625    ///
626    /// let n = nev![0, 1, 2, 3, 4, 5, 6];
627    /// assert_eq!(Some(&0), n.nonempty_iter().nth(0));
628    ///
629    /// let n = nev![0, 1, 2, 3, 4, 5, 6];
630    /// assert_eq!(Some(&6), n.nonempty_iter().nth(6));
631    ///
632    /// let n = nev![0, 1, 2, 3, 4, 5, 6];
633    /// assert_eq!(None, n.nonempty_iter().nth(100));
634    /// ```
635    fn nth(self, n: usize) -> Option<Self::Item>
636    where
637        Self: Sized,
638    {
639        self.into_iter().nth(n)
640    }
641
642    /// Skip the first `n` elements.
643    ///
644    /// Note that the result will not be non-empty.
645    ///
646    /// See also [`Iterator::skip`].
647    ///
648    /// ```
649    /// use nonempty_collections::*;
650    ///
651    /// let v = nev![1, 2, 3];
652    /// assert_eq!(Some(&3), v.nonempty_iter().skip(2).next());
653    /// ```
654    fn skip(self, n: usize) -> std::iter::Skip<<Self as IntoIterator>::IntoIter>
655    where
656        Self: Sized,
657    {
658        self.into_iter().skip(n)
659    }
660
661    /// Skips over all initial elements that pass a given predicate.
662    ///
663    /// **Note**: This does not yield a non-empty iterator, since there is no
664    /// guarantee that anything will fail the predicate.
665    ///
666    /// See also [`Iterator::skip_while`].
667    ///
668    /// ```
669    /// use nonempty_collections::*;
670    ///
671    /// let v = nev![2, 4, 6, 7, 8];
672    /// let r: Vec<_> = v.into_nonempty_iter().skip_while(|n| n % 2 == 0).collect();
673    /// assert_eq!(vec![7, 8], r);
674    /// ```
675    fn skip_while<P>(self, pred: P) -> std::iter::SkipWhile<<Self as IntoIterator>::IntoIter, P>
676    where
677        Self: Sized,
678        P: FnMut(&<Self as IntoIterator>::Item) -> bool,
679    {
680        self.into_iter().skip_while(pred)
681    }
682
683    /// Sums the elements of a non-empty iterator.
684    ///
685    /// See also [`Iterator::sum`].
686    ///
687    /// ```
688    /// use nonempty_collections::*;
689    ///
690    /// let sum: u32 = nev![1, 2, 3, 4].nonempty_iter().sum();
691    /// assert_eq!(10, sum);
692    /// ```
693    #[must_use]
694    fn sum<S>(self) -> S
695    where
696        Self: Sized + IntoIterator,
697        S: Sum<<Self as IntoIterator>::Item>,
698    {
699        Sum::sum(self.into_iter())
700    }
701
702    /// Iterates over the first `n` elements, or fewer if the underlying
703    /// iterator ends sooner.
704    ///
705    /// See also [`Iterator::take`].
706    ///
707    /// # Panics
708    ///
709    /// Panics if `n == 0`.
710    ///
711    /// # Examples
712    ///
713    /// ```
714    /// use core::num::NonZeroUsize;
715    ///
716    /// use nonempty_collections::*;
717    ///
718    /// let n: NEVec<_> = nev![1, 2, 3]
719    ///     .nonempty_iter()
720    ///     .map(|n| n * 2)
721    ///     .take(NonZeroUsize::new(2).unwrap())
722    ///     .collect();
723    /// assert_eq!(nev![2, 4], n);
724    /// ```
725    fn take(self, n: NonZeroUsize) -> Take<Self>
726    where
727        Self: Sized,
728    {
729        Take {
730            iter: self.into_iter().take(n.get()),
731        }
732    }
733
734    /// Iterates over all initial elements that pass a given predicate.
735    ///
736    /// **Note**: This does not yield a non-empty iterator, since there is no
737    /// guarantee that anything will pass the predicate.
738    ///
739    /// See also [`Iterator::take_while`].
740    ///
741    /// ```
742    /// use nonempty_collections::*;
743    ///
744    /// let v = nev![2, 4, 6, 7, 8];
745    /// let r: Vec<_> = v.into_nonempty_iter().take_while(|n| n % 2 == 0).collect();
746    /// assert_eq!(vec![2, 4, 6], r);
747    /// ```
748    fn take_while<P>(self, pred: P) -> std::iter::TakeWhile<<Self as IntoIterator>::IntoIter, P>
749    where
750        Self: Sized,
751        P: FnMut(&<Self as IntoIterator>::Item) -> bool,
752    {
753        self.into_iter().take_while(pred)
754    }
755
756    /// Iterates over the entire non-empty iterator, multiplying all the
757    /// elements.
758    ///
759    /// See also [`Iterator::product`].
760    ///
761    /// ```
762    /// use nonempty_collections::*;
763    ///
764    /// let prod: u32 = nev![1, 2, 3, 4].nonempty_iter().product();
765    /// assert_eq!(24, prod);
766    /// ```
767    #[must_use]
768    fn product<P>(self) -> P
769    where
770        Self: Sized + IntoIterator,
771        P: Product<<Self as IntoIterator>::Item>,
772    {
773        Product::product(self.into_iter())
774    }
775
776    /// "Zips up" two non-empty iterators into a single one, while preserving
777    /// non-emptiness.
778    ///
779    /// See also [`Iterator::zip`].
780    ///
781    /// ```
782    /// use nonempty_collections::*;
783    ///
784    /// let a = nev![1, 2, 3];
785    /// let b = nev![4, 5, 6, 7];
786    /// let r = a
787    ///     .into_nonempty_iter()
788    ///     .zip(b)
789    ///     .map(|(av, bv)| av + bv)
790    ///     .collect();
791    /// assert_eq!(nev![5, 7, 9], r);
792    /// ```
793    fn zip<U>(self, other: U) -> Zip<Self::IntoIter, U::IntoIter>
794    where
795        Self: Sized,
796        U: IntoNonEmptyIterator,
797    {
798        Zip {
799            inner: self.into_iter().zip(other),
800        }
801    }
802
803    /// Reduces the elements to a single one, by repeatedly applying a reducing
804    /// operation.
805    ///
806    /// See also [`Iterator::reduce`].
807    ///
808    /// ```
809    /// use nonempty_collections::*;
810    ///
811    /// let a = nev![1, 2, 3, 4];
812    /// let b = a.clone();
813    ///
814    /// let x = a.into_nonempty_iter().reduce(|acc, v| acc + v);
815    /// assert_eq!(x, 10);
816    ///
817    /// let y = b.into_nonempty_iter().reduce(|acc, v| acc * v);
818    /// assert_eq!(y, 24);
819    /// ```
820    #[must_use]
821    fn reduce<F>(self, f: F) -> Self::Item
822    where
823        Self: Sized,
824        F: FnMut(Self::Item, Self::Item) -> Self::Item,
825    {
826        self.into_iter().reduce(f).unwrap()
827    }
828}
829
830/// Conversion from a [`NonEmptyIterator`].
831pub trait FromNonEmptyIterator<T>: Sized {
832    /// Creates a value from a [`NonEmptyIterator`].
833    fn from_nonempty_iter<I>(iter: I) -> Self
834    where
835        I: IntoNonEmptyIterator<Item = T>;
836}
837
838impl<T> FromNonEmptyIterator<T> for Vec<T> {
839    fn from_nonempty_iter<I>(iter: I) -> Self
840    where
841        I: IntoNonEmptyIterator<Item = T>,
842    {
843        iter.into_nonempty_iter().into_iter().collect()
844    }
845}
846
847impl<K, V, S> FromNonEmptyIterator<(K, V)> for HashMap<K, V, S>
848where
849    K: Eq + Hash,
850    S: BuildHasher + Default,
851{
852    fn from_nonempty_iter<I>(iter: I) -> Self
853    where
854        I: IntoNonEmptyIterator<Item = (K, V)>,
855    {
856        iter.into_nonempty_iter().into_iter().collect()
857    }
858}
859
860impl<T, S> FromNonEmptyIterator<T> for HashSet<T, S>
861where
862    T: Eq + Hash,
863    S: BuildHasher + Default,
864{
865    fn from_nonempty_iter<I>(iter: I) -> Self
866    where
867        I: IntoNonEmptyIterator<Item = T>,
868    {
869        iter.into_nonempty_iter().into_iter().collect()
870    }
871}
872
873impl<A, E, V> FromNonEmptyIterator<Result<A, E>> for Result<V, E>
874where
875    V: FromNonEmptyIterator<A>,
876{
877    fn from_nonempty_iter<I>(iter: I) -> Result<V, E>
878    where
879        I: IntoNonEmptyIterator<Item = Result<A, E>>,
880    {
881        let (head, rest) = iter.into_nonempty_iter().next();
882        let head: A = head?;
883
884        let mut buf = NEVec::new(head);
885
886        for item in rest {
887            let item: A = item?;
888            buf.push(item);
889        }
890        let new_iter = buf.into_nonempty_iter();
891        let output: V = FromNonEmptyIterator::from_nonempty_iter(new_iter);
892        Ok(output)
893    }
894}
895
896/// Conversion into a [`NonEmptyIterator`].
897pub trait IntoNonEmptyIterator: IntoIterator {
898    /// Which kind of [`NonEmptyIterator`] are we turning this into?
899    type IntoNEIter: NonEmptyIterator<Item = Self::Item>;
900
901    /// Creates a [`NonEmptyIterator`] from a value.
902    fn into_nonempty_iter(self) -> Self::IntoNEIter;
903}
904
905impl<I: NonEmptyIterator> IntoNonEmptyIterator for I {
906    type IntoNEIter = I;
907
908    fn into_nonempty_iter(self) -> Self::IntoNEIter {
909        self
910    }
911}
912
913/// Similar to [`std::iter::Map`], but with additional non-emptiness guarantees.
914#[derive(Clone)]
915#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
916pub struct Map<I: NonEmptyIterator, F> {
917    iter: std::iter::Map<I::IntoIter, F>,
918}
919
920impl<U, I, F> NonEmptyIterator for Map<I, F>
921where
922    I: NonEmptyIterator,
923    F: FnMut(I::Item) -> U,
924{
925}
926
927/// ```
928/// use nonempty_collections::*;
929///
930/// let v: Vec<_> = nev![1, 2, 3].nonempty_iter().map(|n| n * 2).collect();
931/// ```
932impl<U, I, F> IntoIterator for Map<I, F>
933where
934    I: NonEmptyIterator,
935    F: FnMut(I::Item) -> U,
936{
937    type Item = U;
938
939    type IntoIter = std::iter::Map<I::IntoIter, F>;
940
941    fn into_iter(self) -> Self::IntoIter {
942        self.iter
943    }
944}
945
946impl<I, F> std::fmt::Debug for Map<I, F>
947where
948    I: NonEmptyIterator,
949    I::IntoIter: std::fmt::Debug,
950{
951    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
952        self.iter.fmt(f)
953    }
954}
955
956/// An iterator that clones the elements of an underlying iterator.
957///
958/// See also [`std::iter::Cloned`].
959#[derive(Clone)]
960#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
961pub struct Cloned<I> {
962    iter: I,
963}
964
965impl<'a, I, T: 'a> NonEmptyIterator for Cloned<I>
966where
967    I: NonEmptyIterator<Item = &'a T>,
968    T: Clone,
969{
970}
971
972impl<'a, I, T: 'a> IntoIterator for Cloned<I>
973where
974    I: IntoIterator<Item = &'a T>,
975    T: Clone,
976{
977    type Item = T;
978
979    type IntoIter = std::iter::Cloned<I::IntoIter>;
980
981    fn into_iter(self) -> Self::IntoIter {
982        self.iter.into_iter().cloned()
983    }
984}
985
986impl<I: std::fmt::Debug> std::fmt::Debug for Cloned<I> {
987    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
988        self.iter.fmt(f)
989    }
990}
991
992/// An iterator that yields the current count and the element during iteration.
993///
994/// See also [`std::iter::Enumerate`].
995#[derive(Clone)]
996#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
997pub struct Enumerate<I> {
998    iter: I,
999}
1000
1001impl<I> NonEmptyIterator for Enumerate<I> where I: NonEmptyIterator {}
1002
1003impl<I> IntoIterator for Enumerate<I>
1004where
1005    I: IntoIterator,
1006{
1007    type Item = (usize, I::Item);
1008
1009    type IntoIter = std::iter::Enumerate<I::IntoIter>;
1010
1011    fn into_iter(self) -> Self::IntoIter {
1012        self.iter.into_iter().enumerate()
1013    }
1014}
1015
1016impl<I: std::fmt::Debug> std::fmt::Debug for Enumerate<I> {
1017    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1018        self.iter.fmt(f)
1019    }
1020}
1021
1022/// A non-empty iterator that only iterates over the first `n` iterations.
1023///
1024/// See also [`Iterator::take`].
1025#[derive(Clone)]
1026#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1027pub struct Take<I: NonEmptyIterator> {
1028    iter: std::iter::Take<I::IntoIter>,
1029}
1030
1031impl<I> NonEmptyIterator for Take<I> where I: NonEmptyIterator {}
1032
1033/// ```
1034/// use core::num::NonZeroUsize;
1035///
1036/// use nonempty_collections::*;
1037///
1038/// let v = nev![1, 2, 3];
1039/// let r = v
1040///     .nonempty_iter()
1041///     .take(NonZeroUsize::new(1).unwrap())
1042///     .into_iter()
1043///     .count();
1044/// assert_eq!(1, r);
1045/// ```
1046impl<I> IntoIterator for Take<I>
1047where
1048    I: NonEmptyIterator,
1049{
1050    type Item = I::Item;
1051
1052    type IntoIter = std::iter::Take<I::IntoIter>;
1053
1054    fn into_iter(self) -> Self::IntoIter {
1055        self.iter
1056    }
1057}
1058
1059impl<I> std::fmt::Debug for Take<I>
1060where
1061    I: NonEmptyIterator,
1062    I::IntoIter: std::fmt::Debug,
1063{
1064    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065        self.iter.fmt(f)
1066    }
1067}
1068
1069/// A non-empty iterator that links two iterators together, in a chain.
1070#[derive(Clone)]
1071#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1072pub struct Chain<A, B> {
1073    inner: std::iter::Chain<A, B>,
1074}
1075
1076impl<A, B> NonEmptyIterator for Chain<A, B>
1077where
1078    A: Iterator,
1079    B: Iterator<Item = A::Item>,
1080{
1081}
1082
1083impl<A, B> IntoIterator for Chain<A, B>
1084where
1085    A: Iterator,
1086    B: Iterator<Item = A::Item>,
1087{
1088    type Item = A::Item;
1089
1090    type IntoIter = std::iter::Chain<A, B>;
1091
1092    fn into_iter(self) -> Self::IntoIter {
1093        self.inner
1094    }
1095}
1096
1097impl<A, B> std::fmt::Debug for Chain<A, B>
1098where
1099    A: std::fmt::Debug,
1100    B: std::fmt::Debug,
1101{
1102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1103        self.inner.fmt(f)
1104    }
1105}
1106
1107/// A non-empty iterator that yields an element exactly once.
1108#[derive(Clone)]
1109#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1110pub struct Once<T> {
1111    inner: std::iter::Once<T>,
1112}
1113
1114impl<T> Once<T> {
1115    pub(crate) fn new(value: T) -> Once<T> {
1116        Once {
1117            inner: std::iter::once(value),
1118        }
1119    }
1120}
1121
1122impl<T> NonEmptyIterator for Once<T> {}
1123
1124impl<T> IntoIterator for Once<T> {
1125    type Item = T;
1126
1127    type IntoIter = std::iter::Once<T>;
1128
1129    fn into_iter(self) -> Self::IntoIter {
1130        self.inner
1131    }
1132}
1133
1134impl<T: std::fmt::Debug> std::fmt::Debug for Once<T> {
1135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1136        self.inner.fmt(f)
1137    }
1138}
1139
1140/// A non-empty iterator that copies the elements of an underlying non-empty
1141/// iterator.
1142///
1143/// See also [`std::iter::Copied`].
1144#[derive(Clone)]
1145#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1146pub struct Copied<I> {
1147    iter: std::iter::Copied<I>,
1148}
1149
1150impl<'a, I, T: 'a> NonEmptyIterator for Copied<I>
1151where
1152    I: Iterator<Item = &'a T>,
1153    T: Copy,
1154{
1155}
1156
1157impl<'a, I, T: 'a> IntoIterator for Copied<I>
1158where
1159    I: Iterator<Item = &'a T>,
1160    T: Copy,
1161{
1162    type Item = T;
1163
1164    type IntoIter = std::iter::Copied<I>;
1165
1166    fn into_iter(self) -> Self::IntoIter {
1167        self.iter
1168    }
1169}
1170
1171impl<'a, I, T: 'a> std::fmt::Debug for Copied<I>
1172where
1173    I: Iterator<Item = &'a T> + std::fmt::Debug,
1174{
1175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1176        self.iter.fmt(f)
1177    }
1178}
1179
1180/// A non-empty iterator that "zips up" its sources.
1181///
1182/// See also [`std::iter::Zip`].
1183#[derive(Clone)]
1184#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1185pub struct Zip<A, B> {
1186    inner: std::iter::Zip<A, B>,
1187}
1188
1189impl<A, B> NonEmptyIterator for Zip<A, B>
1190where
1191    A: Iterator,
1192    B: Iterator,
1193{
1194}
1195
1196impl<A, B> IntoIterator for Zip<A, B>
1197where
1198    A: Iterator,
1199    B: Iterator,
1200{
1201    type Item = (A::Item, B::Item);
1202
1203    type IntoIter = std::iter::Zip<A, B>;
1204
1205    fn into_iter(self) -> Self::IntoIter {
1206        self.inner
1207    }
1208}
1209
1210impl<A, B> std::fmt::Debug for Zip<A, B>
1211where
1212    A: std::fmt::Debug,
1213    B: std::fmt::Debug,
1214{
1215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1216        self.inner.fmt(f)
1217    }
1218}
1219
1220/// Wrapper struct for powering [`NonEmptyIterator::group_by`].
1221#[derive(Debug)]
1222pub struct NEGroupBy<I, F> {
1223    iter: I,
1224    f: F,
1225}
1226
1227impl<I, K, F> NonEmptyIterator for NEGroupBy<I, F>
1228where
1229    I: NonEmptyIterator,
1230    F: FnMut(&I::Item) -> K,
1231    K: PartialEq,
1232{
1233}
1234
1235impl<I, K, F> IntoIterator for NEGroupBy<I, F>
1236where
1237    I: IntoIterator,
1238    F: FnMut(&I::Item) -> K,
1239    K: PartialEq,
1240{
1241    type Item = NEVec<I::Item>;
1242
1243    type IntoIter = GroupBy<<I as IntoIterator>::IntoIter, K, I::Item, F>;
1244
1245    fn into_iter(self) -> Self::IntoIter {
1246        GroupBy {
1247            iter: self.iter.into_iter(),
1248            f: Rc::new(RefCell::new(self.f)),
1249            prev: None,
1250            curr: None,
1251        }
1252    }
1253}
1254
1255/// A (possibly empty) definition of the group-by operation that enables
1256/// [`NEGroupBy`] to be written. You aren't expected to use this directly, thus
1257/// there is no way to construct one.
1258#[derive(Debug)]
1259pub struct GroupBy<I, K, V, F> {
1260    iter: I,
1261    f: Rc<RefCell<F>>,
1262    prev: Option<K>,
1263    curr: Option<NEVec<V>>,
1264}
1265
1266impl<I, K, V, F> Iterator for GroupBy<I, K, V, F>
1267where
1268    I: Iterator<Item = V>,
1269    F: FnMut(&I::Item) -> K,
1270    K: PartialEq,
1271{
1272    type Item = NEVec<I::Item>;
1273
1274    fn next(&mut self) -> Option<Self::Item> {
1275        loop {
1276            match self.iter.next() {
1277                None => return self.curr.take(),
1278                Some(v) => {
1279                    let k = {
1280                        let mut f = self.f.borrow_mut();
1281                        f(&v)
1282                    };
1283
1284                    match (self.prev.as_ref(), &mut self.curr) {
1285                        // Continue some run of similar values.
1286                        (Some(p), Some(c)) if p == &k => {
1287                            c.push(v);
1288                        }
1289                        // We found a break; finally yield an NEVec.
1290                        (Some(_), Some(_)) => {
1291                            let curr = self.curr.take();
1292                            self.curr = Some(nev![v]);
1293                            self.prev = Some(k);
1294                            return curr;
1295                        }
1296                        // Very first iteration.
1297                        (_, _) => {
1298                            self.prev = Some(k);
1299                            self.curr = Some(nev![v]);
1300                        }
1301                    }
1302                }
1303            }
1304        }
1305    }
1306}
1307
1308/// Flatten nested, non-empty structures.
1309///
1310/// See also [`std::iter::FlatMap`].
1311#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1312pub struct FlatMap<I, U: IntoIterator, F> {
1313    inner: std::iter::FlatMap<I, U, F>,
1314}
1315
1316impl<I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U> NonEmptyIterator for FlatMap<I, U, F> {}
1317
1318/// ```
1319/// use nonempty_collections::*;
1320///
1321/// let v = nev![1, 2, 3];
1322/// let r: Vec<_> = v
1323///     .into_nonempty_iter()
1324///     .flat_map(|n| nev![n])
1325///     .into_iter()
1326///     .collect();
1327/// assert_eq!(vec![1, 2, 3], r);
1328/// ```
1329impl<I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U> IntoIterator for FlatMap<I, U, F> {
1330    type Item = U::Item;
1331
1332    type IntoIter = std::iter::FlatMap<I, U, F>;
1333
1334    fn into_iter(self) -> Self::IntoIter {
1335        self.inner
1336    }
1337}
1338
1339impl<I: std::fmt::Debug, U, F> std::fmt::Debug for FlatMap<I, U, F>
1340where
1341    U: IntoIterator,
1342    U::IntoIter: std::fmt::Debug,
1343{
1344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1345        self.inner.fmt(f)
1346    }
1347}
1348
1349impl<I: Clone, U, F: Clone> Clone for FlatMap<I, U, F>
1350where
1351    U: Clone + IntoIterator,
1352    U::IntoIter: Clone,
1353{
1354    fn clone(&self) -> Self {
1355        FlatMap {
1356            inner: self.inner.clone(),
1357        }
1358    }
1359}
1360
1361/// An adapter for regular iterators that are known to be non-empty.
1362#[derive(Clone)]
1363#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1364pub struct NonEmptyIterAdapter<I> {
1365    inner: I,
1366}
1367
1368impl<I: Iterator> NonEmptyIterator for NonEmptyIterAdapter<I> {}
1369
1370impl<I> IntoIterator for NonEmptyIterAdapter<I>
1371where
1372    I: Iterator,
1373{
1374    type Item = I::Item;
1375
1376    type IntoIter = I;
1377
1378    fn into_iter(self) -> Self::IntoIter {
1379        self.inner
1380    }
1381}
1382
1383impl<I: std::fmt::Debug> std::fmt::Debug for NonEmptyIterAdapter<I> {
1384    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1385        self.inner.fmt(f)
1386    }
1387}
1388
1389/// Convenience trait extending [`IntoIterator`].
1390pub trait IntoIteratorExt {
1391    /// The type of the elements being iterated over.
1392    type Item;
1393    /// Which kind of [`NonEmptyIterator`] are we turning this into?
1394    type IntoIter: NonEmptyIterator<Item = Self::Item>;
1395
1396    /// Tries to convert `self` into a [`NonEmptyIterator`].
1397    ///
1398    /// ```
1399    /// use nonempty_collections::*;
1400    ///
1401    /// let a = vec![1];
1402    /// let x = a.try_into_nonempty_iter();
1403    /// assert!(x.is_some());
1404    ///
1405    /// let y = x.unwrap().collect::<NEVec<_>>();
1406    /// assert_eq!(y.len().get(), 1);
1407    /// ```
1408    ///
1409    /// ```
1410    /// use nonempty_collections::*;
1411    ///
1412    /// let b: Vec<u8> = vec![];
1413    /// let x = b.try_into_nonempty_iter();
1414    ///
1415    /// assert!(x.is_none());
1416    /// ```
1417    ///
1418    /// To construct non-empty collections directly, consider macros like
1419    /// [`crate::nev!`].
1420    fn try_into_nonempty_iter(self) -> Option<Self::IntoIter>;
1421}
1422
1423impl<T> IntoIteratorExt for T
1424where
1425    T: IntoIterator,
1426{
1427    type Item = T::Item;
1428
1429    type IntoIter = NonEmptyIterAdapter<Peekable<T::IntoIter>>;
1430
1431    /// Converts `self` into a non-empty iterator or returns `None` if
1432    /// the iterator is empty.
1433    fn try_into_nonempty_iter(self) -> Option<Self::IntoIter> {
1434        let mut iter = self.into_iter().peekable();
1435        iter.peek()
1436            .is_some()
1437            .then_some(NonEmptyIterAdapter { inner: iter })
1438    }
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443    use super::*;
1444    use crate::nem;
1445    use crate::NEMap;
1446
1447    #[test]
1448    fn into_hashset() {
1449        let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
1450        let _: HashSet<_> = m.values().collect();
1451    }
1452
1453    #[test]
1454    fn into_hashmap() {
1455        let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
1456        let h: HashMap<_, _> = m.iter().map(|(k, v)| (*k, *v)).collect();
1457        let n = NEMap::try_from(h).unwrap();
1458        assert_eq!(m, n);
1459    }
1460}