1use crate::fmt;
2use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
3use crate::num::NonZero;
4use crate::ops::{ControlFlow, Try};
5
6/// An iterator that only accepts elements while `predicate` returns `true`.
7///
8/// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
9/// documentation for more.
10///
11/// [`take_while`]: Iterator::take_while
12/// [`Iterator`]: trait.Iterator.html
13#[must_use = "iterators are lazy and do nothing unless consumed"]
14#[stable(feature = "rust1", since = "1.0.0")]
15#[derive(Clone)]
16pub struct TakeWhile<I, P> {
17 iter: I,
18 flag: bool,
19 predicate: P,
20}
21
22impl<I, P> TakeWhile<I, P> {
23 pub(in crate::iter) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
24 TakeWhile { iter, flag: false, predicate }
25 }
26}
27
28#[stable(feature = "core_impl_debug", since = "1.9.0")]
29impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.debug_struct("TakeWhile").field("iter", &self.iter).field(name:"flag", &self.flag).finish()
32 }
33}
34
35#[stable(feature = "rust1", since = "1.0.0")]
36impl<I: Iterator, P> Iterator for TakeWhile<I, P>
37where
38 P: FnMut(&I::Item) -> bool,
39{
40 type Item = I::Item;
41
42 #[inline]
43 fn next(&mut self) -> Option<I::Item> {
44 if self.flag {
45 None
46 } else {
47 let x = self.iter.next()?;
48 if (self.predicate)(&x) {
49 Some(x)
50 } else {
51 self.flag = true;
52 None
53 }
54 }
55 }
56
57 #[inline]
58 fn size_hint(&self) -> (usize, Option<usize>) {
59 if self.flag {
60 (0, Some(0))
61 } else {
62 let (_, upper) = self.iter.size_hint();
63 (0, upper) // can't know a lower bound, due to the predicate
64 }
65 }
66
67 #[inline]
68 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
69 where
70 Self: Sized,
71 Fold: FnMut(Acc, Self::Item) -> R,
72 R: Try<Output = Acc>,
73 {
74 fn check<'a, T, Acc, R: Try<Output = Acc>>(
75 flag: &'a mut bool,
76 p: &'a mut impl FnMut(&T) -> bool,
77 mut fold: impl FnMut(Acc, T) -> R + 'a,
78 ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> + 'a {
79 move |acc, x| {
80 if p(&x) {
81 ControlFlow::from_try(fold(acc, x))
82 } else {
83 *flag = true;
84 ControlFlow::Break(try { acc })
85 }
86 }
87 }
88
89 if self.flag {
90 try { init }
91 } else {
92 let flag = &mut self.flag;
93 let p = &mut self.predicate;
94 self.iter.try_fold(init, check(flag, p, fold)).into_try()
95 }
96 }
97
98 impl_fold_via_try_fold! { fold -> try_fold }
99}
100
101#[stable(feature = "fused", since = "1.26.0")]
102impl<I, P> FusedIterator for TakeWhile<I, P>
103where
104 I: FusedIterator,
105 P: FnMut(&I::Item) -> bool,
106{
107}
108
109#[unstable(issue = "none", feature = "trusted_fused")]
110unsafe impl<I: TrustedFused, P> TrustedFused for TakeWhile<I, P> {}
111
112#[unstable(issue = "none", feature = "inplace_iteration")]
113unsafe impl<P, I> SourceIter for TakeWhile<I, P>
114where
115 I: SourceIter,
116{
117 type Source = I::Source;
118
119 #[inline]
120 unsafe fn as_inner(&mut self) -> &mut I::Source {
121 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
122 unsafe { SourceIter::as_inner(&mut self.iter) }
123 }
124}
125
126#[unstable(issue = "none", feature = "inplace_iteration")]
127unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> {
128 const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
129 const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
130}
131