2 use crate::iter::{adapters::SourceIter, InPlaceIterable};
3 use crate::ops::{ControlFlow, Try};
5 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
7 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`map_while`]: Iterator::map_while
11 /// [`Iterator`]: trait.Iterator.html
12 #[must_use = "iterators are lazy and do nothing unless consumed"]
13 #[stable(feature = "iter_map_while", since = "1.57.0")]
15 pub struct MapWhile<I, P> {
20 impl<I, P> MapWhile<I, P> {
21 pub(in crate::iter) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
22 MapWhile { iter, predicate }
26 #[stable(feature = "iter_map_while", since = "1.57.0")]
27 impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 f.debug_struct("MapWhile").field("iter", &self.iter).finish()
33 #[stable(feature = "iter_map_while", since = "1.57.0")]
34 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
36 P: FnMut(I::Item) -> Option<B>,
41 fn next(&mut self) -> Option<B> {
42 let x = self.iter.next()?;
47 fn size_hint(&self) -> (usize, Option<usize>) {
48 let (_, upper) = self.iter.size_hint();
49 (0, upper) // can't know a lower bound, due to the predicate
53 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
56 Fold: FnMut(Acc, Self::Item) -> R,
59 let Self { iter, predicate } = self;
60 iter.try_fold(init, |acc, x| match predicate(x) {
61 Some(item) => ControlFlow::from_try(fold(acc, item)),
62 None => ControlFlow::Break(try { acc }),
67 impl_fold_via_try_fold! { fold -> try_fold }
70 #[unstable(issue = "none", feature = "inplace_iteration")]
71 unsafe impl<I, P> SourceIter for MapWhile<I, P>
75 type Source = I::Source;
78 unsafe fn as_inner(&mut self) -> &mut I::Source {
79 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
80 unsafe { SourceIter::as_inner(&mut self.iter) }
84 #[unstable(issue = "none", feature = "inplace_iteration")]
85 unsafe impl<B, I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> where
86 P: FnMut(I::Item) -> Option<B>