Skip to main content

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