4 use crate::ops::{Add, AddAssign, ControlFlow, Try};
8 DoubleEndedIterator, ExactSizeIterator, FusedIterator, InPlaceIterable, Iterator, TrustedLen,
16 pub use self::chain::Chain;
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub use self::flatten::{FlatMap, Flatten};
19 pub use self::fuse::Fuse;
20 use self::zip::try_get_unchecked;
21 #[unstable(feature = "trusted_random_access", issue = "none")]
22 pub use self::zip::TrustedRandomAccess;
23 pub use self::zip::Zip;
25 /// This trait provides transitive access to source-stage in an interator-adapter pipeline
26 /// under the conditions that
27 /// * the iterator source `S` itself implements `SourceIter<Source = S>`
28 /// * there is a delegating implementation of this trait for each adapter in the pipeline between
29 /// the source and the pipeline consumer.
31 /// When the source is an owning iterator struct (commonly called `IntoIter`) then
32 /// this can be useful for specializing [`FromIterator`] implementations or recovering the
33 /// remaining elements after an iterator has been partially exhausted.
35 /// Note that implementations do not necessarily have to provide access to the inner-most
36 /// source of a pipeline. A stateful intermediate adapter might eagerly evaluate a part
37 /// of the pipeline and expose its internal storage as source.
39 /// The trait is unsafe because implementers must uphold additional safety properties.
40 /// See [`as_inner`] for details.
44 /// Retrieving a partially consumed source:
47 /// # #![feature(inplace_iteration)]
48 /// # use std::iter::SourceIter;
50 /// let mut iter = vec![9, 9, 9].into_iter().map(|i| i * i);
51 /// let _ = iter.next();
52 /// let mut remainder = std::mem::replace(unsafe { iter.as_inner() }, Vec::new().into_iter());
53 /// println!("n = {} elements remaining", remainder.len());
56 /// [`FromIterator`]: crate::iter::FromIterator
57 /// [`as_inner`]: SourceIter::as_inner
58 #[unstable(issue = "none", feature = "inplace_iteration")]
59 pub unsafe trait SourceIter {
60 /// A source stage in an iterator pipeline.
61 type Source: Iterator;
63 /// Retrieve the source of an iterator pipeline.
67 /// Implementations of must return the same mutable reference for their lifetime, unless
68 /// replaced by a caller.
69 /// Callers may only replace the reference when they stopped iteration and drop the
70 /// iterator pipeline after extracting the source.
72 /// This means iterator adapters can rely on the source not changing during
73 /// iteration but they cannot rely on it in their Drop implementations.
75 /// Implementing this method means adapters relinquish private-only access to their
76 /// source and can only rely on guarantees made based on method receiver types.
77 /// The lack of restricted access also requires that adapters must uphold the source's
78 /// public API even when they have access to its internals.
80 /// Callers in turn must expect the source to be in any state that is consistent with
81 /// its public API since adapters sitting between it and the source have the same
82 /// access. In particular an adapter may have consumed more elements than strictly necessary.
84 /// The overall goal of these requirements is to let the consumer of a pipeline use
85 /// * whatever remains in the source after iteration has stopped
86 /// * the memory that has become unused by advancing a consuming iterator
88 /// [`next()`]: trait.Iterator.html#method.next
89 unsafe fn as_inner(&mut self) -> &mut Self::Source;
92 /// A double-ended iterator with the direction inverted.
94 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
95 /// documentation for more.
97 /// [`rev`]: trait.Iterator.html#method.rev
98 /// [`Iterator`]: trait.Iterator.html
99 #[derive(Clone, Debug)]
100 #[must_use = "iterators are lazy and do nothing unless consumed"]
101 #[stable(feature = "rust1", since = "1.0.0")]
106 pub(super) fn new(iter: T) -> Rev<T> {
111 #[stable(feature = "rust1", since = "1.0.0")]
112 impl<I> Iterator for Rev<I>
114 I: DoubleEndedIterator,
116 type Item = <I as Iterator>::Item;
119 fn next(&mut self) -> Option<<I as Iterator>::Item> {
120 self.iter.next_back()
123 fn size_hint(&self) -> (usize, Option<usize>) {
124 self.iter.size_hint()
128 fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
129 self.iter.nth_back(n)
132 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
135 F: FnMut(B, Self::Item) -> R,
138 self.iter.try_rfold(init, f)
141 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
143 F: FnMut(Acc, Self::Item) -> Acc,
145 self.iter.rfold(init, f)
149 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
151 P: FnMut(&Self::Item) -> bool,
153 self.iter.rfind(predicate)
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<I> DoubleEndedIterator for Rev<I>
160 I: DoubleEndedIterator,
163 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
168 fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
172 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
175 F: FnMut(B, Self::Item) -> R,
178 self.iter.try_fold(init, f)
181 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
183 F: FnMut(Acc, Self::Item) -> Acc,
185 self.iter.fold(init, f)
188 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
190 P: FnMut(&Self::Item) -> bool,
192 self.iter.find(predicate)
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<I> ExactSizeIterator for Rev<I>
199 I: ExactSizeIterator + DoubleEndedIterator,
201 fn len(&self) -> usize {
205 fn is_empty(&self) -> bool {
210 #[stable(feature = "fused", since = "1.26.0")]
211 impl<I> FusedIterator for Rev<I> where I: FusedIterator + DoubleEndedIterator {}
213 #[unstable(feature = "trusted_len", issue = "37572")]
214 unsafe impl<I> TrustedLen for Rev<I> where I: TrustedLen + DoubleEndedIterator {}
216 /// An iterator that copies the elements of an underlying iterator.
218 /// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
219 /// documentation for more.
221 /// [`copied`]: trait.Iterator.html#method.copied
222 /// [`Iterator`]: trait.Iterator.html
223 #[stable(feature = "iter_copied", since = "1.36.0")]
224 #[must_use = "iterators are lazy and do nothing unless consumed"]
225 #[derive(Clone, Debug)]
226 pub struct Copied<I> {
231 pub(super) fn new(it: I) -> Copied<I> {
236 fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
237 move |acc, &elt| f(acc, elt)
240 fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
241 move |acc, &elt| f(acc, elt)
244 #[stable(feature = "iter_copied", since = "1.36.0")]
245 impl<'a, I, T: 'a> Iterator for Copied<I>
247 I: Iterator<Item = &'a T>,
252 fn next(&mut self) -> Option<T> {
253 self.it.next().copied()
256 fn size_hint(&self) -> (usize, Option<usize>) {
260 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
263 F: FnMut(B, Self::Item) -> R,
266 self.it.try_fold(init, copy_try_fold(f))
269 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
271 F: FnMut(Acc, Self::Item) -> Acc,
273 self.it.fold(init, copy_fold(f))
276 fn nth(&mut self, n: usize) -> Option<T> {
277 self.it.nth(n).copied()
280 fn last(self) -> Option<T> {
281 self.it.last().copied()
284 fn count(self) -> usize {
288 unsafe fn get_unchecked(&mut self, idx: usize) -> T
290 Self: TrustedRandomAccess,
292 // SAFETY: the caller must uphold the contract for
293 // `Iterator::get_unchecked`.
294 *unsafe { try_get_unchecked(&mut self.it, idx) }
298 #[stable(feature = "iter_copied", since = "1.36.0")]
299 impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
301 I: DoubleEndedIterator<Item = &'a T>,
304 fn next_back(&mut self) -> Option<T> {
305 self.it.next_back().copied()
308 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
311 F: FnMut(B, Self::Item) -> R,
314 self.it.try_rfold(init, copy_try_fold(f))
317 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
319 F: FnMut(Acc, Self::Item) -> Acc,
321 self.it.rfold(init, copy_fold(f))
325 #[stable(feature = "iter_copied", since = "1.36.0")]
326 impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
328 I: ExactSizeIterator<Item = &'a T>,
331 fn len(&self) -> usize {
335 fn is_empty(&self) -> bool {
340 #[stable(feature = "iter_copied", since = "1.36.0")]
341 impl<'a, I, T: 'a> FusedIterator for Copied<I>
343 I: FusedIterator<Item = &'a T>,
349 #[unstable(feature = "trusted_random_access", issue = "none")]
350 unsafe impl<I> TrustedRandomAccess for Copied<I>
352 I: TrustedRandomAccess,
355 fn may_have_side_effect() -> bool {
356 I::may_have_side_effect()
360 #[stable(feature = "iter_copied", since = "1.36.0")]
361 unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
363 I: TrustedLen<Item = &'a T>,
368 /// An iterator that clones the elements of an underlying iterator.
370 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
371 /// documentation for more.
373 /// [`cloned`]: trait.Iterator.html#method.cloned
374 /// [`Iterator`]: trait.Iterator.html
375 #[stable(feature = "iter_cloned", since = "1.1.0")]
376 #[must_use = "iterators are lazy and do nothing unless consumed"]
377 #[derive(Clone, Debug)]
378 pub struct Cloned<I> {
382 pub(super) fn new(it: I) -> Cloned<I> {
387 fn clone_try_fold<T: Clone, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
388 move |acc, elt| f(acc, elt.clone())
391 #[stable(feature = "iter_cloned", since = "1.1.0")]
392 impl<'a, I, T: 'a> Iterator for Cloned<I>
394 I: Iterator<Item = &'a T>,
399 fn next(&mut self) -> Option<T> {
400 self.it.next().cloned()
403 fn size_hint(&self) -> (usize, Option<usize>) {
407 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
410 F: FnMut(B, Self::Item) -> R,
413 self.it.try_fold(init, clone_try_fold(f))
416 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
418 F: FnMut(Acc, Self::Item) -> Acc,
420 self.it.map(T::clone).fold(init, f)
423 unsafe fn get_unchecked(&mut self, idx: usize) -> T
425 Self: TrustedRandomAccess,
427 // SAFETY: the caller must uphold the contract for
428 // `Iterator::get_unchecked`.
429 unsafe { try_get_unchecked(&mut self.it, idx).clone() }
433 #[stable(feature = "iter_cloned", since = "1.1.0")]
434 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
436 I: DoubleEndedIterator<Item = &'a T>,
439 fn next_back(&mut self) -> Option<T> {
440 self.it.next_back().cloned()
443 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
446 F: FnMut(B, Self::Item) -> R,
449 self.it.try_rfold(init, clone_try_fold(f))
452 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
454 F: FnMut(Acc, Self::Item) -> Acc,
456 self.it.map(T::clone).rfold(init, f)
460 #[stable(feature = "iter_cloned", since = "1.1.0")]
461 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
463 I: ExactSizeIterator<Item = &'a T>,
466 fn len(&self) -> usize {
470 fn is_empty(&self) -> bool {
475 #[stable(feature = "fused", since = "1.26.0")]
476 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
478 I: FusedIterator<Item = &'a T>,
484 #[unstable(feature = "trusted_random_access", issue = "none")]
485 unsafe impl<I> TrustedRandomAccess for Cloned<I>
487 I: TrustedRandomAccess,
490 fn may_have_side_effect() -> bool {
495 #[unstable(feature = "trusted_len", issue = "37572")]
496 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
498 I: TrustedLen<Item = &'a T>,
503 /// An iterator that repeats endlessly.
505 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
506 /// documentation for more.
508 /// [`cycle`]: trait.Iterator.html#method.cycle
509 /// [`Iterator`]: trait.Iterator.html
510 #[derive(Clone, Debug)]
511 #[must_use = "iterators are lazy and do nothing unless consumed"]
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub struct Cycle<I> {
517 impl<I: Clone> Cycle<I> {
518 pub(super) fn new(iter: I) -> Cycle<I> {
519 Cycle { orig: iter.clone(), iter }
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl<I> Iterator for Cycle<I>
528 type Item = <I as Iterator>::Item;
531 fn next(&mut self) -> Option<<I as Iterator>::Item> {
532 match self.iter.next() {
534 self.iter = self.orig.clone();
542 fn size_hint(&self) -> (usize, Option<usize>) {
543 // the cycle iterator is either empty or infinite
544 match self.orig.size_hint() {
545 sz @ (0, Some(0)) => sz,
547 _ => (usize::MAX, None),
552 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
554 F: FnMut(Acc, Self::Item) -> R,
557 // fully iterate the current iterator. this is necessary because
558 // `self.iter` may be empty even when `self.orig` isn't
559 acc = self.iter.try_fold(acc, &mut f)?;
560 self.iter = self.orig.clone();
562 // complete a full cycle, keeping track of whether the cycled
563 // iterator is empty or not. we need to return early in case
564 // of an empty iterator to prevent an infinite loop
565 let mut is_empty = true;
566 acc = self.iter.try_fold(acc, |acc, x| {
572 return Try::from_ok(acc);
576 self.iter = self.orig.clone();
577 acc = self.iter.try_fold(acc, &mut f)?;
581 // No `fold` override, because `fold` doesn't make much sense for `Cycle`,
582 // and we can't do anything better than the default.
585 #[stable(feature = "fused", since = "1.26.0")]
586 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
588 /// An iterator for stepping iterators by a custom amount.
590 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
591 /// its documentation for more.
593 /// [`step_by`]: trait.Iterator.html#method.step_by
594 /// [`Iterator`]: trait.Iterator.html
595 #[must_use = "iterators are lazy and do nothing unless consumed"]
596 #[stable(feature = "iterator_step_by", since = "1.28.0")]
597 #[derive(Clone, Debug)]
598 pub struct StepBy<I> {
604 pub(super) fn new(iter: I, step: usize) -> StepBy<I> {
606 StepBy { iter, step: step - 1, first_take: true }
610 #[stable(feature = "iterator_step_by", since = "1.28.0")]
611 impl<I> Iterator for StepBy<I>
618 fn next(&mut self) -> Option<Self::Item> {
620 self.first_take = false;
623 self.iter.nth(self.step)
628 fn size_hint(&self) -> (usize, Option<usize>) {
630 fn first_size(step: usize) -> impl Fn(usize) -> usize {
631 move |n| if n == 0 { 0 } else { 1 + (n - 1) / (step + 1) }
635 fn other_size(step: usize) -> impl Fn(usize) -> usize {
636 move |n| n / (step + 1)
639 let (low, high) = self.iter.size_hint();
642 let f = first_size(self.step);
643 (f(low), high.map(f))
645 let f = other_size(self.step);
646 (f(low), high.map(f))
651 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
653 self.first_take = false;
654 let first = self.iter.next();
660 // n and self.step are indices, we need to add 1 to get the amount of elements
661 // When calling `.nth`, we need to subtract 1 again to convert back to an index
662 // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
663 let mut step = self.step + 1;
664 // n + 1 could overflow
665 // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
667 self.iter.nth(step - 1);
674 let mul = n.checked_mul(step);
676 if intrinsics::likely(mul.is_some()) {
677 return self.iter.nth(mul.unwrap() - 1);
680 let div_n = usize::MAX / n;
681 let div_step = usize::MAX / step;
682 let nth_n = div_n * n;
683 let nth_step = div_step * step;
684 let nth = if nth_n > nth_step {
691 self.iter.nth(nth - 1);
695 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
697 F: FnMut(Acc, Self::Item) -> R,
701 fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
702 move || iter.nth(step)
706 self.first_take = false;
707 match self.iter.next() {
708 None => return Try::from_ok(acc),
709 Some(x) => acc = f(acc, x)?,
712 from_fn(nth(&mut self.iter, self.step)).try_fold(acc, f)
715 fn fold<Acc, F>(mut self, mut acc: Acc, mut f: F) -> Acc
717 F: FnMut(Acc, Self::Item) -> Acc,
720 fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
721 move || iter.nth(step)
725 self.first_take = false;
726 match self.iter.next() {
728 Some(x) => acc = f(acc, x),
731 from_fn(nth(&mut self.iter, self.step)).fold(acc, f)
737 I: ExactSizeIterator,
739 // The zero-based index starting from the end of the iterator of the
740 // last element. Used in the `DoubleEndedIterator` implementation.
741 fn next_back_index(&self) -> usize {
742 let rem = self.iter.len() % (self.step + 1);
744 if rem == 0 { self.step } else { rem - 1 }
751 #[stable(feature = "double_ended_step_by_iterator", since = "1.38.0")]
752 impl<I> DoubleEndedIterator for StepBy<I>
754 I: DoubleEndedIterator + ExactSizeIterator,
757 fn next_back(&mut self) -> Option<Self::Item> {
758 self.iter.nth_back(self.next_back_index())
762 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
763 // `self.iter.nth_back(usize::MAX)` does the right thing here when `n`
764 // is out of bounds because the length of `self.iter` does not exceed
765 // `usize::MAX` (because `I: ExactSizeIterator`) and `nth_back` is
767 let n = n.saturating_mul(self.step + 1).saturating_add(self.next_back_index());
768 self.iter.nth_back(n)
771 fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R
773 F: FnMut(Acc, Self::Item) -> R,
777 fn nth_back<I: DoubleEndedIterator>(
780 ) -> impl FnMut() -> Option<I::Item> + '_ {
781 move || iter.nth_back(step)
784 match self.next_back() {
785 None => Try::from_ok(init),
787 let acc = f(init, x)?;
788 from_fn(nth_back(&mut self.iter, self.step)).try_fold(acc, f)
794 fn rfold<Acc, F>(mut self, init: Acc, mut f: F) -> Acc
797 F: FnMut(Acc, Self::Item) -> Acc,
800 fn nth_back<I: DoubleEndedIterator>(
803 ) -> impl FnMut() -> Option<I::Item> + '_ {
804 move || iter.nth_back(step)
807 match self.next_back() {
810 let acc = f(init, x);
811 from_fn(nth_back(&mut self.iter, self.step)).fold(acc, f)
817 // StepBy can only make the iterator shorter, so the len will still fit.
818 #[stable(feature = "iterator_step_by", since = "1.28.0")]
819 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
821 /// An iterator that maps the values of `iter` with `f`.
823 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
824 /// documentation for more.
826 /// [`map`]: trait.Iterator.html#method.map
827 /// [`Iterator`]: trait.Iterator.html
829 /// # Notes about side effects
831 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
832 /// you can also [`map`] backwards:
835 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
837 /// assert_eq!(v, [4, 3, 2]);
840 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
842 /// But if your closure has state, iterating backwards may act in a way you do
843 /// not expect. Let's go through an example. First, in the forward direction:
848 /// for pair in vec!['a', 'b', 'c'].into_iter()
849 /// .map(|letter| { c += 1; (letter, c) }) {
850 /// println!("{:?}", pair);
854 /// This will print "('a', 1), ('b', 2), ('c', 3)".
856 /// Now consider this twist where we add a call to `rev`. This version will
857 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
858 /// but the values of the counter still go in order. This is because `map()` is
859 /// still being called lazily on each item, but we are popping items off the
860 /// back of the vector now, instead of shifting them from the front.
865 /// for pair in vec!['a', 'b', 'c'].into_iter()
866 /// .map(|letter| { c += 1; (letter, c) })
868 /// println!("{:?}", pair);
871 #[must_use = "iterators are lazy and do nothing unless consumed"]
872 #[stable(feature = "rust1", since = "1.0.0")]
874 pub struct Map<I, F> {
878 impl<I, F> Map<I, F> {
879 pub(super) fn new(iter: I, f: F) -> Map<I, F> {
884 #[stable(feature = "core_impl_debug", since = "1.9.0")]
885 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887 f.debug_struct("Map").field("iter", &self.iter).finish()
891 fn map_fold<T, B, Acc>(
892 mut f: impl FnMut(T) -> B,
893 mut g: impl FnMut(Acc, B) -> Acc,
894 ) -> impl FnMut(Acc, T) -> Acc {
895 move |acc, elt| g(acc, f(elt))
898 fn map_try_fold<'a, T, B, Acc, R>(
899 f: &'a mut impl FnMut(T) -> B,
900 mut g: impl FnMut(Acc, B) -> R + 'a,
901 ) -> impl FnMut(Acc, T) -> R + 'a {
902 move |acc, elt| g(acc, f(elt))
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<B, I: Iterator, F> Iterator for Map<I, F>
908 F: FnMut(I::Item) -> B,
913 fn next(&mut self) -> Option<B> {
914 self.iter.next().map(&mut self.f)
918 fn size_hint(&self) -> (usize, Option<usize>) {
919 self.iter.size_hint()
922 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
925 G: FnMut(Acc, Self::Item) -> R,
928 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
931 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
933 G: FnMut(Acc, Self::Item) -> Acc,
935 self.iter.fold(init, map_fold(self.f, g))
938 unsafe fn get_unchecked(&mut self, idx: usize) -> B
940 Self: TrustedRandomAccess,
942 // SAFETY: the caller must uphold the contract for
943 // `Iterator::get_unchecked`.
944 unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
951 F: FnMut(I::Item) -> B,
954 fn next_back(&mut self) -> Option<B> {
955 self.iter.next_back().map(&mut self.f)
958 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
961 G: FnMut(Acc, Self::Item) -> R,
964 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
967 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
969 G: FnMut(Acc, Self::Item) -> Acc,
971 self.iter.rfold(init, map_fold(self.f, g))
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
978 F: FnMut(I::Item) -> B,
980 fn len(&self) -> usize {
984 fn is_empty(&self) -> bool {
989 #[stable(feature = "fused", since = "1.26.0")]
990 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
992 #[unstable(feature = "trusted_len", issue = "37572")]
993 unsafe impl<B, I, F> TrustedLen for Map<I, F>
996 F: FnMut(I::Item) -> B,
1001 #[unstable(feature = "trusted_random_access", issue = "none")]
1002 unsafe impl<I, F> TrustedRandomAccess for Map<I, F>
1004 I: TrustedRandomAccess,
1007 fn may_have_side_effect() -> bool {
1012 #[unstable(issue = "none", feature = "inplace_iteration")]
1013 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for Map<I, F>
1015 F: FnMut(I::Item) -> B,
1016 I: SourceIter<Source = S>,
1021 unsafe fn as_inner(&mut self) -> &mut S {
1022 // Safety: unsafe function forwarding to unsafe function with the same requirements
1023 unsafe { SourceIter::as_inner(&mut self.iter) }
1027 #[unstable(issue = "none", feature = "inplace_iteration")]
1028 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for Map<I, F> where F: FnMut(I::Item) -> B {}
1030 /// An iterator that filters the elements of `iter` with `predicate`.
1032 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1033 /// documentation for more.
1035 /// [`filter`]: trait.Iterator.html#method.filter
1036 /// [`Iterator`]: trait.Iterator.html
1037 #[must_use = "iterators are lazy and do nothing unless consumed"]
1038 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub struct Filter<I, P> {
1044 impl<I, P> Filter<I, P> {
1045 pub(super) fn new(iter: I, predicate: P) -> Filter<I, P> {
1046 Filter { iter, predicate }
1050 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1051 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053 f.debug_struct("Filter").field("iter", &self.iter).finish()
1057 fn filter_fold<T, Acc>(
1058 mut predicate: impl FnMut(&T) -> bool,
1059 mut fold: impl FnMut(Acc, T) -> Acc,
1060 ) -> impl FnMut(Acc, T) -> Acc {
1061 move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
1064 fn filter_try_fold<'a, T, Acc, R: Try<Ok = Acc>>(
1065 predicate: &'a mut impl FnMut(&T) -> bool,
1066 mut fold: impl FnMut(Acc, T) -> R + 'a,
1067 ) -> impl FnMut(Acc, T) -> R + 'a {
1068 move |acc, item| if predicate(&item) { fold(acc, item) } else { R::from_ok(acc) }
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<I: Iterator, P> Iterator for Filter<I, P>
1074 P: FnMut(&I::Item) -> bool,
1076 type Item = I::Item;
1079 fn next(&mut self) -> Option<I::Item> {
1080 self.iter.find(&mut self.predicate)
1084 fn size_hint(&self) -> (usize, Option<usize>) {
1085 let (_, upper) = self.iter.size_hint();
1086 (0, upper) // can't know a lower bound, due to the predicate
1089 // this special case allows the compiler to make `.filter(_).count()`
1090 // branchless. Barring perfect branch prediction (which is unattainable in
1091 // the general case), this will be much faster in >90% of cases (containing
1092 // virtually all real workloads) and only a tiny bit slower in the rest.
1094 // Having this specialization thus allows us to write `.filter(p).count()`
1095 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1096 // less readable and also less backwards-compatible to Rust before 1.10.
1098 // Using the branchless version will also simplify the LLVM byte code, thus
1099 // leaving more budget for LLVM optimizations.
1101 fn count(self) -> usize {
1103 fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
1104 move |x| predicate(&x) as usize
1107 self.iter.map(to_usize(self.predicate)).sum()
1111 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1114 Fold: FnMut(Acc, Self::Item) -> R,
1117 self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
1121 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1123 Fold: FnMut(Acc, Self::Item) -> Acc,
1125 self.iter.fold(init, filter_fold(self.predicate, fold))
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1132 P: FnMut(&I::Item) -> bool,
1135 fn next_back(&mut self) -> Option<I::Item> {
1136 self.iter.rfind(&mut self.predicate)
1140 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1143 Fold: FnMut(Acc, Self::Item) -> R,
1146 self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
1150 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1152 Fold: FnMut(Acc, Self::Item) -> Acc,
1154 self.iter.rfold(init, filter_fold(self.predicate, fold))
1158 #[stable(feature = "fused", since = "1.26.0")]
1159 impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1161 #[unstable(issue = "none", feature = "inplace_iteration")]
1162 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
1164 P: FnMut(&I::Item) -> bool,
1165 I: SourceIter<Source = S>,
1170 unsafe fn as_inner(&mut self) -> &mut S {
1171 // Safety: unsafe function forwarding to unsafe function with the same requirements
1172 unsafe { SourceIter::as_inner(&mut self.iter) }
1176 #[unstable(issue = "none", feature = "inplace_iteration")]
1177 unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1179 /// An iterator that uses `f` to both filter and map elements from `iter`.
1181 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1182 /// documentation for more.
1184 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1185 /// [`Iterator`]: trait.Iterator.html
1186 #[must_use = "iterators are lazy and do nothing unless consumed"]
1187 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub struct FilterMap<I, F> {
1193 impl<I, F> FilterMap<I, F> {
1194 pub(super) fn new(iter: I, f: F) -> FilterMap<I, F> {
1195 FilterMap { iter, f }
1199 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1200 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202 f.debug_struct("FilterMap").field("iter", &self.iter).finish()
1206 fn filter_map_fold<T, B, Acc>(
1207 mut f: impl FnMut(T) -> Option<B>,
1208 mut fold: impl FnMut(Acc, B) -> Acc,
1209 ) -> impl FnMut(Acc, T) -> Acc {
1210 move |acc, item| match f(item) {
1211 Some(x) => fold(acc, x),
1216 fn filter_map_try_fold<'a, T, B, Acc, R: Try<Ok = Acc>>(
1217 f: &'a mut impl FnMut(T) -> Option<B>,
1218 mut fold: impl FnMut(Acc, B) -> R + 'a,
1219 ) -> impl FnMut(Acc, T) -> R + 'a {
1220 move |acc, item| match f(item) {
1221 Some(x) => fold(acc, x),
1222 None => R::from_ok(acc),
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1229 F: FnMut(I::Item) -> Option<B>,
1234 fn next(&mut self) -> Option<B> {
1235 self.iter.find_map(&mut self.f)
1239 fn size_hint(&self) -> (usize, Option<usize>) {
1240 let (_, upper) = self.iter.size_hint();
1241 (0, upper) // can't know a lower bound, due to the predicate
1245 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1248 Fold: FnMut(Acc, Self::Item) -> R,
1251 self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold))
1255 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1257 Fold: FnMut(Acc, Self::Item) -> Acc,
1259 self.iter.fold(init, filter_map_fold(self.f, fold))
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1266 F: FnMut(I::Item) -> Option<B>,
1269 fn next_back(&mut self) -> Option<B> {
1272 f: &mut impl FnMut(T) -> Option<B>,
1273 ) -> impl FnMut((), T) -> ControlFlow<(), B> + '_ {
1274 move |(), x| match f(x) {
1275 Some(x) => ControlFlow::Break(x),
1276 None => ControlFlow::CONTINUE,
1280 self.iter.try_rfold((), find(&mut self.f)).break_value()
1284 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1287 Fold: FnMut(Acc, Self::Item) -> R,
1290 self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold))
1294 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1296 Fold: FnMut(Acc, Self::Item) -> Acc,
1298 self.iter.rfold(init, filter_map_fold(self.f, fold))
1302 #[stable(feature = "fused", since = "1.26.0")]
1303 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F> where F: FnMut(I::Item) -> Option<B> {}
1305 #[unstable(issue = "none", feature = "inplace_iteration")]
1306 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for FilterMap<I, F>
1308 F: FnMut(I::Item) -> Option<B>,
1309 I: SourceIter<Source = S>,
1314 unsafe fn as_inner(&mut self) -> &mut S {
1315 // Safety: unsafe function forwarding to unsafe function with the same requirements
1316 unsafe { SourceIter::as_inner(&mut self.iter) }
1320 #[unstable(issue = "none", feature = "inplace_iteration")]
1321 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for FilterMap<I, F> where
1322 F: FnMut(I::Item) -> Option<B>
1326 /// An iterator that yields the current count and the element during iteration.
1328 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1329 /// documentation for more.
1331 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1332 /// [`Iterator`]: trait.Iterator.html
1333 #[derive(Clone, Debug)]
1334 #[must_use = "iterators are lazy and do nothing unless consumed"]
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub struct Enumerate<I> {
1340 impl<I> Enumerate<I> {
1341 pub(super) fn new(iter: I) -> Enumerate<I> {
1342 Enumerate { iter, count: 0 }
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl<I> Iterator for Enumerate<I>
1351 type Item = (usize, <I as Iterator>::Item);
1353 /// # Overflow Behavior
1355 /// The method does no guarding against overflows, so enumerating more than
1356 /// `usize::MAX` elements either produces the wrong result or panics. If
1357 /// debug assertions are enabled, a panic is guaranteed.
1361 /// Might panic if the index of the element overflows a `usize`.
1363 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1364 let a = self.iter.next()?;
1366 // Possible undefined overflow.
1367 AddAssign::add_assign(&mut self.count, 1);
1372 fn size_hint(&self) -> (usize, Option<usize>) {
1373 self.iter.size_hint()
1377 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1378 let a = self.iter.nth(n)?;
1379 // Possible undefined overflow.
1380 let i = Add::add(self.count, n);
1381 self.count = Add::add(i, 1);
1386 fn count(self) -> usize {
1391 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1394 Fold: FnMut(Acc, Self::Item) -> R,
1398 fn enumerate<'a, T, Acc, R>(
1399 count: &'a mut usize,
1400 mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a,
1401 ) -> impl FnMut(Acc, T) -> R + 'a {
1403 let acc = fold(acc, (*count, item));
1404 // Possible undefined overflow.
1405 AddAssign::add_assign(count, 1);
1410 self.iter.try_fold(init, enumerate(&mut self.count, fold))
1414 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1416 Fold: FnMut(Acc, Self::Item) -> Acc,
1419 fn enumerate<T, Acc>(
1421 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1422 ) -> impl FnMut(Acc, T) -> Acc {
1424 let acc = fold(acc, (count, item));
1425 // Possible undefined overflow.
1426 AddAssign::add_assign(&mut count, 1);
1431 self.iter.fold(init, enumerate(self.count, fold))
1434 unsafe fn get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item
1436 Self: TrustedRandomAccess,
1438 // SAFETY: the caller must uphold the contract for
1439 // `Iterator::get_unchecked`.
1440 let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
1441 (Add::add(self.count, idx), value)
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl<I> DoubleEndedIterator for Enumerate<I>
1448 I: ExactSizeIterator + DoubleEndedIterator,
1451 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1452 let a = self.iter.next_back()?;
1453 let len = self.iter.len();
1454 // Can safely add, `ExactSizeIterator` promises that the number of
1455 // elements fits into a `usize`.
1456 Some((self.count + len, a))
1460 fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
1461 let a = self.iter.nth_back(n)?;
1462 let len = self.iter.len();
1463 // Can safely add, `ExactSizeIterator` promises that the number of
1464 // elements fits into a `usize`.
1465 Some((self.count + len, a))
1469 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1472 Fold: FnMut(Acc, Self::Item) -> R,
1475 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1476 // that the number of elements fits into a `usize`.
1477 fn enumerate<T, Acc, R>(
1479 mut fold: impl FnMut(Acc, (usize, T)) -> R,
1480 ) -> impl FnMut(Acc, T) -> R {
1483 fold(acc, (count, item))
1487 let count = self.count + self.iter.len();
1488 self.iter.try_rfold(init, enumerate(count, fold))
1492 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1494 Fold: FnMut(Acc, Self::Item) -> Acc,
1496 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1497 // that the number of elements fits into a `usize`.
1498 fn enumerate<T, Acc>(
1500 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1501 ) -> impl FnMut(Acc, T) -> Acc {
1504 fold(acc, (count, item))
1508 let count = self.count + self.iter.len();
1509 self.iter.rfold(init, enumerate(count, fold))
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<I> ExactSizeIterator for Enumerate<I>
1516 I: ExactSizeIterator,
1518 fn len(&self) -> usize {
1522 fn is_empty(&self) -> bool {
1523 self.iter.is_empty()
1528 #[unstable(feature = "trusted_random_access", issue = "none")]
1529 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1531 I: TrustedRandomAccess,
1533 fn may_have_side_effect() -> bool {
1534 I::may_have_side_effect()
1538 #[stable(feature = "fused", since = "1.26.0")]
1539 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1541 #[unstable(feature = "trusted_len", issue = "37572")]
1542 unsafe impl<I> TrustedLen for Enumerate<I> where I: TrustedLen {}
1544 #[unstable(issue = "none", feature = "inplace_iteration")]
1545 unsafe impl<S: Iterator, I: Iterator> SourceIter for Enumerate<I>
1547 I: SourceIter<Source = S>,
1552 unsafe fn as_inner(&mut self) -> &mut S {
1553 // Safety: unsafe function forwarding to unsafe function with the same requirements
1554 unsafe { SourceIter::as_inner(&mut self.iter) }
1558 #[unstable(issue = "none", feature = "inplace_iteration")]
1559 unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> {}
1561 /// An iterator with a `peek()` that returns an optional reference to the next
1564 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1565 /// documentation for more.
1567 /// [`peekable`]: trait.Iterator.html#method.peekable
1568 /// [`Iterator`]: trait.Iterator.html
1569 #[derive(Clone, Debug)]
1570 #[must_use = "iterators are lazy and do nothing unless consumed"]
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 pub struct Peekable<I: Iterator> {
1574 /// Remember a peeked value, even if it was None.
1575 peeked: Option<Option<I::Item>>,
1577 impl<I: Iterator> Peekable<I> {
1578 pub(super) fn new(iter: I) -> Peekable<I> {
1579 Peekable { iter, peeked: None }
1583 // Peekable must remember if a None has been seen in the `.peek()` method.
1584 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1585 // underlying iterator at most once. This does not by itself make the iterator
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 impl<I: Iterator> Iterator for Peekable<I> {
1589 type Item = I::Item;
1592 fn next(&mut self) -> Option<I::Item> {
1593 match self.peeked.take() {
1595 None => self.iter.next(),
1600 #[rustc_inherit_overflow_checks]
1601 fn count(mut self) -> usize {
1602 match self.peeked.take() {
1604 Some(Some(_)) => 1 + self.iter.count(),
1605 None => self.iter.count(),
1610 fn nth(&mut self, n: usize) -> Option<I::Item> {
1611 match self.peeked.take() {
1613 Some(v @ Some(_)) if n == 0 => v,
1614 Some(Some(_)) => self.iter.nth(n - 1),
1615 None => self.iter.nth(n),
1620 fn last(mut self) -> Option<I::Item> {
1621 let peek_opt = match self.peeked.take() {
1622 Some(None) => return None,
1626 self.iter.last().or(peek_opt)
1630 fn size_hint(&self) -> (usize, Option<usize>) {
1631 let peek_len = match self.peeked {
1632 Some(None) => return (0, Some(0)),
1636 let (lo, hi) = self.iter.size_hint();
1637 let lo = lo.saturating_add(peek_len);
1639 Some(x) => x.checked_add(peek_len),
1646 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1649 F: FnMut(B, Self::Item) -> R,
1652 let acc = match self.peeked.take() {
1653 Some(None) => return Try::from_ok(init),
1654 Some(Some(v)) => f(init, v)?,
1657 self.iter.try_fold(acc, f)
1661 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1663 Fold: FnMut(Acc, Self::Item) -> Acc,
1665 let acc = match self.peeked {
1666 Some(None) => return init,
1667 Some(Some(v)) => fold(init, v),
1670 self.iter.fold(acc, fold)
1674 #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
1675 impl<I> DoubleEndedIterator for Peekable<I>
1677 I: DoubleEndedIterator,
1680 fn next_back(&mut self) -> Option<Self::Item> {
1681 match self.peeked.as_mut() {
1682 Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
1684 None => self.iter.next_back(),
1689 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
1692 F: FnMut(B, Self::Item) -> R,
1695 match self.peeked.take() {
1696 Some(None) => Try::from_ok(init),
1697 Some(Some(v)) => match self.iter.try_rfold(init, &mut f).into_result() {
1698 Ok(acc) => f(acc, v),
1700 self.peeked = Some(Some(v));
1704 None => self.iter.try_rfold(init, f),
1709 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1711 Fold: FnMut(Acc, Self::Item) -> Acc,
1716 let acc = self.iter.rfold(init, &mut fold);
1719 None => self.iter.rfold(init, fold),
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1727 #[stable(feature = "fused", since = "1.26.0")]
1728 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1730 impl<I: Iterator> Peekable<I> {
1731 /// Returns a reference to the next() value without advancing the iterator.
1733 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1734 /// But if the iteration is over, `None` is returned.
1736 /// [`next`]: trait.Iterator.html#tymethod.next
1738 /// Because `peek()` returns a reference, and many iterators iterate over
1739 /// references, there can be a possibly confusing situation where the
1740 /// return value is a double reference. You can see this effect in the
1748 /// let xs = [1, 2, 3];
1750 /// let mut iter = xs.iter().peekable();
1752 /// // peek() lets us see into the future
1753 /// assert_eq!(iter.peek(), Some(&&1));
1754 /// assert_eq!(iter.next(), Some(&1));
1756 /// assert_eq!(iter.next(), Some(&2));
1758 /// // The iterator does not advance even if we `peek` multiple times
1759 /// assert_eq!(iter.peek(), Some(&&3));
1760 /// assert_eq!(iter.peek(), Some(&&3));
1762 /// assert_eq!(iter.next(), Some(&3));
1764 /// // After the iterator is finished, so is `peek()`
1765 /// assert_eq!(iter.peek(), None);
1766 /// assert_eq!(iter.next(), None);
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 pub fn peek(&mut self) -> Option<&I::Item> {
1771 let iter = &mut self.iter;
1772 self.peeked.get_or_insert_with(|| iter.next()).as_ref()
1775 /// Consume and return the next value of this iterator if a condition is true.
1777 /// If `func` returns `true` for the next value of this iterator, consume and return it.
1778 /// Otherwise, return `None`.
1781 /// Consume a number if it's equal to 0.
1783 /// #![feature(peekable_next_if)]
1784 /// let mut iter = (0..5).peekable();
1785 /// // The first item of the iterator is 0; consume it.
1786 /// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
1787 /// // The next item returned is now 1, so `consume` will return `false`.
1788 /// assert_eq!(iter.next_if(|&x| x == 0), None);
1789 /// // `next_if` saves the value of the next item if it was not equal to `expected`.
1790 /// assert_eq!(iter.next(), Some(1));
1793 /// Consume any number less than 10.
1795 /// #![feature(peekable_next_if)]
1796 /// let mut iter = (1..20).peekable();
1797 /// // Consume all numbers less than 10
1798 /// while iter.next_if(|&x| x < 10).is_some() {}
1799 /// // The next value returned will be 10
1800 /// assert_eq!(iter.next(), Some(10));
1802 #[unstable(feature = "peekable_next_if", issue = "72480")]
1803 pub fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item> {
1805 Some(matched) if func(&matched) => Some(matched),
1807 // Since we called `self.next()`, we consumed `self.peeked`.
1808 assert!(self.peeked.is_none());
1809 self.peeked = Some(other);
1815 /// Consume and return the next item if it is equal to `expected`.
1818 /// Consume a number if it's equal to 0.
1820 /// #![feature(peekable_next_if)]
1821 /// let mut iter = (0..5).peekable();
1822 /// // The first item of the iterator is 0; consume it.
1823 /// assert_eq!(iter.next_if_eq(&0), Some(0));
1824 /// // The next item returned is now 1, so `consume` will return `false`.
1825 /// assert_eq!(iter.next_if_eq(&0), None);
1826 /// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
1827 /// assert_eq!(iter.next(), Some(1));
1829 #[unstable(feature = "peekable_next_if", issue = "72480")]
1830 pub fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item>
1833 I::Item: PartialEq<T>,
1835 self.next_if(|next| next == expected)
1839 #[unstable(feature = "trusted_len", issue = "37572")]
1840 unsafe impl<I> TrustedLen for Peekable<I> where I: TrustedLen {}
1842 #[unstable(issue = "none", feature = "inplace_iteration")]
1843 unsafe impl<S: Iterator, I: Iterator> SourceIter for Peekable<I>
1845 I: SourceIter<Source = S>,
1850 unsafe fn as_inner(&mut self) -> &mut S {
1851 // Safety: unsafe function forwarding to unsafe function with the same requirements
1852 unsafe { SourceIter::as_inner(&mut self.iter) }
1856 #[unstable(issue = "none", feature = "inplace_iteration")]
1857 unsafe impl<I: InPlaceIterable> InPlaceIterable for Peekable<I> {}
1859 /// An iterator that rejects elements while `predicate` returns `true`.
1861 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1862 /// documentation for more.
1864 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1865 /// [`Iterator`]: trait.Iterator.html
1866 #[must_use = "iterators are lazy and do nothing unless consumed"]
1867 #[stable(feature = "rust1", since = "1.0.0")]
1869 pub struct SkipWhile<I, P> {
1874 impl<I, P> SkipWhile<I, P> {
1875 pub(super) fn new(iter: I, predicate: P) -> SkipWhile<I, P> {
1876 SkipWhile { iter, flag: false, predicate }
1880 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1881 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883 f.debug_struct("SkipWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1890 P: FnMut(&I::Item) -> bool,
1892 type Item = I::Item;
1895 fn next(&mut self) -> Option<I::Item> {
1898 pred: &'a mut impl FnMut(&T) -> bool,
1899 ) -> impl FnMut(&T) -> bool + 'a {
1901 if *flag || !pred(x) {
1910 let flag = &mut self.flag;
1911 let pred = &mut self.predicate;
1912 self.iter.find(check(flag, pred))
1916 fn size_hint(&self) -> (usize, Option<usize>) {
1917 let (_, upper) = self.iter.size_hint();
1918 (0, upper) // can't know a lower bound, due to the predicate
1922 fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R
1925 Fold: FnMut(Acc, Self::Item) -> R,
1930 Some(v) => init = fold(init, v)?,
1931 None => return Try::from_ok(init),
1934 self.iter.try_fold(init, fold)
1938 fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
1940 Fold: FnMut(Acc, Self::Item) -> Acc,
1944 Some(v) => init = fold(init, v),
1945 None => return init,
1948 self.iter.fold(init, fold)
1952 #[stable(feature = "fused", since = "1.26.0")]
1953 impl<I, P> FusedIterator for SkipWhile<I, P>
1956 P: FnMut(&I::Item) -> bool,
1960 #[unstable(issue = "none", feature = "inplace_iteration")]
1961 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for SkipWhile<I, P>
1963 P: FnMut(&I::Item) -> bool,
1964 I: SourceIter<Source = S>,
1969 unsafe fn as_inner(&mut self) -> &mut S {
1970 // Safety: unsafe function forwarding to unsafe function with the same requirements
1971 unsafe { SourceIter::as_inner(&mut self.iter) }
1975 #[unstable(issue = "none", feature = "inplace_iteration")]
1976 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for SkipWhile<I, F> where
1977 F: FnMut(&I::Item) -> bool
1981 /// An iterator that only accepts elements while `predicate` returns `true`.
1983 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1984 /// documentation for more.
1986 /// [`take_while`]: trait.Iterator.html#method.take_while
1987 /// [`Iterator`]: trait.Iterator.html
1988 #[must_use = "iterators are lazy and do nothing unless consumed"]
1989 #[stable(feature = "rust1", since = "1.0.0")]
1991 pub struct TakeWhile<I, P> {
1996 impl<I, P> TakeWhile<I, P> {
1997 pub(super) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
1998 TakeWhile { iter, flag: false, predicate }
2002 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2003 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
2004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2005 f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2012 P: FnMut(&I::Item) -> bool,
2014 type Item = I::Item;
2017 fn next(&mut self) -> Option<I::Item> {
2021 let x = self.iter.next()?;
2022 if (self.predicate)(&x) {
2032 fn size_hint(&self) -> (usize, Option<usize>) {
2036 let (_, upper) = self.iter.size_hint();
2037 (0, upper) // can't know a lower bound, due to the predicate
2042 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2045 Fold: FnMut(Acc, Self::Item) -> R,
2048 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2050 p: &'a mut impl FnMut(&T) -> bool,
2051 mut fold: impl FnMut(Acc, T) -> R + 'a,
2052 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2055 ControlFlow::from_try(fold(acc, x))
2058 ControlFlow::Break(Try::from_ok(acc))
2066 let flag = &mut self.flag;
2067 let p = &mut self.predicate;
2068 self.iter.try_fold(init, check(flag, p, fold)).into_try()
2073 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2076 Fold: FnMut(Acc, Self::Item) -> Acc,
2079 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2080 move |acc, x| Ok(f(acc, x))
2083 self.try_fold(init, ok(fold)).unwrap()
2087 #[stable(feature = "fused", since = "1.26.0")]
2088 impl<I, P> FusedIterator for TakeWhile<I, P>
2091 P: FnMut(&I::Item) -> bool,
2095 #[unstable(issue = "none", feature = "inplace_iteration")]
2096 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for TakeWhile<I, P>
2098 P: FnMut(&I::Item) -> bool,
2099 I: SourceIter<Source = S>,
2104 unsafe fn as_inner(&mut self) -> &mut S {
2105 // Safety: unsafe function forwarding to unsafe function with the same requirements
2106 unsafe { SourceIter::as_inner(&mut self.iter) }
2110 #[unstable(issue = "none", feature = "inplace_iteration")]
2111 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> where
2112 F: FnMut(&I::Item) -> bool
2116 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
2118 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
2119 /// documentation for more.
2121 /// [`map_while`]: trait.Iterator.html#method.map_while
2122 /// [`Iterator`]: trait.Iterator.html
2123 #[must_use = "iterators are lazy and do nothing unless consumed"]
2124 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2126 pub struct MapWhile<I, P> {
2131 impl<I, P> MapWhile<I, P> {
2132 pub(super) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
2133 MapWhile { iter, predicate }
2137 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2138 impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
2139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2140 f.debug_struct("MapWhile").field("iter", &self.iter).finish()
2144 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2145 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
2147 P: FnMut(I::Item) -> Option<B>,
2152 fn next(&mut self) -> Option<B> {
2153 let x = self.iter.next()?;
2158 fn size_hint(&self) -> (usize, Option<usize>) {
2159 let (_, upper) = self.iter.size_hint();
2160 (0, upper) // can't know a lower bound, due to the predicate
2164 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
2167 Fold: FnMut(Acc, Self::Item) -> R,
2170 let Self { iter, predicate } = self;
2171 iter.try_fold(init, |acc, x| match predicate(x) {
2172 Some(item) => ControlFlow::from_try(fold(acc, item)),
2173 None => ControlFlow::Break(Try::from_ok(acc)),
2179 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2182 Fold: FnMut(Acc, Self::Item) -> Acc,
2185 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2186 move |acc, x| Ok(f(acc, x))
2189 self.try_fold(init, ok(fold)).unwrap()
2193 #[unstable(issue = "none", feature = "inplace_iteration")]
2194 unsafe impl<S: Iterator, B, I: Iterator, P> SourceIter for MapWhile<I, P>
2196 P: FnMut(I::Item) -> Option<B>,
2197 I: SourceIter<Source = S>,
2202 unsafe fn as_inner(&mut self) -> &mut S {
2203 // Safety: unsafe function forwarding to unsafe function with the same requirements
2204 unsafe { SourceIter::as_inner(&mut self.iter) }
2208 #[unstable(issue = "none", feature = "inplace_iteration")]
2209 unsafe impl<B, I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> where
2210 P: FnMut(I::Item) -> Option<B>
2214 /// An iterator that skips over `n` elements of `iter`.
2216 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
2217 /// documentation for more.
2219 /// [`skip`]: trait.Iterator.html#method.skip
2220 /// [`Iterator`]: trait.Iterator.html
2221 #[derive(Clone, Debug)]
2222 #[must_use = "iterators are lazy and do nothing unless consumed"]
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 pub struct Skip<I> {
2229 pub(super) fn new(iter: I, n: usize) -> Skip<I> {
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 impl<I> Iterator for Skip<I>
2239 type Item = <I as Iterator>::Item;
2242 fn next(&mut self) -> Option<I::Item> {
2248 self.iter.nth(old_n)
2253 fn nth(&mut self, n: usize) -> Option<I::Item> {
2254 // Can't just add n + self.n due to overflow.
2256 let to_skip = self.n;
2259 self.iter.nth(to_skip - 1)?;
2265 fn count(mut self) -> usize {
2268 if self.iter.nth(self.n - 1).is_none() {
2276 fn last(mut self) -> Option<I::Item> {
2279 self.iter.nth(self.n - 1)?;
2285 fn size_hint(&self) -> (usize, Option<usize>) {
2286 let (lower, upper) = self.iter.size_hint();
2288 let lower = lower.saturating_sub(self.n);
2289 let upper = match upper {
2290 Some(x) => Some(x.saturating_sub(self.n)),
2298 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2301 Fold: FnMut(Acc, Self::Item) -> R,
2308 if self.iter.nth(n - 1).is_none() {
2309 return Try::from_ok(init);
2312 self.iter.try_fold(init, fold)
2316 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2318 Fold: FnMut(Acc, Self::Item) -> Acc,
2322 if self.iter.nth(self.n - 1).is_none() {
2326 self.iter.fold(init, fold)
2330 #[stable(feature = "rust1", since = "1.0.0")]
2331 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2333 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
2334 impl<I> DoubleEndedIterator for Skip<I>
2336 I: DoubleEndedIterator + ExactSizeIterator,
2338 fn next_back(&mut self) -> Option<Self::Item> {
2339 if self.len() > 0 { self.iter.next_back() } else { None }
2343 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
2344 let len = self.len();
2346 self.iter.nth_back(n)
2349 // consume the original iterator
2350 self.iter.nth_back(len - 1);
2356 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2359 Fold: FnMut(Acc, Self::Item) -> R,
2362 fn check<T, Acc, R: Try<Ok = Acc>>(
2364 mut fold: impl FnMut(Acc, T) -> R,
2365 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> {
2368 let r = fold(acc, x);
2369 if n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2377 self.iter.try_rfold(init, check(n, fold)).into_try()
2381 fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2383 Fold: FnMut(Acc, Self::Item) -> Acc,
2386 fn ok<Acc, T>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, T) -> Result<Acc, !> {
2387 move |acc, x| Ok(f(acc, x))
2390 self.try_rfold(init, ok(fold)).unwrap()
2394 #[stable(feature = "fused", since = "1.26.0")]
2395 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2397 #[unstable(issue = "none", feature = "inplace_iteration")]
2398 unsafe impl<S: Iterator, I: Iterator> SourceIter for Skip<I>
2400 I: SourceIter<Source = S>,
2405 unsafe fn as_inner(&mut self) -> &mut S {
2406 // Safety: unsafe function forwarding to unsafe function with the same requirements
2407 unsafe { SourceIter::as_inner(&mut self.iter) }
2411 #[unstable(issue = "none", feature = "inplace_iteration")]
2412 unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {}
2414 /// An iterator that only iterates over the first `n` iterations of `iter`.
2416 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2417 /// documentation for more.
2419 /// [`take`]: trait.Iterator.html#method.take
2420 /// [`Iterator`]: trait.Iterator.html
2421 #[derive(Clone, Debug)]
2422 #[must_use = "iterators are lazy and do nothing unless consumed"]
2423 #[stable(feature = "rust1", since = "1.0.0")]
2424 pub struct Take<I> {
2426 pub(super) n: usize,
2429 pub(super) fn new(iter: I, n: usize) -> Take<I> {
2434 #[stable(feature = "rust1", since = "1.0.0")]
2435 impl<I> Iterator for Take<I>
2439 type Item = <I as Iterator>::Item;
2442 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2452 fn nth(&mut self, n: usize) -> Option<I::Item> {
2458 self.iter.nth(self.n - 1);
2466 fn size_hint(&self) -> (usize, Option<usize>) {
2468 return (0, Some(0));
2471 let (lower, upper) = self.iter.size_hint();
2473 let lower = cmp::min(lower, self.n);
2475 let upper = match upper {
2476 Some(x) if x < self.n => Some(x),
2484 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2487 Fold: FnMut(Acc, Self::Item) -> R,
2490 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2492 mut fold: impl FnMut(Acc, T) -> R + 'a,
2493 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2496 let r = fold(acc, x);
2497 if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2504 let n = &mut self.n;
2505 self.iter.try_fold(init, check(n, fold)).into_try()
2510 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2513 Fold: FnMut(Acc, Self::Item) -> Acc,
2516 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2517 move |acc, x| Ok(f(acc, x))
2520 self.try_fold(init, ok(fold)).unwrap()
2524 #[unstable(issue = "none", feature = "inplace_iteration")]
2525 unsafe impl<S: Iterator, I: Iterator> SourceIter for Take<I>
2527 I: SourceIter<Source = S>,
2532 unsafe fn as_inner(&mut self) -> &mut S {
2533 // Safety: unsafe function forwarding to unsafe function with the same requirements
2534 unsafe { SourceIter::as_inner(&mut self.iter) }
2538 #[unstable(issue = "none", feature = "inplace_iteration")]
2539 unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> {}
2541 #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
2542 impl<I> DoubleEndedIterator for Take<I>
2544 I: DoubleEndedIterator + ExactSizeIterator,
2547 fn next_back(&mut self) -> Option<Self::Item> {
2553 self.iter.nth_back(self.iter.len().saturating_sub(n))
2558 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2559 let len = self.iter.len();
2561 let m = len.saturating_sub(self.n) + n;
2563 self.iter.nth_back(m)
2566 self.iter.nth_back(len - 1);
2573 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2576 Fold: FnMut(Acc, Self::Item) -> R,
2582 let len = self.iter.len();
2583 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2586 self.iter.try_rfold(init, fold)
2592 fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2595 Fold: FnMut(Acc, Self::Item) -> Acc,
2600 let len = self.iter.len();
2601 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2604 self.iter.rfold(init, fold)
2610 #[stable(feature = "rust1", since = "1.0.0")]
2611 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2613 #[stable(feature = "fused", since = "1.26.0")]
2614 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2616 #[unstable(feature = "trusted_len", issue = "37572")]
2617 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2619 /// An iterator to maintain state while iterating another iterator.
2621 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2622 /// documentation for more.
2624 /// [`scan`]: trait.Iterator.html#method.scan
2625 /// [`Iterator`]: trait.Iterator.html
2626 #[must_use = "iterators are lazy and do nothing unless consumed"]
2627 #[stable(feature = "rust1", since = "1.0.0")]
2629 pub struct Scan<I, St, F> {
2634 impl<I, St, F> Scan<I, St, F> {
2635 pub(super) fn new(iter: I, state: St, f: F) -> Scan<I, St, F> {
2636 Scan { iter, state, f }
2640 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2641 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2643 f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish()
2647 #[stable(feature = "rust1", since = "1.0.0")]
2648 impl<B, I, St, F> Iterator for Scan<I, St, F>
2651 F: FnMut(&mut St, I::Item) -> Option<B>,
2656 fn next(&mut self) -> Option<B> {
2657 let a = self.iter.next()?;
2658 (self.f)(&mut self.state, a)
2662 fn size_hint(&self) -> (usize, Option<usize>) {
2663 let (_, upper) = self.iter.size_hint();
2664 (0, upper) // can't know a lower bound, due to the scan function
2668 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2671 Fold: FnMut(Acc, Self::Item) -> R,
2674 fn scan<'a, T, St, B, Acc, R: Try<Ok = Acc>>(
2676 f: &'a mut impl FnMut(&mut St, T) -> Option<B>,
2677 mut fold: impl FnMut(Acc, B) -> R + 'a,
2678 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2679 move |acc, x| match f(state, x) {
2680 None => ControlFlow::Break(Try::from_ok(acc)),
2681 Some(x) => ControlFlow::from_try(fold(acc, x)),
2685 let state = &mut self.state;
2686 let f = &mut self.f;
2687 self.iter.try_fold(init, scan(state, f, fold)).into_try()
2691 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2694 Fold: FnMut(Acc, Self::Item) -> Acc,
2697 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2698 move |acc, x| Ok(f(acc, x))
2701 self.try_fold(init, ok(fold)).unwrap()
2705 #[unstable(issue = "none", feature = "inplace_iteration")]
2706 unsafe impl<St, F, B, S: Iterator, I: Iterator> SourceIter for Scan<I, St, F>
2708 I: SourceIter<Source = S>,
2709 F: FnMut(&mut St, I::Item) -> Option<B>,
2714 unsafe fn as_inner(&mut self) -> &mut S {
2715 // Safety: unsafe function forwarding to unsafe function with the same requirements
2716 unsafe { SourceIter::as_inner(&mut self.iter) }
2720 #[unstable(issue = "none", feature = "inplace_iteration")]
2721 unsafe impl<St, F, B, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F> where
2722 F: FnMut(&mut St, I::Item) -> Option<B>
2726 /// An iterator that calls a function with a reference to each element before
2729 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2730 /// documentation for more.
2732 /// [`inspect`]: trait.Iterator.html#method.inspect
2733 /// [`Iterator`]: trait.Iterator.html
2734 #[must_use = "iterators are lazy and do nothing unless consumed"]
2735 #[stable(feature = "rust1", since = "1.0.0")]
2737 pub struct Inspect<I, F> {
2741 impl<I, F> Inspect<I, F> {
2742 pub(super) fn new(iter: I, f: F) -> Inspect<I, F> {
2747 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2748 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2749 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2750 f.debug_struct("Inspect").field("iter", &self.iter).finish()
2754 impl<I: Iterator, F> Inspect<I, F>
2759 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2760 if let Some(ref a) = elt {
2768 fn inspect_fold<T, Acc>(
2769 mut f: impl FnMut(&T),
2770 mut fold: impl FnMut(Acc, T) -> Acc,
2771 ) -> impl FnMut(Acc, T) -> Acc {
2778 fn inspect_try_fold<'a, T, Acc, R>(
2779 f: &'a mut impl FnMut(&T),
2780 mut fold: impl FnMut(Acc, T) -> R + 'a,
2781 ) -> impl FnMut(Acc, T) -> R + 'a {
2788 #[stable(feature = "rust1", since = "1.0.0")]
2789 impl<I: Iterator, F> Iterator for Inspect<I, F>
2793 type Item = I::Item;
2796 fn next(&mut self) -> Option<I::Item> {
2797 let next = self.iter.next();
2798 self.do_inspect(next)
2802 fn size_hint(&self) -> (usize, Option<usize>) {
2803 self.iter.size_hint()
2807 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2810 Fold: FnMut(Acc, Self::Item) -> R,
2813 self.iter.try_fold(init, inspect_try_fold(&mut self.f, fold))
2817 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2819 Fold: FnMut(Acc, Self::Item) -> Acc,
2821 self.iter.fold(init, inspect_fold(self.f, fold))
2825 #[stable(feature = "rust1", since = "1.0.0")]
2826 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2831 fn next_back(&mut self) -> Option<I::Item> {
2832 let next = self.iter.next_back();
2833 self.do_inspect(next)
2837 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2840 Fold: FnMut(Acc, Self::Item) -> R,
2843 self.iter.try_rfold(init, inspect_try_fold(&mut self.f, fold))
2847 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2849 Fold: FnMut(Acc, Self::Item) -> Acc,
2851 self.iter.rfold(init, inspect_fold(self.f, fold))
2855 #[stable(feature = "rust1", since = "1.0.0")]
2856 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2860 fn len(&self) -> usize {
2864 fn is_empty(&self) -> bool {
2865 self.iter.is_empty()
2869 #[stable(feature = "fused", since = "1.26.0")]
2870 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F> where F: FnMut(&I::Item) {}
2872 #[unstable(issue = "none", feature = "inplace_iteration")]
2873 unsafe impl<S: Iterator, I: Iterator, F> SourceIter for Inspect<I, F>
2876 I: SourceIter<Source = S>,
2881 unsafe fn as_inner(&mut self) -> &mut S {
2882 // Safety: unsafe function forwarding to unsafe function with the same requirements
2883 unsafe { SourceIter::as_inner(&mut self.iter) }
2887 #[unstable(issue = "none", feature = "inplace_iteration")]
2888 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Inspect<I, F> where F: FnMut(&I::Item) {}
2890 /// An iterator adapter that produces output as long as the underlying
2891 /// iterator produces `Result::Ok` values.
2893 /// If an error is encountered, the iterator stops and the error is
2895 pub(crate) struct ResultShunt<'a, I, E> {
2897 error: &'a mut Result<(), E>,
2900 /// Process the given iterator as if it yielded a `T` instead of a
2901 /// `Result<T, _>`. Any errors will stop the inner iterator and
2902 /// the overall result will be an error.
2903 pub(crate) fn process_results<I, T, E, F, U>(iter: I, mut f: F) -> Result<U, E>
2905 I: Iterator<Item = Result<T, E>>,
2906 for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U,
2908 let mut error = Ok(());
2909 let shunt = ResultShunt { iter, error: &mut error };
2910 let value = f(shunt);
2911 error.map(|()| value)
2914 impl<I, T, E> Iterator for ResultShunt<'_, I, E>
2916 I: Iterator<Item = Result<T, E>>,
2920 fn next(&mut self) -> Option<Self::Item> {
2924 fn size_hint(&self) -> (usize, Option<usize>) {
2925 if self.error.is_err() {
2928 let (_, upper) = self.iter.size_hint();
2933 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2935 F: FnMut(B, Self::Item) -> R,
2938 let error = &mut *self.error;
2940 .try_fold(init, |acc, x| match x {
2941 Ok(x) => ControlFlow::from_try(f(acc, x)),
2944 ControlFlow::Break(Try::from_ok(acc))
2950 fn fold<B, F>(mut self, init: B, fold: F) -> B
2953 F: FnMut(B, Self::Item) -> B,
2956 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2957 move |acc, x| Ok(f(acc, x))
2960 self.try_fold(init, ok(fold)).unwrap()