2 use crate::iter::adapters::{zip::try_get_unchecked, SourceIter, TrustedRandomAccess};
3 use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
6 /// An iterator that maps the values of `iter` with `f`.
8 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
9 /// documentation for more.
11 /// [`map`]: Iterator::map
12 /// [`Iterator`]: trait.Iterator.html
14 /// # Notes about side effects
16 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
17 /// you can also [`map`] backwards:
20 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
22 /// assert_eq!(v, [4, 3, 2]);
25 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
27 /// But if your closure has state, iterating backwards may act in a way you do
28 /// not expect. Let's go through an example. First, in the forward direction:
33 /// for pair in vec!['a', 'b', 'c'].into_iter()
34 /// .map(|letter| { c += 1; (letter, c) }) {
35 /// println!("{:?}", pair);
39 /// This will print "('a', 1), ('b', 2), ('c', 3)".
41 /// Now consider this twist where we add a call to `rev`. This version will
42 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
43 /// but the values of the counter still go in order. This is because `map()` is
44 /// still being called lazily on each item, but we are popping items off the
45 /// back of the vector now, instead of shifting them from the front.
50 /// for pair in vec!['a', 'b', 'c'].into_iter()
51 /// .map(|letter| { c += 1; (letter, c) })
53 /// println!("{:?}", pair);
56 #[must_use = "iterators are lazy and do nothing unless consumed"]
57 #[stable(feature = "rust1", since = "1.0.0")]
59 pub struct Map<I, F> {
63 impl<I, F> Map<I, F> {
64 pub(in crate::iter) fn new(iter: I, f: F) -> Map<I, F> {
69 #[stable(feature = "core_impl_debug", since = "1.9.0")]
70 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.debug_struct("Map").field("iter", &self.iter).finish()
76 fn map_fold<T, B, Acc>(
77 mut f: impl FnMut(T) -> B,
78 mut g: impl FnMut(Acc, B) -> Acc,
79 ) -> impl FnMut(Acc, T) -> Acc {
80 move |acc, elt| g(acc, f(elt))
83 fn map_try_fold<'a, T, B, Acc, R>(
84 f: &'a mut impl FnMut(T) -> B,
85 mut g: impl FnMut(Acc, B) -> R + 'a,
86 ) -> impl FnMut(Acc, T) -> R + 'a {
87 move |acc, elt| g(acc, f(elt))
90 #[stable(feature = "rust1", since = "1.0.0")]
91 impl<B, I: Iterator, F> Iterator for Map<I, F>
93 F: FnMut(I::Item) -> B,
98 fn next(&mut self) -> Option<B> {
99 self.iter.next().map(&mut self.f)
103 fn size_hint(&self) -> (usize, Option<usize>) {
104 self.iter.size_hint()
107 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
110 G: FnMut(Acc, Self::Item) -> R,
113 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
116 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
118 G: FnMut(Acc, Self::Item) -> Acc,
120 self.iter.fold(init, map_fold(self.f, g))
123 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
125 Self: TrustedRandomAccess,
127 // SAFETY: the caller must uphold the contract for
128 // `Iterator::__iterator_get_unchecked`.
129 unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
136 F: FnMut(I::Item) -> B,
139 fn next_back(&mut self) -> Option<B> {
140 self.iter.next_back().map(&mut self.f)
143 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
146 G: FnMut(Acc, Self::Item) -> R,
149 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
152 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
154 G: FnMut(Acc, Self::Item) -> Acc,
156 self.iter.rfold(init, map_fold(self.f, g))
160 #[stable(feature = "rust1", since = "1.0.0")]
161 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
163 F: FnMut(I::Item) -> B,
165 fn len(&self) -> usize {
169 fn is_empty(&self) -> bool {
174 #[stable(feature = "fused", since = "1.26.0")]
175 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
177 #[unstable(feature = "trusted_len", issue = "37572")]
178 unsafe impl<B, I, F> TrustedLen for Map<I, F>
181 F: FnMut(I::Item) -> B,
186 #[unstable(feature = "trusted_random_access", issue = "none")]
187 unsafe impl<I, F> TrustedRandomAccess for Map<I, F>
189 I: TrustedRandomAccess,
192 fn may_have_side_effect() -> bool {
197 #[unstable(issue = "none", feature = "inplace_iteration")]
198 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for Map<I, F>
200 F: FnMut(I::Item) -> B,
201 I: SourceIter<Source = S>,
206 unsafe fn as_inner(&mut self) -> &mut S {
207 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
208 unsafe { SourceIter::as_inner(&mut self.iter) }
212 #[unstable(issue = "none", feature = "inplace_iteration")]
213 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for Map<I, F> where F: FnMut(I::Item) -> B {}