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    /// Equivalent to [`collect`] on [`Iterator`].
246    ///
247    /// See also [`collect_non_empty`].
248    ///
249    /// [`collect`]: Iterator::collect
250    /// [`collect_non_empty`]: NonEmptyIterator::collect_non_empty
251    fn collect<C: FromIterator<Self::Item>>(self) -> C {
252        self.into_iter().collect()
253    }
254
255    /// Collects the items of the non-empty iterator into the collection.
256    ///
257    /// See also [`collect`].
258    ///
259    /// # Difference from [`Iterator`]
260    ///
261    /// Note that the collection is required to be [`FromNonEmptyIterator`].
262    ///
263    /// [`collect`]: NonEmptyIterator::collect
264    fn collect_non_empty<C: FromNonEmptyIterator<Self::Item>>(self) -> C {
265        C::from_non_empty_iter(self)
266    }
267
268    /// Similar to [`map`], but flattens produced non-empty iterators.
269    ///
270    /// See also [`flat_map`] on [`Iterator`].
271    ///
272    /// # Difference from [`Iterator`]
273    ///
274    /// Note that the function is required to return [`IntoNonEmptyIterator`].
275    ///
276    /// # Non-empty
277    ///
278    /// The returned iterator is guaranteed to be non-empty.
279    ///
280    /// [`map`]: NonEmptyIterator::map
281    /// [`flat_map`]: Iterator::flat_map
282    fn flat_map<J: IntoNonEmptyIterator, F: FnMut(Self::Item) -> J>(
283        self,
284        function: F,
285    ) -> FlatMap<Self, J, F> {
286        FlatMap::new(self, function)
287    }
288
289    /// Flattens one level of nesting in `self` non-empty iterator.
290    ///
291    /// See also [`flatten`] on [`Iterator`].
292    ///
293    /// # Difference from [`Iterator`]
294    ///
295    /// Note that the items are required to be [`IntoNonEmptyIterator`].
296    ///
297    /// # Non-empty
298    ///
299    /// The returned iterator is guaranteed to be non-empty.
300    ///
301    /// [`flatten`]: Iterator::flatten
302    fn flatten(self) -> Flatten<Self>
303    where
304        Self::Item: IntoNonEmptyIterator,
305    {
306        Flatten::new(self)
307    }
308
309    /// Equivalent to [`filter`] on [`Iterator`].
310    ///
311    /// Note that the returned iterator can be empty, depending on the predicate.
312    ///
313    /// [`filter`]: Iterator::filter
314    fn filter<P: FnMut(&Self::Item) -> bool>(
315        self,
316        predicate: P,
317    ) -> iter::Filter<Self::IntoIter, P> {
318        self.into_iter().filter(predicate)
319    }
320
321    /// Equivalent to [`find`] on [`Iterator`].
322    ///
323    /// [`find`]: Iterator::find
324    fn find<P: FnMut(&Self::Item) -> bool>(self, predicate: P) -> Option<Self::Item> {
325        self.into_iter().find(predicate)
326    }
327
328    /// Equivalent to [`filter_map`] on [`Iterator`].
329    ///
330    /// Note that the returned iterator can be empty, depending on the function.
331    ///
332    /// [`filter_map`]: Iterator::filter_map
333    fn filter_map<T, F: FnMut(Self::Item) -> Option<T>>(
334        self,
335        function: F,
336    ) -> iter::FilterMap<Self::IntoIter, F> {
337        self.into_iter().filter_map(function)
338    }
339
340    /// Equivalent to [`fold`] on [`Iterator`].
341    ///
342    /// [`fold`]: Iterator::fold
343    #[must_use]
344    fn fold<A, F: FnMut(A, Self::Item) -> A>(self, initial: A, function: F) -> A {
345        self.into_iter().fold(initial, function)
346    }
347
348    /// Creates non-empty iterators that map the items of the non-empty iterator with the function.
349    ///
350    /// See also [`map`] on [`Iterator`].
351    ///
352    /// # Non-empty
353    ///
354    /// The returned iterator is guaranteed to be non-empty.
355    ///
356    /// [`map`]: Iterator::map
357    fn map<U, F: FnMut(Self::Item) -> U>(self, function: F) -> Map<Self, F> {
358        Map::new(self, function)
359    }
360
361    /// Returns the maximum item of the non-empty iterator.
362    ///
363    /// See also [`max`] on [`Iterator`].
364    ///
365    /// # Difference from [`Iterator`]
366    ///
367    /// Note that this function always returns some value, as the iterator is non-empty.
368    ///
369    /// [`max`]: Iterator::max
370    #[must_use]
371    fn max(self) -> Self::Item
372    where
373        Self::Item: Ord,
374    {
375        let max = self.into_iter().max();
376
377        // SAFETY: the implementor guarantees the iterator is non-empty
378        // therefore, `max` has to contain some value
379        unsafe { max.unwrap_unchecked() }
380    }
381
382    /// Returns the maximum item of the non-empty iterator with respect to the comparison function.
383    ///
384    /// See also [`max_by`] on [`Iterator`].
385    ///
386    /// # Difference from [`Iterator`]
387    ///
388    /// Note that this function always returns some value, as the iterator is non-empty.
389    ///
390    /// [`max_by`]: Iterator::max_by
391    #[must_use]
392    fn max_by<F: FnMut(&Self::Item, &Self::Item) -> Ordering>(self, function: F) -> Self::Item {
393        let max = self.into_iter().max_by(function);
394
395        // SAFETY: the implementor guarantees the iterator is non-empty
396        // therefore, `max` has to contain some value
397        unsafe { max.unwrap_unchecked() }
398    }
399
400    /// Returns the maximum item of the non-empty iterator with respect to the key function.
401    ///
402    /// See also [`max_by_key`] on [`Iterator`].
403    ///
404    /// # Difference from [`Iterator`]
405    ///
406    /// Note that this function always returns some value, as the iterator is non-empty.
407    ///
408    /// [`max_by_key`]: Iterator::max_by_key
409    #[must_use]
410    fn max_by_key<K: Ord, F: FnMut(&Self::Item) -> K>(self, function: F) -> Self::Item {
411        let max = self.into_iter().max_by_key(function);
412
413        // SAFETY: the implementor guarantees the iterator is non-empty
414        // therefore, `max` has to contain some value
415        unsafe { max.unwrap_unchecked() }
416    }
417
418    /// Returns the minimum item of the non-empty iterator.
419    ///
420    /// See also [`min`] on [`Iterator`].
421    ///
422    /// # Difference from [`Iterator`]
423    ///
424    /// Note that this function always returns some value, as the iterator is non-empty.
425    ///
426    /// [`min`]: Iterator::min
427    #[must_use]
428    fn min(self) -> Self::Item
429    where
430        Self::Item: Ord,
431    {
432        let min = self.into_iter().min();
433
434        // SAFETY: the implementor guarantees the iterator is non-empty
435        // therefore, `min` has to contain some value
436        unsafe { min.unwrap_unchecked() }
437    }
438
439    /// Returns the minimum item of the non-empty iterator with respect to the comparison function.
440    ///
441    /// See also [`min_by`] on [`Iterator`].
442    ///
443    /// # Difference from [`Iterator`]
444    ///
445    /// Note that this function always returns some value, as the iterator is non-empty.
446    ///
447    /// [`min_by`]: Iterator::min_by
448    #[must_use]
449    fn min_by<F: FnMut(&Self::Item, &Self::Item) -> Ordering>(self, function: F) -> Self::Item {
450        let min = self.into_iter().min_by(function);
451
452        // SAFETY: the implementor guarantees the iterator is non-empty
453        // therefore, `min` has to contain some value
454        unsafe { min.unwrap_unchecked() }
455    }
456
457    /// Returns the minimum item of the non-empty iterator with respect to the key function.
458    ///
459    /// See also [`min_by_key`] on [`Iterator`].
460    ///
461    /// # Difference from [`Iterator`]
462    ///
463    /// Note that this function always returns some value, as the iterator is non-empty.
464    ///
465    /// [`min_by_key`]: Iterator::min_by_key
466    #[must_use]
467    fn min_by_key<K: Ord, F: FnMut(&Self::Item) -> K>(self, function: F) -> Self::Item {
468        let min = self.into_iter().min_by_key(function);
469
470        // SAFETY: the implementor guarantees the iterator is non-empty
471        // therefore, `min` has to contain some value
472        unsafe { min.unwrap_unchecked() }
473    }
474
475    /// Returns the `n`-th item of the non-empty iterator.
476    ///
477    /// See also [`nth`] on [`Iterator`].
478    ///
479    /// # Difference from [`Iterator`]
480    ///
481    /// Note that this function expects non-zero `n`, as the first item can be obtained
482    /// via [`consume`].
483    ///
484    /// [`nth`]: Iterator::nth
485    /// [`consume`]: NonEmptyIterator::consume
486    fn nth(self, n: Size) -> Option<Self::Item> {
487        self.into_iter().nth(n.get())
488    }
489
490    /// Skips the first given number of items in the non-empty iterator.
491    ///
492    /// See also [`skip`] on [`Iterator`].
493    ///
494    /// The returned iterator can be empty, depending on the count.
495    ///
496    /// # Difference from [`Iterator`]
497    ///
498    /// Note that this function expects non-zero count.
499    ///
500    /// [`skip`]: Iterator::skip
501    fn skip(self, count: Size) -> iter::Skip<Self::IntoIter> {
502        self.into_iter().skip(count.get())
503    }
504
505    /// Takes only the first given number of items from the non-empty iterator.
506    ///
507    /// See also [`take`] on [`Iterator`].
508    ///
509    /// # Difference from [`Iterator`]
510    ///
511    /// Note that this function expects non-zero count in order to guarantee non-emptiness.
512    ///
513    /// # Non-empty
514    ///
515    /// The returned iterator is guaranteed to be non-empty.
516    ///
517    /// [`take`]: Iterator::take
518    fn take(self, count: Size) -> Take<Self> {
519        Take::new(self, count)
520    }
521
522    /// Returns the last item of the non-empty iterator.
523    ///
524    /// See also [`last`] on [`Iterator`].
525    ///
526    /// # Difference from [`Iterator`]
527    ///
528    /// Note that this function always returns some value, as the iterator is non-empty.
529    ///
530    /// [`last`]: Iterator::last
531    #[must_use]
532    fn last(self) -> Self::Item {
533        let last = self.into_iter().last();
534
535        // SAFETY: the implementor guarantees the iterator is non-empty
536        // therefore, `last` has to contain some value
537        unsafe { last.unwrap_unchecked() }
538    }
539
540    /// Steps the non-empty iterator by the given custom amount.
541    ///
542    /// See also [`step_by`] on [`Iterator`].
543    ///
544    /// # Difference from [`Iterator`]
545    ///
546    /// Note that this function expects non-zero step as the [`step_by`] on [`Iterator`]
547    /// panics on zero.
548    ///
549    /// # Non-empty
550    ///
551    /// The returned iterator is guaranteed to be non-empty.
552    ///
553    /// [`step_by`]: Iterator::step_by
554    fn step_by(self, step: Size) -> StepBy<Self> {
555        StepBy::new(self, step)
556    }
557
558    /// Equivalent to [`for_each`] on [`Iterator`].
559    ///
560    /// [`for_each`]: Iterator::for_each
561    fn for_each<F: FnMut(Self::Item)>(self, function: F) {
562        self.into_iter().for_each(function);
563    }
564
565    /// Consumes the iterator, exhausting it by dropping all of its items.
566    ///
567    /// This is equivalent to calling [`for_each`] with [`drop`].
568    ///
569    /// [`for_each`]: NonEmptyIterator::for_each
570    fn exhaust(self) {
571        self.for_each(drop);
572    }
573
574    /// Equivalent to [`skip_while`] on [`Iterator`].
575    ///
576    /// Note that the returned iterator can be empty, depending on the predicate.
577    ///
578    /// [`skip_while`]: Iterator::skip_while
579    fn skip_while<P: FnMut(&Self::Item) -> bool>(
580        self,
581        predicate: P,
582    ) -> iter::SkipWhile<Self::IntoIter, P> {
583        self.into_iter().skip_while(predicate)
584    }
585
586    /// Equivalent to [`take_while`] on [`Iterator`].
587    ///
588    /// Note that the returned iterator can be empty, depending on the predicate.
589    ///
590    /// [`take_while`]: Iterator::take_while
591    fn take_while<P: FnMut(&Self::Item) -> bool>(
592        self,
593        predicate: P,
594    ) -> iter::TakeWhile<Self::IntoIter, P> {
595        self.into_iter().take_while(predicate)
596    }
597
598    /// Equivalent to [`map_while`] on [`Iterator`].
599    ///
600    /// Note that the returned iterator can be empty, depending on the predicate.
601    ///
602    /// [`map_while`]: Iterator::map_while
603    fn map_while<T, P: FnMut(Self::Item) -> Option<T>>(
604        self,
605        predicate: P,
606    ) -> iter::MapWhile<Self::IntoIter, P> {
607        self.into_iter().map_while(predicate)
608    }
609
610    /// Equivalent to [`scan`] on [`Iterator`].
611    ///
612    /// Note that the returned iterator can be empty, depending on the function.
613    ///
614    /// [`scan`]: Iterator::scan
615    fn scan<S, T, F: FnMut(&mut S, Self::Item) -> Option<T>>(
616        self,
617        initial: S,
618        function: F,
619    ) -> iter::Scan<Self::IntoIter, S, F> {
620        self.into_iter().scan(initial, function)
621    }
622
623    /// Creates non-empty iterators that call the provided function with references to each item.
624    ///
625    /// See also [`inspect`] on [`Iterator`].
626    ///
627    /// # Non-empty
628    ///
629    /// The returned iterator is guaranteed to be non-empty.
630    ///
631    /// [`inspect`]: Iterator::inspect
632    fn inspect<F: FnMut(&Self::Item)>(self, function: F) -> Inspect<Self, F> {
633        Inspect::new(self, function)
634    }
635
636    /// Equivalent to [`partition`] on [`Iterator`].
637    ///
638    /// [`partition`]: Iterator::partition
639    fn partition<C: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool>(
640        self,
641        function: F,
642    ) -> (C, C) {
643        self.into_iter().partition(function)
644    }
645
646    /// Equivalent to [`position`] on [`Iterator`].
647    ///
648    /// [`position`]: Iterator::position
649    fn position<P: FnMut(Self::Item) -> bool>(self, predicate: P) -> Option<usize> {
650        self.into_iter().position(predicate)
651    }
652
653    /// Equivalent to [`cmp`] on [`Iterator`].
654    ///
655    /// [`cmp`]: Iterator::cmp
656    fn cmp<I: IntoIterator<Item = Self::Item>>(self, other: I) -> Ordering
657    where
658        Self::Item: Ord,
659    {
660        self.into_iter().cmp(other)
661    }
662
663    /// Equivalent to [`partial_cmp`] on [`Iterator`].
664    ///
665    /// [`partial_cmp`]: Iterator::partial_cmp
666    fn partial_cmp<I: IntoIterator>(self, other: I) -> Option<Ordering>
667    where
668        Self::Item: PartialOrd<I::Item>,
669    {
670        self.into_iter().partial_cmp(other)
671    }
672
673    /// Equivalent to [`eq`] on [`Iterator`].
674    ///
675    /// [`eq`]: Iterator::eq
676    fn eq<I: IntoIterator>(self, other: I) -> bool
677    where
678        Self::Item: PartialEq<I::Item>,
679    {
680        self.into_iter().eq(other)
681    }
682
683    /// Equivalent to [`ne`] on [`Iterator`].
684    ///
685    /// [`ne`]: Iterator::ne
686    fn ne<I: IntoIterator>(self, other: I) -> bool
687    where
688        Self::Item: PartialEq<I::Item>,
689    {
690        self.into_iter().ne(other)
691    }
692
693    /// Equivalent to [`lt`] on [`Iterator`].
694    ///
695    /// [`lt`]: Iterator::lt
696    fn lt<I: IntoIterator>(self, other: I) -> bool
697    where
698        Self::Item: PartialOrd<I::Item>,
699    {
700        self.into_iter().lt(other)
701    }
702
703    /// Equivalent to [`le`] on [`Iterator`].
704    ///
705    /// [`le`]: Iterator::le
706    fn le<I: IntoIterator>(self, other: I) -> bool
707    where
708        Self::Item: PartialOrd<I::Item>,
709    {
710        self.into_iter().le(other)
711    }
712
713    /// Equivalent to [`gt`] on [`Iterator`].
714    ///
715    /// [`gt`]: Iterator::gt
716    fn gt<I: IntoIterator>(self, other: I) -> bool
717    where
718        Self::Item: PartialOrd<I::Item>,
719    {
720        self.into_iter().gt(other)
721    }
722
723    /// Equivalent to [`ge`] on [`Iterator`].
724    ///
725    /// [`ge`]: Iterator::ge
726    fn ge<I: IntoIterator>(self, other: I) -> bool
727    where
728        Self::Item: PartialOrd<I::Item>,
729    {
730        self.into_iter().ge(other)
731    }
732
733    /// Equivalent to [`is_sorted`] on [`Iterator`].
734    ///
735    /// [`is_sorted`]: Iterator::is_sorted
736    #[allow(clippy::wrong_self_convention)]
737    fn is_sorted(self) -> bool
738    where
739        Self::Item: PartialOrd,
740    {
741        self.into_iter().is_sorted()
742    }
743
744    /// Equivalent to [`is_sorted_by`] on [`Iterator`].
745    ///
746    /// [`is_sorted_by`]: Iterator::is_sorted_by
747    #[allow(clippy::wrong_self_convention)]
748    fn is_sorted_by<F: FnMut(&Self::Item, &Self::Item) -> bool>(self, function: F) -> bool {
749        self.into_iter().is_sorted_by(function)
750    }
751
752    /// Equivalent to [`is_sorted_by_key`] on [`Iterator`].
753    ///
754    /// [`is_sorted_by_key`]: Iterator::is_sorted_by_key
755    #[allow(clippy::wrong_self_convention)]
756    fn is_sorted_by_key<K: PartialOrd, F: FnMut(Self::Item) -> K>(self, function: F) -> bool {
757        self.into_iter().is_sorted_by_key(function)
758    }
759
760    /// Similar to [`collect`], but extends the provided collection instead of creating new ones.
761    ///
762    /// Returns the provided collection after extending.
763    ///
764    /// [`collect`]: NonEmptyIterator::collect
765    fn collect_into<C: Extend<Self::Item>>(self, collection: &mut C) -> &mut C {
766        collection.extend(self);
767
768        collection
769    }
770
771    /// Equivalent to [`find_map`] on [`Iterator`].
772    ///
773    /// [`find_map`]: Iterator::find_map
774    fn find_map<T, F: FnMut(Self::Item) -> Option<T>>(self, function: F) -> Option<T> {
775        self.into_iter().find_map(function)
776    }
777
778    /// Fuses the non-empty iterator, ensuring that once it returns [`None`],
779    /// it will return [`None`] forever afterwards.
780    ///
781    /// See also [`fuse`] on [`Iterator`].
782    ///
783    /// # Non-empty
784    ///
785    /// The returned iterator is guaranteed to be non-empty.
786    ///
787    /// [`fuse`]: Iterator::fuse
788    fn fuse(self) -> Fuse<Self> {
789        Fuse::new(self)
790    }
791
792    /// Reverses the iteration in non-empty iterators.
793    ///
794    /// See also [`rev`] on [`Iterator`].
795    ///
796    /// # Non-empty
797    ///
798    /// The returned iterator is guaranteed to be non-empty.
799    ///
800    /// [`rev`]: Iterator::rev
801    fn rev(self) -> Rev<Self>
802    where
803        Self::IntoIter: DoubleEndedIterator,
804    {
805        Rev::new(self)
806    }
807
808    /// Repeats the non-empty iterator endlessly.
809    ///
810    /// See also [`cycle`] on [`Iterator`].
811    ///
812    /// # Non-empty
813    ///
814    /// The returned iterator is guaranteed to be non-empty.
815    ///
816    /// [`cycle`]: Iterator::cycle
817    fn cycle(self) -> Cycle<Self>
818    where
819        Self::IntoIter: Clone,
820    {
821        Cycle::new(self)
822    }
823}
824
825/// Represents types that can be created from non-empty iterators.
826///
827/// This is similar to [`FromIterator`], but specifically for non-empty iterators.
828pub trait FromNonEmptyIterator<T>: Sized {
829    /// Creates [`Self`] from the provided non-empty iterator.
830    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = T>>(iterable: I) -> Self;
831}
832
833/// Represents types that can be converted into non-empty iterators.
834///
835/// This is similar to [`IntoIterator`], but specifically for non-empty iterators.
836///
837/// Any [`NonEmptyIterator`] is also [`IntoNonEmptyIterator`], akin to how any [`Iterator`]
838/// is also [`IntoIterator`].
839pub trait IntoNonEmptyIterator: IntoIterator {
840    /// What kind of [`NonEmptyIterator`] are we turning this into?
841    type IntoNonEmptyIter: NonEmptyIterator<Item = Self::Item>;
842
843    /// Converts `self` into [`NonEmptyIterator`].
844    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter;
845}
846
847impl<I: NonEmptyIterator> IntoNonEmptyIterator for I {
848    type IntoNonEmptyIter = Self;
849
850    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
851        self
852    }
853}
854
855mod sealed {
856    pub trait Sealed {}
857}
858
859/// Convenience trait implemented for any type that is [`IntoIterator`],
860/// allowing to convert iterables into non-empty ones.
861pub trait TryIntoNonEmptyIterator: sealed::Sealed {
862    /// The type of the items being iterated over.
863    type Item;
864
865    /// Which kind of [`NonEmptyIterator`] are we turning this into?
866    type IntoNonEmptyIter: NonEmptyIterator<Item = Self::Item>;
867
868    /// Tries to convert `self` into [`NonEmptyIterator`].
869    ///
870    /// Returns [`None`] if `self` is empty and therefore can not be converted.
871    fn try_into_non_empty_iter(self) -> Option<Self::IntoNonEmptyIter>;
872}
873
874impl<I: IntoIterator> sealed::Sealed for I {}
875
876impl<I: IntoIterator> TryIntoNonEmptyIterator for I {
877    type Item = I::Item;
878
879    type IntoNonEmptyIter = NonEmptyAdapter<iter::Peekable<I::IntoIter>>;
880
881    fn try_into_non_empty_iter(self) -> Option<Self::IntoNonEmptyIter> {
882        let mut peekable = self.into_iter().peekable();
883
884        peekable.peek()?;
885
886        // SAFETY: `peekable` is non-empty if we reached here
887        Some(unsafe { NonEmptyAdapter::new(peekable) })
888    }
889}