non_empty_iter/
non_empty.rs

1//! The non-empty iterator core traits.
2
3use core::{
4    cmp::Ordering,
5    iter::{self, Product, Sum},
6};
7
8use non_zero_size::Size;
9
10use crate::{
11    adapter::NonEmptyAdapter, chain::Chain, cloned::Cloned, copied::Copied, cycle::Cycle,
12    enumerate::Enumerate, flat_map::FlatMap, flatten::Flatten, fuse::Fuse, inspect::Inspect,
13    map::Map, peeked::Peeked, rev::Rev, step_by::StepBy, take::Take, zip::Zip,
14};
15
16/// Represents [`Iterator`] that is guaranteed to be non-empty
17/// (equivalently, having at least one item).
18///
19/// Note that this trait is `unsafe` to implement, as the implementor must guarantee non-emptiness.
20///
21/// Moreover, [`NonEmptyIterator`] has [`IntoIterator`] and [`Sized`] bounds, as it is always
22/// consumed by value and converted into the underlying iterator.
23///
24/// One can use the `for` loop with non-empty iterators, and downgrade to the regular [`Iterator`]
25/// by calling [`into_iter`] or [`consume`].
26///
27/// # Safety
28///
29/// By implementing [`NonEmptyIterator`] the implementor is responsible
30/// for ensuring that non-emptiness holds. Violating this invariant causes
31/// *Undefined Behavior*!
32///
33/// [`into_iter`]: IntoIterator::into_iter
34/// [`consume`]: NonEmptyIterator::consume
35pub unsafe trait NonEmptyIterator: IntoIterator + Sized {
36    /// Consumes the non-empty iterator, returning the next item
37    /// along with the possibly empty iterator.
38    #[must_use]
39    fn consume(self) -> (Self::Item, Self::IntoIter) {
40        let mut iterator = self.into_iter();
41
42        // SAFETY: the implementor guarantees the iterator is non-empty
43        let item = unsafe { iterator.next().unwrap_unchecked() };
44
45        (item, iterator)
46    }
47
48    /// Consumes the non-empty iterator, returning the item count.
49    ///
50    /// See also [`count`] on [`Iterator`].
51    ///
52    /// # Non-zero
53    ///
54    /// The returned count is guaranteed to be non-zero.
55    ///
56    /// [`count`]: Iterator::count
57    #[must_use]
58    fn count(self) -> Size {
59        let count = self.into_iter().count();
60
61        // SAFETY: the implementor guarantees the iterator is non-empty
62        // therefore, `count` is non-zero
63        unsafe { Size::new_unchecked(count) }
64    }
65
66    /// Creates non-empty iterators that yield the current count and the item during iteration.
67    ///
68    /// See also [`enumerate`] on [`Iterator`].
69    ///
70    /// # Non-empty
71    ///
72    /// The returned iterator is guaranteed to be non-empty.
73    ///
74    /// [`enumerate`]: Iterator::enumerate
75    fn enumerate(self) -> Enumerate<Self> {
76        Enumerate::new(self)
77    }
78
79    /// Peeks at the next item of the non-empty iterator, returning it along
80    /// with the possibly empty iterator.
81    ///
82    /// This is equivalent to calling [`consume`] and wrapping the output.
83    ///
84    /// See also [`peekable`] on [`Iterator`].
85    ///
86    /// # Non-empty
87    ///
88    /// The returned iterator is guaranteed to be non-empty.
89    ///
90    /// [`consume`]: NonEmptyIterator::consume
91    /// [`peekable`]: Iterator::peekable
92    fn peeked(self) -> Peeked<Self::IntoIter> {
93        let (item, rest) = self.consume();
94
95        Peeked::new(item, rest)
96    }
97
98    /// Links the non-empty iterator with the provided possibly empty iterator.
99    ///
100    /// See also [`chain`] on [`Iterator`].
101    ///
102    /// # Non-empty
103    ///
104    /// The returned iterator is guaranteed to be non-empty.
105    ///
106    /// [`chain`]: Iterator::chain
107    fn chain<I: IntoIterator<Item = Self::Item>>(self, other: I) -> Chain<Self, I::IntoIter> {
108        Chain::new(self, other.into_iter())
109    }
110
111    /// Creates non-empty iterators that clone the items of the underlying non-empty iterator.
112    ///
113    /// See also [`cloned`] on [`Iterator`].
114    ///
115    /// # Non-empty
116    ///
117    /// The returned iterator is guaranteed to be non-empty.
118    ///
119    /// [`cloned`]: Iterator::cloned
120    fn cloned<'a, T>(self) -> Cloned<Self>
121    where
122        Self: NonEmptyIterator<Item = &'a T>,
123        T: Clone + 'a,
124    {
125        Cloned::new(self)
126    }
127
128    /// Creates non-empty iterators that copy the items of the underlying non-empty iterator.
129    ///
130    /// See also [`copied`] on [`Iterator`].
131    ///
132    /// # Non-empty
133    ///
134    /// The returned iterator is guaranteed to be non-empty.
135    ///
136    /// [`copied`]: Iterator::copied
137    fn copied<'a, T>(self) -> Copied<Self>
138    where
139        Self: NonEmptyIterator<Item = &'a T>,
140        T: Copy + 'a,
141    {
142        Copied::new(self)
143    }
144
145    /// Zips the non-empty iterator with the provided non-empty iterator.
146    ///
147    /// This allows to iterate over the items of both iterators simultaneously.
148    ///
149    /// See also [`zip`] on [`Iterator`].
150    ///
151    /// # Difference from [`Iterator`]
152    ///
153    /// Note that the argument is required to be [`IntoNonEmptyIterator`].
154    ///
155    /// # Non-empty
156    ///
157    /// The returned iterator is guaranteed to be non-empty.
158    ///
159    /// [`zip`]: Iterator::zip
160    fn zip<I: IntoNonEmptyIterator>(self, other: I) -> Zip<Self, I::IntoNonEmptyIter> {
161        Zip::new(self, other.into_non_empty_iter())
162    }
163
164    /// Sums the items of the non-empty iterator together.
165    ///
166    /// See also [`sum`] on [`Iterator`].
167    ///
168    /// [`sum`]: Iterator::sum
169    #[must_use]
170    fn sum<S: Sum<Self::Item>>(self) -> S {
171        self.into_iter().sum()
172    }
173
174    /// Multiplies the items of the non-empty iterator together.
175    ///
176    /// See also [`product`] on [`Iterator`].
177    ///
178    /// [`product`]: Iterator::product
179    #[must_use]
180    fn product<P: Product<Self::Item>>(self) -> P {
181        self.into_iter().product()
182    }
183
184    /// Tests whether all items of the non-empty iterator match the predicate.
185    ///
186    /// See also [`all`] on [`Iterator`].
187    ///
188    /// [`all`]: Iterator::all
189    fn all<P: FnMut(Self::Item) -> bool>(self, predicate: P) -> bool {
190        self.into_iter().all(predicate)
191    }
192
193    /// Tests whether any items of the non-empty iterator match the predicate.
194    ///
195    /// See also [`any`] on [`Iterator`].
196    ///
197    /// [`any`]: Iterator::any
198    fn any<P: FnMut(Self::Item) -> bool>(self, predicate: P) -> bool {
199        self.into_iter().any(predicate)
200    }
201
202    /// Tests whether no items of the non-empty iterator match the predicate.
203    ///
204    /// This is equivalent to negating the output of [`any`].
205    ///
206    /// [`any`]: NonEmptyIterator::any
207    fn none<P: FnMut(Self::Item) -> bool>(self, predicate: P) -> bool {
208        !self.any(predicate)
209    }
210
211    /// Reduces the items of the non-empty iterator into the single one
212    /// by repeatedly applying the given function.
213    ///
214    /// See also [`reduce`] on [`Iterator`].
215    ///
216    /// # Difference from [`Iterator`]
217    ///
218    /// Note that this function always returns some value, as the iterator is non-empty.
219    ///
220    /// [`reduce`]: Iterator::reduce
221    #[must_use]
222    fn reduce<F>(self, function: F) -> Self::Item
223    where
224        F: FnMut(Self::Item, Self::Item) -> Self::Item,
225    {
226        let output = self.into_iter().reduce(function);
227
228        // SAFETY: the implementor guarantees the iterator is non-empty
229        // therefore, `output` has to contain some value
230        unsafe { output.unwrap_unchecked() }
231    }
232
233    /// Converts the non-empty iterator of pairs into the pair of collections.
234    ///
235    /// See also [`unzip`] on [`Iterator`].
236    ///
237    /// [`unzip`]: Iterator::unzip
238    fn unzip<T, U, C: Default + Extend<T>, D: Default + Extend<U>>(self) -> (C, D)
239    where
240        Self: NonEmptyIterator<Item = (T, U)>,
241    {
242        self.into_iter().unzip()
243    }
244
245    /// Collects the items of the non-empty iterator into the collection.
246    ///
247    /// See also [`collect`] on [`Iterator`].
248    ///
249    /// # Difference from [`Iterator`]
250    ///
251    /// Note that the collection is required to be [`FromNonEmptyIterator`],
252    /// though anything that is [`FromIterator`] is also [`FromNonEmptyIterator`].
253    ///
254    /// [`collect`]: Iterator::collect
255    fn collect<C: FromNonEmptyIterator<Self::Item>>(self) -> C {
256        C::from_non_empty_iter(self)
257    }
258
259    /// Similar to [`map`], but flattens produced non-empty iterators.
260    ///
261    /// See also [`flat_map`] on [`Iterator`].
262    ///
263    /// # Difference from [`Iterator`]
264    ///
265    /// Note that the function is required to return [`IntoNonEmptyIterator`].
266    ///
267    /// # Non-empty
268    ///
269    /// The returned iterator is guaranteed to be non-empty.
270    ///
271    /// [`map`]: NonEmptyIterator::map
272    /// [`flat_map`]: Iterator::flat_map
273    fn flat_map<J: IntoNonEmptyIterator, F: FnMut(Self::Item) -> J>(
274        self,
275        function: F,
276    ) -> FlatMap<Self, J, F> {
277        FlatMap::new(self, function)
278    }
279
280    /// Flattens one level of nesting in `self` non-empty iterator.
281    ///
282    /// See also [`flatten`] on [`Iterator`].
283    ///
284    /// # Difference from [`Iterator`]
285    ///
286    /// Note that the items are required to be [`IntoNonEmptyIterator`].
287    ///
288    /// # Non-empty
289    ///
290    /// The returned iterator is guaranteed to be non-empty.
291    ///
292    /// [`flatten`]: Iterator::flatten
293    fn flatten(self) -> Flatten<Self>
294    where
295        Self::Item: IntoNonEmptyIterator,
296    {
297        Flatten::new(self)
298    }
299
300    /// Equivalent to [`filter`] on [`Iterator`].
301    ///
302    /// Note that the returned iterator can be empty, depending on the predicate.
303    ///
304    /// [`filter`]: Iterator::filter
305    fn filter<P: FnMut(&Self::Item) -> bool>(
306        self,
307        predicate: P,
308    ) -> iter::Filter<Self::IntoIter, P> {
309        self.into_iter().filter(predicate)
310    }
311
312    /// Equivalent to [`find`] on [`Iterator`].
313    ///
314    /// [`find`]: Iterator::find
315    fn find<P: FnMut(&Self::Item) -> bool>(self, predicate: P) -> Option<Self::Item> {
316        self.into_iter().find(predicate)
317    }
318
319    /// Equivalent to [`filter_map`] on [`Iterator`].
320    ///
321    /// Note that the returned iterator can be empty, depending on the function.
322    ///
323    /// [`filter_map`]: Iterator::filter_map
324    fn filter_map<T, F: FnMut(Self::Item) -> Option<T>>(
325        self,
326        function: F,
327    ) -> iter::FilterMap<Self::IntoIter, F> {
328        self.into_iter().filter_map(function)
329    }
330
331    /// Equivalent to [`fold`] on [`Iterator`].
332    ///
333    /// [`fold`]: Iterator::fold
334    #[must_use]
335    fn fold<A, F: FnMut(A, Self::Item) -> A>(self, initial: A, function: F) -> A {
336        self.into_iter().fold(initial, function)
337    }
338
339    /// Creates non-empty iterators that map the items of the non-empty iterator with the function.
340    ///
341    /// See also [`map`] on [`Iterator`].
342    ///
343    /// # Non-empty
344    ///
345    /// The returned iterator is guaranteed to be non-empty.
346    ///
347    /// [`map`]: Iterator::map
348    fn map<U, F: FnMut(Self::Item) -> U>(self, function: F) -> Map<Self, F> {
349        Map::new(self, function)
350    }
351
352    /// Returns the maximum item of the non-empty iterator.
353    ///
354    /// See also [`max`] on [`Iterator`].
355    ///
356    /// # Difference from [`Iterator`]
357    ///
358    /// Note that this function always returns some value, as the iterator is non-empty.
359    ///
360    /// [`max`]: Iterator::max
361    #[must_use]
362    fn max(self) -> Self::Item
363    where
364        Self::Item: Ord,
365    {
366        let max = self.into_iter().max();
367
368        // SAFETY: the implementor guarantees the iterator is non-empty
369        // therefore, `max` has to contain some value
370        unsafe { max.unwrap_unchecked() }
371    }
372
373    /// Returns the maximum item of the non-empty iterator with respect to the comparison function.
374    ///
375    /// See also [`max_by`] on [`Iterator`].
376    ///
377    /// # Difference from [`Iterator`]
378    ///
379    /// Note that this function always returns some value, as the iterator is non-empty.
380    ///
381    /// [`max_by`]: Iterator::max_by
382    #[must_use]
383    fn max_by<F: FnMut(&Self::Item, &Self::Item) -> Ordering>(self, function: F) -> Self::Item {
384        let max = self.into_iter().max_by(function);
385
386        // SAFETY: the implementor guarantees the iterator is non-empty
387        // therefore, `max` has to contain some value
388        unsafe { max.unwrap_unchecked() }
389    }
390
391    /// Returns the maximum item of the non-empty iterator with respect to the key function.
392    ///
393    /// See also [`max_by_key`] on [`Iterator`].
394    ///
395    /// # Difference from [`Iterator`]
396    ///
397    /// Note that this function always returns some value, as the iterator is non-empty.
398    ///
399    /// [`max_by_key`]: Iterator::max_by_key
400    #[must_use]
401    fn max_by_key<K: Ord, F: FnMut(&Self::Item) -> K>(self, function: F) -> Self::Item {
402        let max = self.into_iter().max_by_key(function);
403
404        // SAFETY: the implementor guarantees the iterator is non-empty
405        // therefore, `max` has to contain some value
406        unsafe { max.unwrap_unchecked() }
407    }
408
409    /// Returns the minimum item of the non-empty iterator.
410    ///
411    /// See also [`min`] on [`Iterator`].
412    ///
413    /// # Difference from [`Iterator`]
414    ///
415    /// Note that this function always returns some value, as the iterator is non-empty.
416    ///
417    /// [`min`]: Iterator::min
418    #[must_use]
419    fn min(self) -> Self::Item
420    where
421        Self::Item: Ord,
422    {
423        let min = self.into_iter().min();
424
425        // SAFETY: the implementor guarantees the iterator is non-empty
426        // therefore, `min` has to contain some value
427        unsafe { min.unwrap_unchecked() }
428    }
429
430    /// Returns the minimum item of the non-empty iterator with respect to the comparison function.
431    ///
432    /// See also [`min_by`] on [`Iterator`].
433    ///
434    /// # Difference from [`Iterator`]
435    ///
436    /// Note that this function always returns some value, as the iterator is non-empty.
437    ///
438    /// [`min_by`]: Iterator::min_by
439    #[must_use]
440    fn min_by<F: FnMut(&Self::Item, &Self::Item) -> Ordering>(self, function: F) -> Self::Item {
441        let min = self.into_iter().min_by(function);
442
443        // SAFETY: the implementor guarantees the iterator is non-empty
444        // therefore, `min` has to contain some value
445        unsafe { min.unwrap_unchecked() }
446    }
447
448    /// Returns the minimum item of the non-empty iterator with respect to the key function.
449    ///
450    /// See also [`min_by_key`] on [`Iterator`].
451    ///
452    /// # Difference from [`Iterator`]
453    ///
454    /// Note that this function always returns some value, as the iterator is non-empty.
455    ///
456    /// [`min_by_key`]: Iterator::min_by_key
457    #[must_use]
458    fn min_by_key<K: Ord, F: FnMut(&Self::Item) -> K>(self, function: F) -> Self::Item {
459        let min = self.into_iter().min_by_key(function);
460
461        // SAFETY: the implementor guarantees the iterator is non-empty
462        // therefore, `min` has to contain some value
463        unsafe { min.unwrap_unchecked() }
464    }
465
466    /// Returns the `n`-th item of the non-empty iterator.
467    ///
468    /// See also [`nth`] on [`Iterator`].
469    ///
470    /// # Difference from [`Iterator`]
471    ///
472    /// Note that this function expects non-zero `n`, as the first item can be obtained
473    /// via [`consume`].
474    ///
475    /// [`nth`]: Iterator::nth
476    fn nth(self, n: Size) -> Option<Self::Item> {
477        self.into_iter().nth(n.get())
478    }
479
480    /// Skips the first given number of items in the non-empty iterator.
481    ///
482    /// See also [`skip`] on [`Iterator`].
483    ///
484    /// The returned iterator can be empty, depending on the count.
485    ///
486    /// # Difference from [`Iterator`]
487    ///
488    /// Note that this function expects non-zero count.
489    ///
490    /// [`skip`]: Iterator::skip
491    fn skip(self, count: Size) -> iter::Skip<Self::IntoIter> {
492        self.into_iter().skip(count.get())
493    }
494
495    /// Takes only the first given number of items from the non-empty iterator.
496    ///
497    /// See also [`take`] on [`Iterator`].
498    ///
499    /// # Difference from [`Iterator`]
500    ///
501    /// Note that this function expects non-zero count in order to guarantee non-emptiness.
502    ///
503    /// # Non-empty
504    ///
505    /// The returned iterator is guaranteed to be non-empty.
506    ///
507    /// [`take`]: Iterator::take
508    fn take(self, count: Size) -> Take<Self> {
509        Take::new(self, count)
510    }
511
512    /// Returns the last item of the non-empty iterator.
513    ///
514    /// See also [`last`] on [`Iterator`].
515    ///
516    /// # Difference from [`Iterator`]
517    ///
518    /// Note that this function always returns some value, as the iterator is non-empty.
519    ///
520    /// [`last`]: Iterator::last
521    #[must_use]
522    fn last(self) -> Self::Item {
523        let last = self.into_iter().last();
524
525        // SAFETY: the implementor guarantees the iterator is non-empty
526        // therefore, `last` has to contain some value
527        unsafe { last.unwrap_unchecked() }
528    }
529
530    /// Steps the non-empty iterator by the given custom amount.
531    ///
532    /// See also [`step_by`] on [`Iterator`].
533    ///
534    /// # Difference from [`Iterator`]
535    ///
536    /// Note that this function expects non-zero step as the [`step_by`] on [`Iterator`]
537    /// panics on zero.
538    ///
539    /// # Non-empty
540    ///
541    /// The returned iterator is guaranteed to be non-empty.
542    ///
543    /// [`step_by`]: Iterator::step_by
544    fn step_by(self, step: Size) -> StepBy<Self> {
545        StepBy::new(self, step)
546    }
547
548    /// Equivalent to [`for_each`] on [`Iterator`].
549    ///
550    /// [`for_each`]: Iterator::for_each
551    fn for_each<F: FnMut(Self::Item)>(self, function: F) {
552        self.into_iter().for_each(function);
553    }
554
555    /// Consumes the iterator, exhausting it by dropping all of its items.
556    ///
557    /// This is equivalent to calling [`for_each`] with [`drop`].
558    ///
559    /// [`for_each`]: NonEmptyIterator::for_each
560    fn exhaust(self) {
561        self.for_each(drop);
562    }
563
564    /// Equivalent to [`skip_while`] on [`Iterator`].
565    ///
566    /// Note that the returned iterator can be empty, depending on the predicate.
567    ///
568    /// [`skip_while`]: Iterator::skip_while
569    fn skip_while<P: FnMut(&Self::Item) -> bool>(
570        self,
571        predicate: P,
572    ) -> iter::SkipWhile<Self::IntoIter, P> {
573        self.into_iter().skip_while(predicate)
574    }
575
576    /// Equivalent to [`take_while`] on [`Iterator`].
577    ///
578    /// Note that the returned iterator can be empty, depending on the predicate.
579    ///
580    /// [`take_while`]: Iterator::take_while
581    fn take_while<P: FnMut(&Self::Item) -> bool>(
582        self,
583        predicate: P,
584    ) -> iter::TakeWhile<Self::IntoIter, P> {
585        self.into_iter().take_while(predicate)
586    }
587
588    /// Equivalent to [`map_while`] on [`Iterator`].
589    ///
590    /// Note that the returned iterator can be empty, depending on the predicate.
591    ///
592    /// [`map_while`]: Iterator::map_while
593    fn map_while<T, P: FnMut(Self::Item) -> Option<T>>(
594        self,
595        predicate: P,
596    ) -> iter::MapWhile<Self::IntoIter, P> {
597        self.into_iter().map_while(predicate)
598    }
599
600    /// Equivalent to [`scan`] on [`Iterator`].
601    ///
602    /// Note that the returned iterator can be empty, depending on the function.
603    ///
604    /// [`scan`]: Iterator::scan
605    fn scan<S, T, F: FnMut(&mut S, Self::Item) -> Option<T>>(
606        self,
607        initial: S,
608        function: F,
609    ) -> iter::Scan<Self::IntoIter, S, F> {
610        self.into_iter().scan(initial, function)
611    }
612
613    /// Creates non-empty iterators that call the provided function with references to each item.
614    ///
615    /// See also [`inspect`] on [`Iterator`].
616    ///
617    /// # Non-empty
618    ///
619    /// The returned iterator is guaranteed to be non-empty.
620    ///
621    /// [`inspect`]: Iterator::inspect
622    fn inspect<F: FnMut(&Self::Item)>(self, function: F) -> Inspect<Self, F> {
623        Inspect::new(self, function)
624    }
625
626    /// Equivalent to [`partition`] on [`Iterator`].
627    ///
628    /// [`partition`]: Iterator::partition
629    fn partition<C: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool>(
630        self,
631        function: F,
632    ) -> (C, C) {
633        self.into_iter().partition(function)
634    }
635
636    /// Equivalent to [`position`] on [`Iterator`].
637    ///
638    /// [`position`]: Iterator::position
639    fn position<P: FnMut(Self::Item) -> bool>(self, predicate: P) -> Option<usize> {
640        self.into_iter().position(predicate)
641    }
642
643    /// Equivalent to [`cmp`] on [`Iterator`].
644    ///
645    /// [`cmp`]: Iterator::cmp
646    fn cmp<I: IntoIterator<Item = Self::Item>>(self, other: I) -> Ordering
647    where
648        Self::Item: Ord,
649    {
650        self.into_iter().cmp(other)
651    }
652
653    /// Equivalent to [`partial_cmp`] on [`Iterator`].
654    ///
655    /// [`partial_cmp`]: Iterator::partial_cmp
656    fn partial_cmp<I: IntoIterator>(self, other: I) -> Option<Ordering>
657    where
658        Self::Item: PartialOrd<I::Item>,
659    {
660        self.into_iter().partial_cmp(other)
661    }
662
663    /// Equivalent to [`eq`] on [`Iterator`].
664    ///
665    /// [`eq`]: Iterator::eq
666    fn eq<I: IntoIterator>(self, other: I) -> bool
667    where
668        Self::Item: PartialEq<I::Item>,
669    {
670        self.into_iter().eq(other)
671    }
672
673    /// Equivalent to [`ne`] on [`Iterator`].
674    ///
675    /// [`ne`]: Iterator::ne
676    fn ne<I: IntoIterator>(self, other: I) -> bool
677    where
678        Self::Item: PartialEq<I::Item>,
679    {
680        self.into_iter().ne(other)
681    }
682
683    /// Equivalent to [`lt`] on [`Iterator`].
684    ///
685    /// [`lt`]: Iterator::lt
686    fn lt<I: IntoIterator>(self, other: I) -> bool
687    where
688        Self::Item: PartialOrd<I::Item>,
689    {
690        self.into_iter().lt(other)
691    }
692
693    /// Equivalent to [`le`] on [`Iterator`].
694    ///
695    /// [`le`]: Iterator::le
696    fn le<I: IntoIterator>(self, other: I) -> bool
697    where
698        Self::Item: PartialOrd<I::Item>,
699    {
700        self.into_iter().le(other)
701    }
702
703    /// Equivalent to [`gt`] on [`Iterator`].
704    ///
705    /// [`gt`]: Iterator::gt
706    fn gt<I: IntoIterator>(self, other: I) -> bool
707    where
708        Self::Item: PartialOrd<I::Item>,
709    {
710        self.into_iter().gt(other)
711    }
712
713    /// Equivalent to [`ge`] on [`Iterator`].
714    fn ge<I: IntoIterator>(self, other: I) -> bool
715    where
716        Self::Item: PartialOrd<I::Item>,
717    {
718        self.into_iter().ge(other)
719    }
720
721    /// Equivalent to [`is_sorted`] on [`Iterator`].
722    ///
723    /// [`is_sorted`]: Iterator::is_sorted
724    #[allow(clippy::wrong_self_convention)]
725    fn is_sorted(self) -> bool
726    where
727        Self::Item: PartialOrd,
728    {
729        self.into_iter().is_sorted()
730    }
731
732    /// Equivalent to [`is_sorted_by`] on [`Iterator`].
733    ///
734    /// [`is_sorted_by`]: Iterator::is_sorted_by
735    #[allow(clippy::wrong_self_convention)]
736    fn is_sorted_by<F: FnMut(&Self::Item, &Self::Item) -> bool>(self, function: F) -> bool {
737        self.into_iter().is_sorted_by(function)
738    }
739
740    /// Equivalent to [`is_sorted_by_key`] on [`Iterator`].
741    ///
742    /// [`is_sorted_by_key`]: Iterator::is_sorted_by_key
743    #[allow(clippy::wrong_self_convention)]
744    fn is_sorted_by_key<K: PartialOrd, F: FnMut(Self::Item) -> K>(self, function: F) -> bool {
745        self.into_iter().is_sorted_by_key(function)
746    }
747
748    /// Similar to [`collect`], but extends the provided collection instead of creating new ones.
749    ///
750    /// Returns the provided collection after extending.
751    ///
752    /// [`collect`]: NonEmptyIterator::collect
753    fn collect_into<C: Extend<Self::Item>>(self, collection: &mut C) -> &mut C {
754        collection.extend(self);
755
756        collection
757    }
758
759    /// Equivalent to [`find_map`] on [`Iterator`].
760    ///
761    /// [`find_map`]: Iterator::find_map
762    fn find_map<T, F: FnMut(Self::Item) -> Option<T>>(self, function: F) -> Option<T> {
763        self.into_iter().find_map(function)
764    }
765
766    /// Fuses the non-empty iterator, ensuring that once it returns [`None`],
767    /// it will return [`None`] forever afterwards.
768    ///
769    /// See also [`fuse`] on [`Iterator`].
770    ///
771    /// # Non-empty
772    ///
773    /// The returned iterator is guaranteed to be non-empty.
774    ///
775    /// [`fuse`]: Iterator::fuse
776    fn fuse(self) -> Fuse<Self> {
777        Fuse::new(self)
778    }
779
780    /// Reverses the iteration in non-empty iterators.
781    ///
782    /// See also [`rev`] on [`Iterator`].
783    ///
784    /// # Non-empty
785    ///
786    /// The returned iterator is guaranteed to be non-empty.
787    ///
788    /// [`rev`]: Iterator::rev
789    fn rev(self) -> Rev<Self>
790    where
791        Self::IntoIter: DoubleEndedIterator,
792    {
793        Rev::new(self)
794    }
795
796    /// Repeats the non-empty iterator endlessly.
797    ///
798    /// See also [`cycle`] on [`Iterator`].
799    ///
800    /// # Non-empty
801    ///
802    /// The returned iterator is guaranteed to be non-empty.
803    ///
804    /// [`cycle`]: Iterator::cycle
805    fn cycle(self) -> Cycle<Self>
806    where
807        Self::IntoIter: Clone,
808    {
809        Cycle::new(self)
810    }
811}
812
813/// Represents types that can be created from non-empty iterators.
814///
815/// This is similar to [`FromIterator`], but specifically for non-empty iterators,
816/// though anything that is [`FromIterator`] is also [`FromNonEmptyIterator`].
817pub trait FromNonEmptyIterator<T>: Sized {
818    /// Creates [`Self`] from the provided non-empty iterator.
819    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = T>>(iterable: I) -> Self;
820}
821
822impl<T, C: FromIterator<T>> FromNonEmptyIterator<T> for C {
823    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = T>>(iterable: I) -> Self {
824        iterable.into_non_empty_iter().into_iter().collect()
825    }
826}
827
828/// Represents types that can be converted into non-empty iterators.
829///
830/// This is similar to [`IntoIterator`], but specifically for non-empty iterators.
831///
832/// Any [`NonEmptyIterator`] is also [`IntoNonEmptyIterator`], akin to how any [`Iterator`]
833/// is also [`IntoIterator`].
834pub trait IntoNonEmptyIterator: IntoIterator {
835    /// What kind of [`NonEmptyIterator`] are we turning this into?
836    type IntoNonEmptyIter: NonEmptyIterator<Item = Self::Item>;
837
838    /// Converts `self` into [`NonEmptyIterator`].
839    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter;
840}
841
842impl<I: NonEmptyIterator> IntoNonEmptyIterator for I {
843    type IntoNonEmptyIter = Self;
844
845    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
846        self
847    }
848}
849
850mod sealed {
851    pub trait Sealed {}
852}
853
854/// Convenience trait implemented for any type that is [`IntoIterator`],
855/// allowing to convert iterables into non-empty ones.
856pub trait TryIntoNonEmptyIterator: sealed::Sealed {
857    /// The type of the items being iterated over.
858    type Item;
859
860    /// Which kind of [`NonEmptyIterator`] are we turning this into?
861    type IntoNonEmptyIter: NonEmptyIterator<Item = Self::Item>;
862
863    /// Tries to convert `self` into [`NonEmptyIterator`].
864    ///
865    /// Returns [`None`] if `self` is empty and therefore can not be converted.
866    fn try_into_non_empty_iter(self) -> Option<Self::IntoNonEmptyIter>;
867}
868
869impl<I: IntoIterator> sealed::Sealed for I {}
870
871impl<I: IntoIterator> TryIntoNonEmptyIterator for I {
872    type Item = I::Item;
873
874    type IntoNonEmptyIter = NonEmptyAdapter<iter::Peekable<I::IntoIter>>;
875
876    fn try_into_non_empty_iter(self) -> Option<Self::IntoNonEmptyIter> {
877        let mut peekable = self.into_iter().peekable();
878
879        peekable.peek()?;
880
881        // SAFETY: `peekable` is non-empty if we reached here
882        Some(unsafe { NonEmptyAdapter::new(peekable) })
883    }
884}