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