1use crate::fmt;
2use crate::iter::{adapters::SourceIter, InPlaceIterable};
3use crate::num::NonZero;
4use crate::ops::{ControlFlow, Try};
5
6/// An iterator that only accepts elements while `predicate` returns `Some(_)`.
7///
8/// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
9/// documentation for more.
10///
11/// [`map_while`]: Iterator::map_while
12/// [`Iterator`]: trait.Iterator.html
13#[must_use = "iterators are lazy and do nothing unless consumed"]
14#[stable(feature = "iter_map_while", since = "1.57.0")]
15#[derive(Clone)]
16pub struct MapWhile<I, P> {
17 iter: I,
18 predicate: P,
19}
20
21impl<I, P> MapWhile<I, P> {
22 pub(in crate::iter) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
23 MapWhile { iter, predicate }
24 }
25}
26
27#[stable(feature = "iter_map_while", since = "1.57.0")]
28impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 f.debug_struct("MapWhile").field(name:"iter", &self.iter).finish()
31 }
32}
33
34#[stable(feature = "iter_map_while", since = "1.57.0")]
35impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
36where
37 P: FnMut(I::Item) -> Option<B>,
38{
39 type Item = B;
40
41 #[inline]
42 fn next(&mut self) -> Option<B> {
43 let x = self.iter.next()?;
44 (self.predicate)(x)
45 }
46
47 #[inline]
48 fn size_hint(&self) -> (usize, Option<usize>) {
49 let (_, upper) = self.iter.size_hint();
50 (0, upper) // can't know a lower bound, due to the predicate
51 }
52
53 #[inline]
54 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
55 where
56 Self: Sized,
57 Fold: FnMut(Acc, Self::Item) -> R,
58 R: Try<Output = Acc>,
59 {
60 let Self { iter, predicate } = self;
61 iter.try_fold(init, |acc, x| match predicate(x) {
62 Some(item) => ControlFlow::from_try(fold(acc, item)),
63 None => ControlFlow::Break(try { acc }),
64 })
65 .into_try()
66 }
67
68 impl_fold_via_try_fold! { fold -> try_fold }
69}
70
71#[unstable(issue = "none", feature = "inplace_iteration")]
72unsafe impl<I, P> SourceIter for MapWhile<I, P>
73where
74 I: SourceIter,
75{
76 type Source = I::Source;
77
78 #[inline]
79 unsafe fn as_inner(&mut self) -> &mut I::Source {
80 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
81 unsafe { SourceIter::as_inner(&mut self.iter) }
82 }
83}
84
85#[unstable(issue = "none", feature = "inplace_iteration")]
86unsafe impl<I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> {
87 const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
88 const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
89}
90