2 use crate::iter::adapters::{
3 zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce,
5 use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
8 /// An iterator that maps the values of `iter` with `f`.
10 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
11 /// documentation for more.
13 /// [`map`]: Iterator::map
14 /// [`Iterator`]: trait.Iterator.html
16 /// # Notes about side effects
18 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
19 /// you can also [`map`] backwards:
22 /// let v: Vec<i32> = [1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
24 /// assert_eq!(v, [4, 3, 2]);
27 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
29 /// But if your closure has state, iterating backwards may act in a way you do
30 /// not expect. Let's go through an example. First, in the forward direction:
35 /// for pair in ['a', 'b', 'c'].into_iter()
36 /// .map(|letter| { c += 1; (letter, c) }) {
37 /// println!("{pair:?}");
41 /// This will print `('a', 1), ('b', 2), ('c', 3)`.
43 /// Now consider this twist where we add a call to `rev`. This version will
44 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
45 /// but the values of the counter still go in order. This is because `map()` is
46 /// still being called lazily on each item, but we are popping items off the
47 /// back of the vector now, instead of shifting them from the front.
52 /// for pair in ['a', 'b', 'c'].into_iter()
53 /// .map(|letter| { c += 1; (letter, c) })
55 /// println!("{pair:?}");
58 #[must_use = "iterators are lazy and do nothing unless consumed"]
59 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Map<I, F> {
62 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
67 impl<I, F> Map<I, F> {
68 pub(in crate::iter) fn new(iter: I, f: F) -> Map<I, F> {
73 #[stable(feature = "core_impl_debug", since = "1.9.0")]
74 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.debug_struct("Map").field("iter", &self.iter).finish()
80 fn map_fold<T, B, Acc>(
81 mut f: impl FnMut(T) -> B,
82 mut g: impl FnMut(Acc, B) -> Acc,
83 ) -> impl FnMut(Acc, T) -> Acc {
84 move |acc, elt| g(acc, f(elt))
87 fn map_try_fold<'a, T, B, Acc, R>(
88 f: &'a mut impl FnMut(T) -> B,
89 mut g: impl FnMut(Acc, B) -> R + 'a,
90 ) -> impl FnMut(Acc, T) -> R + 'a {
91 move |acc, elt| g(acc, f(elt))
94 #[stable(feature = "rust1", since = "1.0.0")]
95 impl<B, I: Iterator, F> Iterator for Map<I, F>
97 F: FnMut(I::Item) -> B,
102 fn next(&mut self) -> Option<B> {
103 self.iter.next().map(&mut self.f)
107 fn size_hint(&self) -> (usize, Option<usize>) {
108 self.iter.size_hint()
111 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
114 G: FnMut(Acc, Self::Item) -> R,
115 R: Try<Output = Acc>,
117 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
120 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
122 G: FnMut(Acc, Self::Item) -> Acc,
124 self.iter.fold(init, map_fold(self.f, g))
128 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
130 Self: TrustedRandomAccessNoCoerce,
132 // SAFETY: the caller must uphold the contract for
133 // `Iterator::__iterator_get_unchecked`.
134 unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
141 F: FnMut(I::Item) -> B,
144 fn next_back(&mut self) -> Option<B> {
145 self.iter.next_back().map(&mut self.f)
148 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
151 G: FnMut(Acc, Self::Item) -> R,
152 R: Try<Output = Acc>,
154 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
157 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
159 G: FnMut(Acc, Self::Item) -> Acc,
161 self.iter.rfold(init, map_fold(self.f, g))
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
168 F: FnMut(I::Item) -> B,
170 fn len(&self) -> usize {
174 fn is_empty(&self) -> bool {
179 #[stable(feature = "fused", since = "1.26.0")]
180 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
182 #[unstable(feature = "trusted_len", issue = "37572")]
183 unsafe impl<B, I, F> TrustedLen for Map<I, F>
186 F: FnMut(I::Item) -> B,
191 #[unstable(feature = "trusted_random_access", issue = "none")]
192 unsafe impl<I, F> TrustedRandomAccess for Map<I, F> where I: TrustedRandomAccess {}
195 #[unstable(feature = "trusted_random_access", issue = "none")]
196 unsafe impl<I, F> TrustedRandomAccessNoCoerce for Map<I, F>
198 I: TrustedRandomAccessNoCoerce,
200 const MAY_HAVE_SIDE_EFFECT: bool = true;
203 #[unstable(issue = "none", feature = "inplace_iteration")]
204 unsafe impl<I, F> SourceIter for Map<I, F>
208 type Source = I::Source;
211 unsafe fn as_inner(&mut self) -> &mut I::Source {
212 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
213 unsafe { SourceIter::as_inner(&mut self.iter) }
217 #[unstable(issue = "none", feature = "inplace_iteration")]
218 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for Map<I, F> where F: FnMut(I::Item) -> B {}