]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/adapters/map_while.rs
Auto merge of #89123 - the8472:push_in_capacity, r=amanieu
[rust.git] / library / core / src / iter / adapters / map_while.rs
1 use crate::fmt;
2 use crate::iter::{adapters::SourceIter, InPlaceIterable};
3 use crate::ops::{ControlFlow, Try};
4
5 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
6 ///
7 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
8 /// documentation for more.
9 ///
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")]
14 #[derive(Clone)]
15 pub struct MapWhile<I, P> {
16     iter: I,
17     predicate: P,
18 }
19
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 }
23     }
24 }
25
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()
30     }
31 }
32
33 #[stable(feature = "iter_map_while", since = "1.57.0")]
34 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
35 where
36     P: FnMut(I::Item) -> Option<B>,
37 {
38     type Item = B;
39
40     #[inline]
41     fn next(&mut self) -> Option<B> {
42         let x = self.iter.next()?;
43         (self.predicate)(x)
44     }
45
46     #[inline]
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
50     }
51
52     #[inline]
53     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
54     where
55         Self: Sized,
56         Fold: FnMut(Acc, Self::Item) -> R,
57         R: Try<Output = Acc>,
58     {
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 }),
63         })
64         .into_try()
65     }
66
67     impl_fold_via_try_fold! { fold -> try_fold }
68 }
69
70 #[unstable(issue = "none", feature = "inplace_iteration")]
71 unsafe impl<I, P> SourceIter for MapWhile<I, P>
72 where
73     I: SourceIter,
74 {
75     type Source = I::Source;
76
77     #[inline]
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) }
81     }
82 }
83
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>
87 {
88 }