2 use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable};
3 use crate::ops::{ControlFlow, Try};
5 /// An iterator that only accepts elements while `predicate` returns `true`.
7 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`take_while`]: Iterator::take_while
11 /// [`Iterator`]: trait.Iterator.html
12 #[must_use = "iterators are lazy and do nothing unless consumed"]
13 #[stable(feature = "rust1", since = "1.0.0")]
15 pub struct TakeWhile<I, P> {
21 impl<I, P> TakeWhile<I, P> {
22 pub(in crate::iter) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
23 TakeWhile { iter, flag: false, predicate }
27 #[stable(feature = "core_impl_debug", since = "1.9.0")]
28 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
34 #[stable(feature = "rust1", since = "1.0.0")]
35 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
37 P: FnMut(&I::Item) -> bool,
42 fn next(&mut self) -> Option<I::Item> {
46 let x = self.iter.next()?;
47 if (self.predicate)(&x) {
57 fn size_hint(&self) -> (usize, Option<usize>) {
61 let (_, upper) = self.iter.size_hint();
62 (0, upper) // can't know a lower bound, due to the predicate
67 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
70 Fold: FnMut(Acc, Self::Item) -> R,
73 fn check<'a, T, Acc, R: Try<Output = Acc>>(
75 p: &'a mut impl FnMut(&T) -> bool,
76 mut fold: impl FnMut(Acc, T) -> R + 'a,
77 ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> + 'a {
80 ControlFlow::from_try(fold(acc, x))
83 ControlFlow::Break(try { acc })
91 let flag = &mut self.flag;
92 let p = &mut self.predicate;
93 self.iter.try_fold(init, check(flag, p, fold)).into_try()
97 impl_fold_via_try_fold! { fold -> try_fold }
100 #[stable(feature = "fused", since = "1.26.0")]
101 impl<I, P> FusedIterator for TakeWhile<I, P>
104 P: FnMut(&I::Item) -> bool,
108 #[unstable(issue = "none", feature = "inplace_iteration")]
109 unsafe impl<P, I> SourceIter for TakeWhile<I, P>
113 type Source = I::Source;
116 unsafe fn as_inner(&mut self) -> &mut I::Source {
117 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
118 unsafe { SourceIter::as_inner(&mut self.iter) }
122 #[unstable(issue = "none", feature = "inplace_iteration")]
123 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> where
124 F: FnMut(&I::Item) -> bool