4 use crate::ops::{Add, AddAssign, Try};
7 use super::{from_fn, LoopState};
8 use super::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, TrustedLen};
14 pub use self::chain::Chain;
15 #[stable(feature = "rust1", since = "1.0.0")]
16 pub use self::flatten::{FlatMap, Flatten};
17 pub(crate) use self::zip::TrustedRandomAccess;
18 pub use self::zip::Zip;
20 /// A double-ended iterator with the direction inverted.
22 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
23 /// documentation for more.
25 /// [`rev`]: trait.Iterator.html#method.rev
26 /// [`Iterator`]: trait.Iterator.html
27 #[derive(Clone, Debug)]
28 #[must_use = "iterators are lazy and do nothing unless consumed"]
29 #[stable(feature = "rust1", since = "1.0.0")]
34 pub(super) fn new(iter: T) -> Rev<T> {
39 #[stable(feature = "rust1", since = "1.0.0")]
40 impl<I> Iterator for Rev<I>
42 I: DoubleEndedIterator,
44 type Item = <I as Iterator>::Item;
47 fn next(&mut self) -> Option<<I as Iterator>::Item> {
51 fn size_hint(&self) -> (usize, Option<usize>) {
56 fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
60 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
63 F: FnMut(B, Self::Item) -> R,
66 self.iter.try_rfold(init, f)
69 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
71 F: FnMut(Acc, Self::Item) -> Acc,
73 self.iter.rfold(init, f)
77 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
79 P: FnMut(&Self::Item) -> bool,
81 self.iter.rfind(predicate)
85 #[stable(feature = "rust1", since = "1.0.0")]
86 impl<I> DoubleEndedIterator for Rev<I>
88 I: DoubleEndedIterator,
91 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
96 fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
100 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
103 F: FnMut(B, Self::Item) -> R,
106 self.iter.try_fold(init, f)
109 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
111 F: FnMut(Acc, Self::Item) -> Acc,
113 self.iter.fold(init, f)
116 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
118 P: FnMut(&Self::Item) -> bool,
120 self.iter.find(predicate)
124 #[stable(feature = "rust1", since = "1.0.0")]
125 impl<I> ExactSizeIterator for Rev<I>
127 I: ExactSizeIterator + DoubleEndedIterator,
129 fn len(&self) -> usize {
133 fn is_empty(&self) -> bool {
138 #[stable(feature = "fused", since = "1.26.0")]
139 impl<I> FusedIterator for Rev<I> where I: FusedIterator + DoubleEndedIterator {}
141 #[unstable(feature = "trusted_len", issue = "37572")]
142 unsafe impl<I> TrustedLen for Rev<I> where I: TrustedLen + DoubleEndedIterator {}
144 /// An iterator that copies the elements of an underlying iterator.
146 /// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
147 /// documentation for more.
149 /// [`copied`]: trait.Iterator.html#method.copied
150 /// [`Iterator`]: trait.Iterator.html
151 #[stable(feature = "iter_copied", since = "1.36.0")]
152 #[must_use = "iterators are lazy and do nothing unless consumed"]
153 #[derive(Clone, Debug)]
154 pub struct Copied<I> {
159 pub(super) fn new(it: I) -> Copied<I> {
164 fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
165 move |acc, &elt| f(acc, elt)
168 fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
169 move |acc, &elt| f(acc, elt)
172 #[stable(feature = "iter_copied", since = "1.36.0")]
173 impl<'a, I, T: 'a> Iterator for Copied<I>
175 I: Iterator<Item = &'a T>,
180 fn next(&mut self) -> Option<T> {
181 self.it.next().copied()
184 fn size_hint(&self) -> (usize, Option<usize>) {
188 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
191 F: FnMut(B, Self::Item) -> R,
194 self.it.try_fold(init, copy_try_fold(f))
197 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
199 F: FnMut(Acc, Self::Item) -> Acc,
201 self.it.fold(init, copy_fold(f))
204 fn nth(&mut self, n: usize) -> Option<T> {
205 self.it.nth(n).copied()
208 fn last(self) -> Option<T> {
209 self.it.last().copied()
212 fn count(self) -> usize {
217 #[stable(feature = "iter_copied", since = "1.36.0")]
218 impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
220 I: DoubleEndedIterator<Item = &'a T>,
223 fn next_back(&mut self) -> Option<T> {
224 self.it.next_back().copied()
227 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
230 F: FnMut(B, Self::Item) -> R,
233 self.it.try_rfold(init, copy_try_fold(f))
236 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
238 F: FnMut(Acc, Self::Item) -> Acc,
240 self.it.rfold(init, copy_fold(f))
244 #[stable(feature = "iter_copied", since = "1.36.0")]
245 impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
247 I: ExactSizeIterator<Item = &'a T>,
250 fn len(&self) -> usize {
254 fn is_empty(&self) -> bool {
259 #[stable(feature = "iter_copied", since = "1.36.0")]
260 impl<'a, I, T: 'a> FusedIterator for Copied<I>
262 I: FusedIterator<Item = &'a T>,
268 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Copied<I>
270 I: TrustedRandomAccess<Item = &'a T>,
273 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
274 *self.it.get_unchecked(i)
278 fn may_have_side_effect() -> bool {
279 I::may_have_side_effect()
283 #[stable(feature = "iter_copied", since = "1.36.0")]
284 unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
286 I: TrustedLen<Item = &'a T>,
291 /// An iterator that clones the elements of an underlying iterator.
293 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
294 /// documentation for more.
296 /// [`cloned`]: trait.Iterator.html#method.cloned
297 /// [`Iterator`]: trait.Iterator.html
298 #[stable(feature = "iter_cloned", since = "1.1.0")]
299 #[must_use = "iterators are lazy and do nothing unless consumed"]
300 #[derive(Clone, Debug)]
301 pub struct Cloned<I> {
305 pub(super) fn new(it: I) -> Cloned<I> {
310 fn clone_try_fold<T: Clone, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
311 move |acc, elt| f(acc, elt.clone())
314 #[stable(feature = "iter_cloned", since = "1.1.0")]
315 impl<'a, I, T: 'a> Iterator for Cloned<I>
317 I: Iterator<Item = &'a T>,
322 fn next(&mut self) -> Option<T> {
323 self.it.next().cloned()
326 fn size_hint(&self) -> (usize, Option<usize>) {
330 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
333 F: FnMut(B, Self::Item) -> R,
336 self.it.try_fold(init, clone_try_fold(f))
339 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
341 F: FnMut(Acc, Self::Item) -> Acc,
343 self.it.map(T::clone).fold(init, f)
347 #[stable(feature = "iter_cloned", since = "1.1.0")]
348 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
350 I: DoubleEndedIterator<Item = &'a T>,
353 fn next_back(&mut self) -> Option<T> {
354 self.it.next_back().cloned()
357 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
360 F: FnMut(B, Self::Item) -> R,
363 self.it.try_rfold(init, clone_try_fold(f))
366 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
368 F: FnMut(Acc, Self::Item) -> Acc,
370 self.it.map(T::clone).rfold(init, f)
374 #[stable(feature = "iter_cloned", since = "1.1.0")]
375 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
377 I: ExactSizeIterator<Item = &'a T>,
380 fn len(&self) -> usize {
384 fn is_empty(&self) -> bool {
389 #[stable(feature = "fused", since = "1.26.0")]
390 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
392 I: FusedIterator<Item = &'a T>,
398 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
400 I: TrustedRandomAccess<Item = &'a T>,
403 default unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
404 self.it.get_unchecked(i).clone()
408 default fn may_have_side_effect() -> bool {
414 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
416 I: TrustedRandomAccess<Item = &'a T>,
419 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
420 *self.it.get_unchecked(i)
424 fn may_have_side_effect() -> bool {
425 I::may_have_side_effect()
429 #[unstable(feature = "trusted_len", issue = "37572")]
430 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
432 I: TrustedLen<Item = &'a T>,
437 /// An iterator that repeats endlessly.
439 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
440 /// documentation for more.
442 /// [`cycle`]: trait.Iterator.html#method.cycle
443 /// [`Iterator`]: trait.Iterator.html
444 #[derive(Clone, Debug)]
445 #[must_use = "iterators are lazy and do nothing unless consumed"]
446 #[stable(feature = "rust1", since = "1.0.0")]
447 pub struct Cycle<I> {
451 impl<I: Clone> Cycle<I> {
452 pub(super) fn new(iter: I) -> Cycle<I> {
453 Cycle { orig: iter.clone(), iter }
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl<I> Iterator for Cycle<I>
462 type Item = <I as Iterator>::Item;
465 fn next(&mut self) -> Option<<I as Iterator>::Item> {
466 match self.iter.next() {
468 self.iter = self.orig.clone();
476 fn size_hint(&self) -> (usize, Option<usize>) {
477 // the cycle iterator is either empty or infinite
478 match self.orig.size_hint() {
479 sz @ (0, Some(0)) => sz,
481 _ => (usize::MAX, None),
486 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
488 F: FnMut(Acc, Self::Item) -> R,
491 // fully iterate the current iterator. this is necessary because
492 // `self.iter` may be empty even when `self.orig` isn't
493 acc = self.iter.try_fold(acc, &mut f)?;
494 self.iter = self.orig.clone();
496 // complete a full cycle, keeping track of whether the cycled
497 // iterator is empty or not. we need to return early in case
498 // of an empty iterator to prevent an infinite loop
499 let mut is_empty = true;
500 acc = self.iter.try_fold(acc, |acc, x| {
506 return Try::from_ok(acc);
510 self.iter = self.orig.clone();
511 acc = self.iter.try_fold(acc, &mut f)?;
516 #[stable(feature = "fused", since = "1.26.0")]
517 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
519 /// An iterator for stepping iterators by a custom amount.
521 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
522 /// its documentation for more.
524 /// [`step_by`]: trait.Iterator.html#method.step_by
525 /// [`Iterator`]: trait.Iterator.html
526 #[must_use = "iterators are lazy and do nothing unless consumed"]
527 #[stable(feature = "iterator_step_by", since = "1.28.0")]
528 #[derive(Clone, Debug)]
529 pub struct StepBy<I> {
535 pub(super) fn new(iter: I, step: usize) -> StepBy<I> {
537 StepBy { iter, step: step - 1, first_take: true }
541 #[stable(feature = "iterator_step_by", since = "1.28.0")]
542 impl<I> Iterator for StepBy<I>
549 fn next(&mut self) -> Option<Self::Item> {
551 self.first_take = false;
554 self.iter.nth(self.step)
559 fn size_hint(&self) -> (usize, Option<usize>) {
561 fn first_size(step: usize) -> impl Fn(usize) -> usize {
562 move |n| if n == 0 { 0 } else { 1 + (n - 1) / (step + 1) }
566 fn other_size(step: usize) -> impl Fn(usize) -> usize {
567 move |n| n / (step + 1)
570 let (low, high) = self.iter.size_hint();
573 let f = first_size(self.step);
574 (f(low), high.map(f))
576 let f = other_size(self.step);
577 (f(low), high.map(f))
582 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
584 self.first_take = false;
585 let first = self.iter.next();
591 // n and self.step are indices, we need to add 1 to get the amount of elements
592 // When calling `.nth`, we need to subtract 1 again to convert back to an index
593 // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
594 let mut step = self.step + 1;
595 // n + 1 could overflow
596 // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
598 self.iter.nth(step - 1);
605 let mul = n.checked_mul(step);
607 if intrinsics::likely(mul.is_some()) {
608 return self.iter.nth(mul.unwrap() - 1);
611 let div_n = usize::MAX / n;
612 let div_step = usize::MAX / step;
613 let nth_n = div_n * n;
614 let nth_step = div_step * step;
615 let nth = if nth_n > nth_step {
622 self.iter.nth(nth - 1);
626 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
628 F: FnMut(Acc, Self::Item) -> R,
632 fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
633 move || iter.nth(step)
637 self.first_take = false;
638 match self.iter.next() {
639 None => return Try::from_ok(acc),
640 Some(x) => acc = f(acc, x)?,
643 from_fn(nth(&mut self.iter, self.step)).try_fold(acc, f)
649 I: ExactSizeIterator,
651 // The zero-based index starting from the end of the iterator of the
652 // last element. Used in the `DoubleEndedIterator` implementation.
653 fn next_back_index(&self) -> usize {
654 let rem = self.iter.len() % (self.step + 1);
656 if rem == 0 { self.step } else { rem - 1 }
663 #[stable(feature = "double_ended_step_by_iterator", since = "1.38.0")]
664 impl<I> DoubleEndedIterator for StepBy<I>
666 I: DoubleEndedIterator + ExactSizeIterator,
669 fn next_back(&mut self) -> Option<Self::Item> {
670 self.iter.nth_back(self.next_back_index())
674 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
675 // `self.iter.nth_back(usize::MAX)` does the right thing here when `n`
676 // is out of bounds because the length of `self.iter` does not exceed
677 // `usize::MAX` (because `I: ExactSizeIterator`) and `nth_back` is
679 let n = n.saturating_mul(self.step + 1).saturating_add(self.next_back_index());
680 self.iter.nth_back(n)
683 fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R
685 F: FnMut(Acc, Self::Item) -> R,
689 fn nth_back<I: DoubleEndedIterator>(
692 ) -> impl FnMut() -> Option<I::Item> + '_ {
693 move || iter.nth_back(step)
696 match self.next_back() {
697 None => Try::from_ok(init),
699 let acc = f(init, x)?;
700 from_fn(nth_back(&mut self.iter, self.step)).try_fold(acc, f)
706 // StepBy can only make the iterator shorter, so the len will still fit.
707 #[stable(feature = "iterator_step_by", since = "1.28.0")]
708 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
710 /// An iterator that maps the values of `iter` with `f`.
712 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
713 /// documentation for more.
715 /// [`map`]: trait.Iterator.html#method.map
716 /// [`Iterator`]: trait.Iterator.html
718 /// # Notes about side effects
720 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
721 /// you can also [`map`] backwards:
724 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
726 /// assert_eq!(v, [4, 3, 2]);
729 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
731 /// But if your closure has state, iterating backwards may act in a way you do
732 /// not expect. Let's go through an example. First, in the forward direction:
737 /// for pair in vec!['a', 'b', 'c'].into_iter()
738 /// .map(|letter| { c += 1; (letter, c) }) {
739 /// println!("{:?}", pair);
743 /// This will print "('a', 1), ('b', 2), ('c', 3)".
745 /// Now consider this twist where we add a call to `rev`. This version will
746 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
747 /// but the values of the counter still go in order. This is because `map()` is
748 /// still being called lazily on each item, but we are popping items off the
749 /// back of the vector now, instead of shifting them from the front.
754 /// for pair in vec!['a', 'b', 'c'].into_iter()
755 /// .map(|letter| { c += 1; (letter, c) })
757 /// println!("{:?}", pair);
760 #[must_use = "iterators are lazy and do nothing unless consumed"]
761 #[stable(feature = "rust1", since = "1.0.0")]
763 pub struct Map<I, F> {
767 impl<I, F> Map<I, F> {
768 pub(super) fn new(iter: I, f: F) -> Map<I, F> {
773 #[stable(feature = "core_impl_debug", since = "1.9.0")]
774 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776 f.debug_struct("Map").field("iter", &self.iter).finish()
780 fn map_fold<T, B, Acc>(
781 mut f: impl FnMut(T) -> B,
782 mut g: impl FnMut(Acc, B) -> Acc,
783 ) -> impl FnMut(Acc, T) -> Acc {
784 move |acc, elt| g(acc, f(elt))
787 fn map_try_fold<'a, T, B, Acc, R>(
788 f: &'a mut impl FnMut(T) -> B,
789 mut g: impl FnMut(Acc, B) -> R + 'a,
790 ) -> impl FnMut(Acc, T) -> R + 'a {
791 move |acc, elt| g(acc, f(elt))
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<B, I: Iterator, F> Iterator for Map<I, F>
797 F: FnMut(I::Item) -> B,
802 fn next(&mut self) -> Option<B> {
803 self.iter.next().map(&mut self.f)
807 fn size_hint(&self) -> (usize, Option<usize>) {
808 self.iter.size_hint()
811 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
814 G: FnMut(Acc, Self::Item) -> R,
817 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
820 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
822 G: FnMut(Acc, Self::Item) -> Acc,
824 self.iter.fold(init, map_fold(self.f, g))
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
831 F: FnMut(I::Item) -> B,
834 fn next_back(&mut self) -> Option<B> {
835 self.iter.next_back().map(&mut self.f)
838 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
841 G: FnMut(Acc, Self::Item) -> R,
844 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
847 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
849 G: FnMut(Acc, Self::Item) -> Acc,
851 self.iter.rfold(init, map_fold(self.f, g))
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
858 F: FnMut(I::Item) -> B,
860 fn len(&self) -> usize {
864 fn is_empty(&self) -> bool {
869 #[stable(feature = "fused", since = "1.26.0")]
870 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
872 #[unstable(feature = "trusted_len", issue = "37572")]
873 unsafe impl<B, I, F> TrustedLen for Map<I, F>
876 F: FnMut(I::Item) -> B,
881 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
883 I: TrustedRandomAccess,
884 F: FnMut(I::Item) -> B,
886 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
887 (self.f)(self.iter.get_unchecked(i))
890 fn may_have_side_effect() -> bool {
895 /// An iterator that filters the elements of `iter` with `predicate`.
897 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
898 /// documentation for more.
900 /// [`filter`]: trait.Iterator.html#method.filter
901 /// [`Iterator`]: trait.Iterator.html
902 #[must_use = "iterators are lazy and do nothing unless consumed"]
903 #[stable(feature = "rust1", since = "1.0.0")]
905 pub struct Filter<I, P> {
909 impl<I, P> Filter<I, P> {
910 pub(super) fn new(iter: I, predicate: P) -> Filter<I, P> {
911 Filter { iter, predicate }
915 #[stable(feature = "core_impl_debug", since = "1.9.0")]
916 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
918 f.debug_struct("Filter").field("iter", &self.iter).finish()
922 fn filter_fold<T, Acc>(
923 mut predicate: impl FnMut(&T) -> bool,
924 mut fold: impl FnMut(Acc, T) -> Acc,
925 ) -> impl FnMut(Acc, T) -> Acc {
926 move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
929 fn filter_try_fold<'a, T, Acc, R: Try<Ok = Acc>>(
930 predicate: &'a mut impl FnMut(&T) -> bool,
931 mut fold: impl FnMut(Acc, T) -> R + 'a,
932 ) -> impl FnMut(Acc, T) -> R + 'a {
933 move |acc, item| if predicate(&item) { fold(acc, item) } else { R::from_ok(acc) }
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<I: Iterator, P> Iterator for Filter<I, P>
939 P: FnMut(&I::Item) -> bool,
944 fn next(&mut self) -> Option<I::Item> {
945 self.iter.find(&mut self.predicate)
949 fn size_hint(&self) -> (usize, Option<usize>) {
950 let (_, upper) = self.iter.size_hint();
951 (0, upper) // can't know a lower bound, due to the predicate
954 // this special case allows the compiler to make `.filter(_).count()`
955 // branchless. Barring perfect branch prediction (which is unattainable in
956 // the general case), this will be much faster in >90% of cases (containing
957 // virtually all real workloads) and only a tiny bit slower in the rest.
959 // Having this specialization thus allows us to write `.filter(p).count()`
960 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
961 // less readable and also less backwards-compatible to Rust before 1.10.
963 // Using the branchless version will also simplify the LLVM byte code, thus
964 // leaving more budget for LLVM optimizations.
966 fn count(self) -> usize {
968 fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
969 move |x| predicate(&x) as usize
972 self.iter.map(to_usize(self.predicate)).sum()
976 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
979 Fold: FnMut(Acc, Self::Item) -> R,
982 self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
986 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
988 Fold: FnMut(Acc, Self::Item) -> Acc,
990 self.iter.fold(init, filter_fold(self.predicate, fold))
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
997 P: FnMut(&I::Item) -> bool,
1000 fn next_back(&mut self) -> Option<I::Item> {
1001 self.iter.rfind(&mut self.predicate)
1005 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1008 Fold: FnMut(Acc, Self::Item) -> R,
1011 self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
1015 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1017 Fold: FnMut(Acc, Self::Item) -> Acc,
1019 self.iter.rfold(init, filter_fold(self.predicate, fold))
1023 #[stable(feature = "fused", since = "1.26.0")]
1024 impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1026 /// An iterator that uses `f` to both filter and map elements from `iter`.
1028 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1029 /// documentation for more.
1031 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1032 /// [`Iterator`]: trait.Iterator.html
1033 #[must_use = "iterators are lazy and do nothing unless consumed"]
1034 #[stable(feature = "rust1", since = "1.0.0")]
1036 pub struct FilterMap<I, F> {
1040 impl<I, F> FilterMap<I, F> {
1041 pub(super) fn new(iter: I, f: F) -> FilterMap<I, F> {
1042 FilterMap { iter, f }
1046 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1047 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049 f.debug_struct("FilterMap").field("iter", &self.iter).finish()
1053 fn filter_map_fold<T, B, Acc>(
1054 mut f: impl FnMut(T) -> Option<B>,
1055 mut fold: impl FnMut(Acc, B) -> Acc,
1056 ) -> impl FnMut(Acc, T) -> Acc {
1057 move |acc, item| match f(item) {
1058 Some(x) => fold(acc, x),
1063 fn filter_map_try_fold<'a, T, B, Acc, R: Try<Ok = Acc>>(
1064 f: &'a mut impl FnMut(T) -> Option<B>,
1065 mut fold: impl FnMut(Acc, B) -> R + 'a,
1066 ) -> impl FnMut(Acc, T) -> R + 'a {
1067 move |acc, item| match f(item) {
1068 Some(x) => fold(acc, x),
1069 None => R::from_ok(acc),
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1076 F: FnMut(I::Item) -> Option<B>,
1081 fn next(&mut self) -> Option<B> {
1082 self.iter.find_map(&mut self.f)
1086 fn size_hint(&self) -> (usize, Option<usize>) {
1087 let (_, upper) = self.iter.size_hint();
1088 (0, upper) // can't know a lower bound, due to the predicate
1092 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1095 Fold: FnMut(Acc, Self::Item) -> R,
1098 self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold))
1102 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1104 Fold: FnMut(Acc, Self::Item) -> Acc,
1106 self.iter.fold(init, filter_map_fold(self.f, fold))
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1113 F: FnMut(I::Item) -> Option<B>,
1116 fn next_back(&mut self) -> Option<B> {
1119 f: &mut impl FnMut(T) -> Option<B>,
1120 ) -> impl FnMut((), T) -> LoopState<(), B> + '_ {
1121 move |(), x| match f(x) {
1122 Some(x) => LoopState::Break(x),
1123 None => LoopState::Continue(()),
1127 self.iter.try_rfold((), find(&mut self.f)).break_value()
1131 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1134 Fold: FnMut(Acc, Self::Item) -> R,
1137 self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold))
1141 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1143 Fold: FnMut(Acc, Self::Item) -> Acc,
1145 self.iter.rfold(init, filter_map_fold(self.f, fold))
1149 #[stable(feature = "fused", since = "1.26.0")]
1150 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F> where F: FnMut(I::Item) -> Option<B> {}
1152 /// An iterator that yields the current count and the element during iteration.
1154 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1155 /// documentation for more.
1157 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1158 /// [`Iterator`]: trait.Iterator.html
1159 #[derive(Clone, Debug)]
1160 #[must_use = "iterators are lazy and do nothing unless consumed"]
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub struct Enumerate<I> {
1166 impl<I> Enumerate<I> {
1167 pub(super) fn new(iter: I) -> Enumerate<I> {
1168 Enumerate { iter, count: 0 }
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 impl<I> Iterator for Enumerate<I>
1177 type Item = (usize, <I as Iterator>::Item);
1179 /// # Overflow Behavior
1181 /// The method does no guarding against overflows, so enumerating more than
1182 /// `usize::MAX` elements either produces the wrong result or panics. If
1183 /// debug assertions are enabled, a panic is guaranteed.
1187 /// Might panic if the index of the element overflows a `usize`.
1189 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1190 let a = self.iter.next()?;
1192 // Possible undefined overflow.
1193 AddAssign::add_assign(&mut self.count, 1);
1198 fn size_hint(&self) -> (usize, Option<usize>) {
1199 self.iter.size_hint()
1203 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1204 let a = self.iter.nth(n)?;
1205 // Possible undefined overflow.
1206 let i = Add::add(self.count, n);
1207 self.count = Add::add(i, 1);
1212 fn count(self) -> usize {
1217 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1220 Fold: FnMut(Acc, Self::Item) -> R,
1224 fn enumerate<'a, T, Acc, R>(
1225 count: &'a mut usize,
1226 mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a,
1227 ) -> impl FnMut(Acc, T) -> R + 'a {
1229 let acc = fold(acc, (*count, item));
1230 // Possible undefined overflow.
1231 AddAssign::add_assign(count, 1);
1236 self.iter.try_fold(init, enumerate(&mut self.count, fold))
1240 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1242 Fold: FnMut(Acc, Self::Item) -> Acc,
1245 fn enumerate<T, Acc>(
1247 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1248 ) -> impl FnMut(Acc, T) -> Acc {
1250 let acc = fold(acc, (count, item));
1251 // Possible undefined overflow.
1252 AddAssign::add_assign(&mut count, 1);
1257 self.iter.fold(init, enumerate(self.count, fold))
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<I> DoubleEndedIterator for Enumerate<I>
1264 I: ExactSizeIterator + DoubleEndedIterator,
1267 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1268 let a = self.iter.next_back()?;
1269 let len = self.iter.len();
1270 // Can safely add, `ExactSizeIterator` promises that the number of
1271 // elements fits into a `usize`.
1272 Some((self.count + len, a))
1276 fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
1277 let a = self.iter.nth_back(n)?;
1278 let len = self.iter.len();
1279 // Can safely add, `ExactSizeIterator` promises that the number of
1280 // elements fits into a `usize`.
1281 Some((self.count + len, a))
1285 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1288 Fold: FnMut(Acc, Self::Item) -> R,
1291 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1292 // that the number of elements fits into a `usize`.
1293 fn enumerate<T, Acc, R>(
1295 mut fold: impl FnMut(Acc, (usize, T)) -> R,
1296 ) -> impl FnMut(Acc, T) -> R {
1299 fold(acc, (count, item))
1303 let count = self.count + self.iter.len();
1304 self.iter.try_rfold(init, enumerate(count, fold))
1308 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1310 Fold: FnMut(Acc, Self::Item) -> Acc,
1312 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1313 // that the number of elements fits into a `usize`.
1314 fn enumerate<T, Acc>(
1316 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1317 ) -> impl FnMut(Acc, T) -> Acc {
1320 fold(acc, (count, item))
1324 let count = self.count + self.iter.len();
1325 self.iter.rfold(init, enumerate(count, fold))
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 impl<I> ExactSizeIterator for Enumerate<I>
1332 I: ExactSizeIterator,
1334 fn len(&self) -> usize {
1338 fn is_empty(&self) -> bool {
1339 self.iter.is_empty()
1344 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1346 I: TrustedRandomAccess,
1348 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1349 (self.count + i, self.iter.get_unchecked(i))
1352 fn may_have_side_effect() -> bool {
1353 I::may_have_side_effect()
1357 #[stable(feature = "fused", since = "1.26.0")]
1358 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1360 #[unstable(feature = "trusted_len", issue = "37572")]
1361 unsafe impl<I> TrustedLen for Enumerate<I> where I: TrustedLen {}
1363 /// An iterator with a `peek()` that returns an optional reference to the next
1366 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1367 /// documentation for more.
1369 /// [`peekable`]: trait.Iterator.html#method.peekable
1370 /// [`Iterator`]: trait.Iterator.html
1371 #[derive(Clone, Debug)]
1372 #[must_use = "iterators are lazy and do nothing unless consumed"]
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub struct Peekable<I: Iterator> {
1376 /// Remember a peeked value, even if it was None.
1377 peeked: Option<Option<I::Item>>,
1379 impl<I: Iterator> Peekable<I> {
1380 pub(super) fn new(iter: I) -> Peekable<I> {
1381 Peekable { iter, peeked: None }
1385 // Peekable must remember if a None has been seen in the `.peek()` method.
1386 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1387 // underlying iterator at most once. This does not by itself make the iterator
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<I: Iterator> Iterator for Peekable<I> {
1391 type Item = I::Item;
1394 fn next(&mut self) -> Option<I::Item> {
1395 match self.peeked.take() {
1397 None => self.iter.next(),
1402 #[rustc_inherit_overflow_checks]
1403 fn count(mut self) -> usize {
1404 match self.peeked.take() {
1406 Some(Some(_)) => 1 + self.iter.count(),
1407 None => self.iter.count(),
1412 fn nth(&mut self, n: usize) -> Option<I::Item> {
1413 match self.peeked.take() {
1415 Some(v @ Some(_)) if n == 0 => v,
1416 Some(Some(_)) => self.iter.nth(n - 1),
1417 None => self.iter.nth(n),
1422 fn last(mut self) -> Option<I::Item> {
1423 let peek_opt = match self.peeked.take() {
1424 Some(None) => return None,
1428 self.iter.last().or(peek_opt)
1432 fn size_hint(&self) -> (usize, Option<usize>) {
1433 let peek_len = match self.peeked {
1434 Some(None) => return (0, Some(0)),
1438 let (lo, hi) = self.iter.size_hint();
1439 let lo = lo.saturating_add(peek_len);
1441 Some(x) => x.checked_add(peek_len),
1448 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1451 F: FnMut(B, Self::Item) -> R,
1454 let acc = match self.peeked.take() {
1455 Some(None) => return Try::from_ok(init),
1456 Some(Some(v)) => f(init, v)?,
1459 self.iter.try_fold(acc, f)
1463 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1465 Fold: FnMut(Acc, Self::Item) -> Acc,
1467 let acc = match self.peeked {
1468 Some(None) => return init,
1469 Some(Some(v)) => fold(init, v),
1472 self.iter.fold(acc, fold)
1476 #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
1477 impl<I> DoubleEndedIterator for Peekable<I>
1479 I: DoubleEndedIterator,
1482 fn next_back(&mut self) -> Option<Self::Item> {
1483 match self.peeked.as_mut() {
1484 Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
1486 None => self.iter.next_back(),
1491 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
1494 F: FnMut(B, Self::Item) -> R,
1497 match self.peeked.take() {
1498 Some(None) => Try::from_ok(init),
1499 Some(Some(v)) => match self.iter.try_rfold(init, &mut f).into_result() {
1500 Ok(acc) => f(acc, v),
1502 self.peeked = Some(Some(v));
1506 None => self.iter.try_rfold(init, f),
1511 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1513 Fold: FnMut(Acc, Self::Item) -> Acc,
1518 let acc = self.iter.rfold(init, &mut fold);
1521 None => self.iter.rfold(init, fold),
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1529 #[stable(feature = "fused", since = "1.26.0")]
1530 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1532 impl<I: Iterator> Peekable<I> {
1533 /// Returns a reference to the next() value without advancing the iterator.
1535 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1536 /// But if the iteration is over, `None` is returned.
1538 /// [`next`]: trait.Iterator.html#tymethod.next
1540 /// Because `peek()` returns a reference, and many iterators iterate over
1541 /// references, there can be a possibly confusing situation where the
1542 /// return value is a double reference. You can see this effect in the
1550 /// let xs = [1, 2, 3];
1552 /// let mut iter = xs.iter().peekable();
1554 /// // peek() lets us see into the future
1555 /// assert_eq!(iter.peek(), Some(&&1));
1556 /// assert_eq!(iter.next(), Some(&1));
1558 /// assert_eq!(iter.next(), Some(&2));
1560 /// // The iterator does not advance even if we `peek` multiple times
1561 /// assert_eq!(iter.peek(), Some(&&3));
1562 /// assert_eq!(iter.peek(), Some(&&3));
1564 /// assert_eq!(iter.next(), Some(&3));
1566 /// // After the iterator is finished, so is `peek()`
1567 /// assert_eq!(iter.peek(), None);
1568 /// assert_eq!(iter.next(), None);
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 pub fn peek(&mut self) -> Option<&I::Item> {
1573 let iter = &mut self.iter;
1574 self.peeked.get_or_insert_with(|| iter.next()).as_ref()
1578 /// An iterator that rejects elements while `predicate` returns `true`.
1580 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1581 /// documentation for more.
1583 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1584 /// [`Iterator`]: trait.Iterator.html
1585 #[must_use = "iterators are lazy and do nothing unless consumed"]
1586 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub struct SkipWhile<I, P> {
1593 impl<I, P> SkipWhile<I, P> {
1594 pub(super) fn new(iter: I, predicate: P) -> SkipWhile<I, P> {
1595 SkipWhile { iter, flag: false, predicate }
1599 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1600 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1602 f.debug_struct("SkipWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1609 P: FnMut(&I::Item) -> bool,
1611 type Item = I::Item;
1614 fn next(&mut self) -> Option<I::Item> {
1617 pred: &'a mut impl FnMut(&T) -> bool,
1618 ) -> impl FnMut(&T) -> bool + 'a {
1620 if *flag || !pred(x) {
1629 let flag = &mut self.flag;
1630 let pred = &mut self.predicate;
1631 self.iter.find(check(flag, pred))
1635 fn size_hint(&self) -> (usize, Option<usize>) {
1636 let (_, upper) = self.iter.size_hint();
1637 (0, upper) // can't know a lower bound, due to the predicate
1641 fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R
1644 Fold: FnMut(Acc, Self::Item) -> R,
1649 Some(v) => init = fold(init, v)?,
1650 None => return Try::from_ok(init),
1653 self.iter.try_fold(init, fold)
1657 fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
1659 Fold: FnMut(Acc, Self::Item) -> Acc,
1663 Some(v) => init = fold(init, v),
1664 None => return init,
1667 self.iter.fold(init, fold)
1671 #[stable(feature = "fused", since = "1.26.0")]
1672 impl<I, P> FusedIterator for SkipWhile<I, P>
1675 P: FnMut(&I::Item) -> bool,
1679 /// An iterator that only accepts elements while `predicate` returns `true`.
1681 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1682 /// documentation for more.
1684 /// [`take_while`]: trait.Iterator.html#method.take_while
1685 /// [`Iterator`]: trait.Iterator.html
1686 #[must_use = "iterators are lazy and do nothing unless consumed"]
1687 #[stable(feature = "rust1", since = "1.0.0")]
1689 pub struct TakeWhile<I, P> {
1694 impl<I, P> TakeWhile<I, P> {
1695 pub(super) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
1696 TakeWhile { iter, flag: false, predicate }
1700 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1701 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1703 f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1710 P: FnMut(&I::Item) -> bool,
1712 type Item = I::Item;
1715 fn next(&mut self) -> Option<I::Item> {
1719 let x = self.iter.next()?;
1720 if (self.predicate)(&x) {
1730 fn size_hint(&self) -> (usize, Option<usize>) {
1734 let (_, upper) = self.iter.size_hint();
1735 (0, upper) // can't know a lower bound, due to the predicate
1740 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1743 Fold: FnMut(Acc, Self::Item) -> R,
1746 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
1748 p: &'a mut impl FnMut(&T) -> bool,
1749 mut fold: impl FnMut(Acc, T) -> R + 'a,
1750 ) -> impl FnMut(Acc, T) -> LoopState<Acc, R> + 'a {
1753 LoopState::from_try(fold(acc, x))
1756 LoopState::Break(Try::from_ok(acc))
1764 let flag = &mut self.flag;
1765 let p = &mut self.predicate;
1766 self.iter.try_fold(init, check(flag, p, fold)).into_try()
1771 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
1773 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
1774 /// documentation for more.
1776 /// [`map_while`]: trait.Iterator.html#method.map_while
1777 /// [`Iterator`]: trait.Iterator.html
1778 #[must_use = "iterators are lazy and do nothing unless consumed"]
1779 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1781 pub struct MapWhile<I, P> {
1787 impl<I, P> MapWhile<I, P> {
1788 pub(super) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
1789 MapWhile { iter, finished: false, predicate }
1793 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1794 impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
1795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1796 f.debug_struct("MapWhile").field("iter", &self.iter).field("flag", &self.finished).finish()
1800 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1801 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
1803 P: FnMut(I::Item) -> Option<B>,
1808 fn next(&mut self) -> Option<B> {
1812 let x = self.iter.next()?;
1813 let ret = (self.predicate)(x);
1814 self.finished = ret.is_none();
1820 fn size_hint(&self) -> (usize, Option<usize>) {
1824 let (_, upper) = self.iter.size_hint();
1825 (0, upper) // can't know a lower bound, due to the predicate
1830 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1833 Fold: FnMut(Acc, Self::Item) -> R,
1836 fn check<'a, B, T, Acc, R: Try<Ok = Acc>>(
1838 p: &'a mut impl FnMut(T) -> Option<B>,
1839 mut fold: impl FnMut(Acc, B) -> R + 'a,
1840 ) -> impl FnMut(Acc, T) -> LoopState<Acc, R> + 'a {
1841 move |acc, x| match p(x) {
1842 Some(item) => LoopState::from_try(fold(acc, item)),
1845 LoopState::Break(Try::from_ok(acc))
1853 let flag = &mut self.finished;
1854 let p = &mut self.predicate;
1855 self.iter.try_fold(init, check(flag, p, fold)).into_try()
1860 #[stable(feature = "fused", since = "1.26.0")]
1861 impl<I, P> FusedIterator for TakeWhile<I, P>
1864 P: FnMut(&I::Item) -> bool,
1868 /// An iterator that skips over `n` elements of `iter`.
1870 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
1871 /// documentation for more.
1873 /// [`skip`]: trait.Iterator.html#method.skip
1874 /// [`Iterator`]: trait.Iterator.html
1875 #[derive(Clone, Debug)]
1876 #[must_use = "iterators are lazy and do nothing unless consumed"]
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 pub struct Skip<I> {
1883 pub(super) fn new(iter: I, n: usize) -> Skip<I> {
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<I> Iterator for Skip<I>
1893 type Item = <I as Iterator>::Item;
1896 fn next(&mut self) -> Option<I::Item> {
1902 self.iter.nth(old_n)
1907 fn nth(&mut self, n: usize) -> Option<I::Item> {
1908 // Can't just add n + self.n due to overflow.
1910 let to_skip = self.n;
1913 self.iter.nth(to_skip - 1)?;
1919 fn count(mut self) -> usize {
1922 if self.iter.nth(self.n - 1).is_none() {
1930 fn last(mut self) -> Option<I::Item> {
1933 self.iter.nth(self.n - 1)?;
1939 fn size_hint(&self) -> (usize, Option<usize>) {
1940 let (lower, upper) = self.iter.size_hint();
1942 let lower = lower.saturating_sub(self.n);
1943 let upper = match upper {
1944 Some(x) => Some(x.saturating_sub(self.n)),
1952 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1955 Fold: FnMut(Acc, Self::Item) -> R,
1962 if self.iter.nth(n - 1).is_none() {
1963 return Try::from_ok(init);
1966 self.iter.try_fold(init, fold)
1970 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
1972 Fold: FnMut(Acc, Self::Item) -> Acc,
1976 if self.iter.nth(self.n - 1).is_none() {
1980 self.iter.fold(init, fold)
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1987 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
1988 impl<I> DoubleEndedIterator for Skip<I>
1990 I: DoubleEndedIterator + ExactSizeIterator,
1992 fn next_back(&mut self) -> Option<Self::Item> {
1993 if self.len() > 0 { self.iter.next_back() } else { None }
1997 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1998 let len = self.len();
2000 self.iter.nth_back(n)
2003 // consume the original iterator
2004 self.iter.nth_back(len - 1);
2010 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2013 Fold: FnMut(Acc, Self::Item) -> R,
2016 fn check<T, Acc, R: Try<Ok = Acc>>(
2018 mut fold: impl FnMut(Acc, T) -> R,
2019 ) -> impl FnMut(Acc, T) -> LoopState<Acc, R> {
2022 let r = fold(acc, x);
2023 if n == 0 { LoopState::Break(r) } else { LoopState::from_try(r) }
2031 self.iter.try_rfold(init, check(n, fold)).into_try()
2036 #[stable(feature = "fused", since = "1.26.0")]
2037 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2039 /// An iterator that only iterates over the first `n` iterations of `iter`.
2041 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2042 /// documentation for more.
2044 /// [`take`]: trait.Iterator.html#method.take
2045 /// [`Iterator`]: trait.Iterator.html
2046 #[derive(Clone, Debug)]
2047 #[must_use = "iterators are lazy and do nothing unless consumed"]
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 pub struct Take<I> {
2051 pub(super) n: usize,
2054 pub(super) fn new(iter: I, n: usize) -> Take<I> {
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 impl<I> Iterator for Take<I>
2064 type Item = <I as Iterator>::Item;
2067 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2077 fn nth(&mut self, n: usize) -> Option<I::Item> {
2083 self.iter.nth(self.n - 1);
2091 fn size_hint(&self) -> (usize, Option<usize>) {
2093 return (0, Some(0));
2096 let (lower, upper) = self.iter.size_hint();
2098 let lower = cmp::min(lower, self.n);
2100 let upper = match upper {
2101 Some(x) if x < self.n => Some(x),
2109 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2112 Fold: FnMut(Acc, Self::Item) -> R,
2115 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2117 mut fold: impl FnMut(Acc, T) -> R + 'a,
2118 ) -> impl FnMut(Acc, T) -> LoopState<Acc, R> + 'a {
2121 let r = fold(acc, x);
2122 if *n == 0 { LoopState::Break(r) } else { LoopState::from_try(r) }
2129 let n = &mut self.n;
2130 self.iter.try_fold(init, check(n, fold)).into_try()
2135 #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
2136 impl<I> DoubleEndedIterator for Take<I>
2138 I: DoubleEndedIterator + ExactSizeIterator,
2141 fn next_back(&mut self) -> Option<Self::Item> {
2147 self.iter.nth_back(self.iter.len().saturating_sub(n))
2152 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2153 let len = self.iter.len();
2155 let m = len.saturating_sub(self.n) + n;
2157 self.iter.nth_back(m)
2160 self.iter.nth_back(len - 1);
2167 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2170 Fold: FnMut(Acc, Self::Item) -> R,
2176 let len = self.iter.len();
2177 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2180 self.iter.try_rfold(init, fold)
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2189 #[stable(feature = "fused", since = "1.26.0")]
2190 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2192 #[unstable(feature = "trusted_len", issue = "37572")]
2193 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2195 /// An iterator to maintain state while iterating another iterator.
2197 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2198 /// documentation for more.
2200 /// [`scan`]: trait.Iterator.html#method.scan
2201 /// [`Iterator`]: trait.Iterator.html
2202 #[must_use = "iterators are lazy and do nothing unless consumed"]
2203 #[stable(feature = "rust1", since = "1.0.0")]
2205 pub struct Scan<I, St, F> {
2210 impl<I, St, F> Scan<I, St, F> {
2211 pub(super) fn new(iter: I, state: St, f: F) -> Scan<I, St, F> {
2212 Scan { iter, state, f }
2216 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2217 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2219 f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish()
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 impl<B, I, St, F> Iterator for Scan<I, St, F>
2227 F: FnMut(&mut St, I::Item) -> Option<B>,
2232 fn next(&mut self) -> Option<B> {
2233 let a = self.iter.next()?;
2234 (self.f)(&mut self.state, a)
2238 fn size_hint(&self) -> (usize, Option<usize>) {
2239 let (_, upper) = self.iter.size_hint();
2240 (0, upper) // can't know a lower bound, due to the scan function
2244 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2247 Fold: FnMut(Acc, Self::Item) -> R,
2250 fn scan<'a, T, St, B, Acc, R: Try<Ok = Acc>>(
2252 f: &'a mut impl FnMut(&mut St, T) -> Option<B>,
2253 mut fold: impl FnMut(Acc, B) -> R + 'a,
2254 ) -> impl FnMut(Acc, T) -> LoopState<Acc, R> + 'a {
2255 move |acc, x| match f(state, x) {
2256 None => LoopState::Break(Try::from_ok(acc)),
2257 Some(x) => LoopState::from_try(fold(acc, x)),
2261 let state = &mut self.state;
2262 let f = &mut self.f;
2263 self.iter.try_fold(init, scan(state, f, fold)).into_try()
2267 /// An iterator that yields `None` forever after the underlying iterator
2268 /// yields `None` once.
2270 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
2271 /// documentation for more.
2273 /// [`fuse`]: trait.Iterator.html#method.fuse
2274 /// [`Iterator`]: trait.Iterator.html
2275 #[derive(Clone, Debug)]
2276 #[must_use = "iterators are lazy and do nothing unless consumed"]
2277 #[stable(feature = "rust1", since = "1.0.0")]
2278 pub struct Fuse<I> {
2283 pub(super) fn new(iter: I) -> Fuse<I> {
2284 Fuse { iter, done: false }
2288 #[stable(feature = "fused", since = "1.26.0")]
2289 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
2291 #[stable(feature = "rust1", since = "1.0.0")]
2292 impl<I> Iterator for Fuse<I>
2296 type Item = <I as Iterator>::Item;
2299 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
2303 let next = self.iter.next();
2304 self.done = next.is_none();
2310 default fn nth(&mut self, n: usize) -> Option<I::Item> {
2314 let nth = self.iter.nth(n);
2315 self.done = nth.is_none();
2321 default fn last(self) -> Option<I::Item> {
2322 if self.done { None } else { self.iter.last() }
2326 default fn count(self) -> usize {
2327 if self.done { 0 } else { self.iter.count() }
2331 default fn size_hint(&self) -> (usize, Option<usize>) {
2332 if self.done { (0, Some(0)) } else { self.iter.size_hint() }
2336 default fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2339 Fold: FnMut(Acc, Self::Item) -> R,
2345 let acc = self.iter.try_fold(init, fold)?;
2352 default fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2354 Fold: FnMut(Acc, Self::Item) -> Acc,
2356 if self.done { init } else { self.iter.fold(init, fold) }
2360 #[stable(feature = "rust1", since = "1.0.0")]
2361 impl<I> DoubleEndedIterator for Fuse<I>
2363 I: DoubleEndedIterator,
2366 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2370 let next = self.iter.next_back();
2371 self.done = next.is_none();
2377 default fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
2381 let nth = self.iter.nth_back(n);
2382 self.done = nth.is_none();
2388 default fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2391 Fold: FnMut(Acc, Self::Item) -> R,
2397 let acc = self.iter.try_rfold(init, fold)?;
2404 default fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2406 Fold: FnMut(Acc, Self::Item) -> Acc,
2408 if self.done { init } else { self.iter.rfold(init, fold) }
2412 unsafe impl<I> TrustedRandomAccess for Fuse<I>
2414 I: TrustedRandomAccess,
2416 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
2417 self.iter.get_unchecked(i)
2420 fn may_have_side_effect() -> bool {
2421 I::may_have_side_effect()
2425 #[stable(feature = "fused", since = "1.26.0")]
2426 impl<I> Iterator for Fuse<I>
2431 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2436 fn nth(&mut self, n: usize) -> Option<I::Item> {
2441 fn last(self) -> Option<I::Item> {
2446 fn count(self) -> usize {
2451 fn size_hint(&self) -> (usize, Option<usize>) {
2452 self.iter.size_hint()
2456 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2459 Fold: FnMut(Acc, Self::Item) -> R,
2462 self.iter.try_fold(init, fold)
2466 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2468 Fold: FnMut(Acc, Self::Item) -> Acc,
2470 self.iter.fold(init, fold)
2474 #[stable(feature = "fused", since = "1.26.0")]
2475 impl<I> DoubleEndedIterator for Fuse<I>
2477 I: DoubleEndedIterator + FusedIterator,
2480 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2481 self.iter.next_back()
2485 fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
2486 self.iter.nth_back(n)
2490 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2493 Fold: FnMut(Acc, Self::Item) -> R,
2496 self.iter.try_rfold(init, fold)
2500 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2502 Fold: FnMut(Acc, Self::Item) -> Acc,
2504 self.iter.rfold(init, fold)
2508 #[stable(feature = "rust1", since = "1.0.0")]
2509 impl<I> ExactSizeIterator for Fuse<I>
2511 I: ExactSizeIterator,
2513 fn len(&self) -> usize {
2517 fn is_empty(&self) -> bool {
2518 self.iter.is_empty()
2522 /// An iterator that calls a function with a reference to each element before
2525 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2526 /// documentation for more.
2528 /// [`inspect`]: trait.Iterator.html#method.inspect
2529 /// [`Iterator`]: trait.Iterator.html
2530 #[must_use = "iterators are lazy and do nothing unless consumed"]
2531 #[stable(feature = "rust1", since = "1.0.0")]
2533 pub struct Inspect<I, F> {
2537 impl<I, F> Inspect<I, F> {
2538 pub(super) fn new(iter: I, f: F) -> Inspect<I, F> {
2543 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2544 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2546 f.debug_struct("Inspect").field("iter", &self.iter).finish()
2550 impl<I: Iterator, F> Inspect<I, F>
2555 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2556 if let Some(ref a) = elt {
2564 fn inspect_fold<T, Acc>(
2565 mut f: impl FnMut(&T),
2566 mut fold: impl FnMut(Acc, T) -> Acc,
2567 ) -> impl FnMut(Acc, T) -> Acc {
2574 fn inspect_try_fold<'a, T, Acc, R>(
2575 f: &'a mut impl FnMut(&T),
2576 mut fold: impl FnMut(Acc, T) -> R + 'a,
2577 ) -> impl FnMut(Acc, T) -> R + 'a {
2584 #[stable(feature = "rust1", since = "1.0.0")]
2585 impl<I: Iterator, F> Iterator for Inspect<I, F>
2589 type Item = I::Item;
2592 fn next(&mut self) -> Option<I::Item> {
2593 let next = self.iter.next();
2594 self.do_inspect(next)
2598 fn size_hint(&self) -> (usize, Option<usize>) {
2599 self.iter.size_hint()
2603 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2606 Fold: FnMut(Acc, Self::Item) -> R,
2609 self.iter.try_fold(init, inspect_try_fold(&mut self.f, fold))
2613 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2615 Fold: FnMut(Acc, Self::Item) -> Acc,
2617 self.iter.fold(init, inspect_fold(self.f, fold))
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2627 fn next_back(&mut self) -> Option<I::Item> {
2628 let next = self.iter.next_back();
2629 self.do_inspect(next)
2633 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2636 Fold: FnMut(Acc, Self::Item) -> R,
2639 self.iter.try_rfold(init, inspect_try_fold(&mut self.f, fold))
2643 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2645 Fold: FnMut(Acc, Self::Item) -> Acc,
2647 self.iter.rfold(init, inspect_fold(self.f, fold))
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2656 fn len(&self) -> usize {
2660 fn is_empty(&self) -> bool {
2661 self.iter.is_empty()
2665 #[stable(feature = "fused", since = "1.26.0")]
2666 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F> where F: FnMut(&I::Item) {}
2668 /// An iterator adapter that produces output as long as the underlying
2669 /// iterator produces `Result::Ok` values.
2671 /// If an error is encountered, the iterator stops and the error is
2673 pub(crate) struct ResultShunt<'a, I, E> {
2675 error: &'a mut Result<(), E>,
2678 /// Process the given iterator as if it yielded a `T` instead of a
2679 /// `Result<T, _>`. Any errors will stop the inner iterator and
2680 /// the overall result will be an error.
2681 pub(crate) fn process_results<I, T, E, F, U>(iter: I, mut f: F) -> Result<U, E>
2683 I: Iterator<Item = Result<T, E>>,
2684 for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U,
2686 let mut error = Ok(());
2687 let shunt = ResultShunt { iter, error: &mut error };
2688 let value = f(shunt);
2689 error.map(|()| value)
2692 impl<I, T, E> Iterator for ResultShunt<'_, I, E>
2694 I: Iterator<Item = Result<T, E>>,
2698 fn next(&mut self) -> Option<Self::Item> {
2702 fn size_hint(&self) -> (usize, Option<usize>) {
2703 if self.error.is_err() {
2706 let (_, upper) = self.iter.size_hint();
2711 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2713 F: FnMut(B, Self::Item) -> R,
2716 let error = &mut *self.error;
2718 .try_fold(init, |acc, x| match x {
2719 Ok(x) => LoopState::from_try(f(acc, x)),
2722 LoopState::Break(Try::from_ok(acc))