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 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
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 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
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 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
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 }),
68 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
71 Fold: FnMut(Acc, Self::Item) -> Acc,
74 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
75 move |acc, x| Ok(f(acc, x))
78 self.try_fold(init, ok(fold)).unwrap()
82 #[unstable(issue = "none", feature = "inplace_iteration")]
83 unsafe impl<S: Iterator, B, I: Iterator, P> SourceIter for MapWhile<I, P>
85 P: FnMut(I::Item) -> Option<B>,
86 I: SourceIter<Source = S>,
91 unsafe fn as_inner(&mut self) -> &mut S {
92 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
93 unsafe { SourceIter::as_inner(&mut self.iter) }
97 #[unstable(issue = "none", feature = "inplace_iteration")]
98 unsafe impl<B, I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> where
99 P: FnMut(I::Item) -> Option<B>