Skip to main content

core/iter/adapters/
map.rs

1use crate::fmt;
2use crate::iter::adapters::zip::try_get_unchecked;
3use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
4use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen};
5use crate::num::NonZero;
6use crate::ops::Try;
7
8/// An iterator that maps the values of `iter` with `f`.
9///
10/// This `struct` is created by the [`map`] method on [`Iterator`]. See its
11/// documentation for more.
12///
13/// [`map`]: Iterator::map
14/// [`Iterator`]: trait.Iterator.html
15///
16/// # Notes about side effects
17///
18/// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
19/// you can also [`map`] backwards:
20///
21/// ```rust
22/// let v: Vec<i32> = [1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
23///
24/// assert_eq!(v, [4, 3, 2]);
25/// ```
26///
27/// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
28///
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:
31///
32/// ```rust
33/// let mut c = 0;
34///
35/// for pair in ['a', 'b', 'c'].into_iter()
36///                                .map(|letter| { c += 1; (letter, c) }) {
37///     println!("{pair:?}");
38/// }
39/// ```
40///
41/// This will print `('a', 1), ('b', 2), ('c', 3)`.
42///
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.
48///
49/// ```rust
50/// let mut c = 0;
51///
52/// for pair in ['a', 'b', 'c'].into_iter()
53///                                .map(|letter| { c += 1; (letter, c) })
54///                                .rev() {
55///     println!("{pair:?}");
56/// }
57/// ```
58#[must_use = "iterators are lazy and do nothing unless consumed"]
59#[stable(feature = "rust1", since = "1.0.0")]
60#[derive(Clone)]
61#[ferrocene::prevalidated]
62pub struct Map<I, F> {
63    // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
64    pub(crate) iter: I,
65    f: F,
66}
67
68impl<I, F> Map<I, F> {
69    #[ferrocene::prevalidated]
70    pub(in crate::iter) const fn new(iter: I, f: F) -> Map<I, F> {
71        Map { iter, f }
72    }
73
74    #[ferrocene::prevalidated]
75    pub(crate) fn into_inner(self) -> I {
76        self.iter
77    }
78}
79
80#[stable(feature = "core_impl_debug", since = "1.9.0")]
81impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
82    #[ferrocene::prevalidated]
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.debug_struct("Map").field("iter", &self.iter).finish()
85    }
86}
87
88#[ferrocene::prevalidated]
89fn map_fold<T, B, Acc>(
90    mut f: impl FnMut(T) -> B,
91    mut g: impl FnMut(Acc, B) -> Acc,
92) -> impl FnMut(Acc, T) -> Acc {
93    move |acc, elt| g(acc, f(elt))
94}
95
96#[ferrocene::prevalidated]
97fn map_try_fold<'a, T, B, Acc, R>(
98    f: &'a mut impl FnMut(T) -> B,
99    mut g: impl FnMut(Acc, B) -> R + 'a,
100) -> impl FnMut(Acc, T) -> R + 'a {
101    move |acc, elt| g(acc, f(elt))
102}
103
104#[stable(feature = "rust1", since = "1.0.0")]
105impl<B, I: Iterator, F> Iterator for Map<I, F>
106where
107    F: FnMut(I::Item) -> B,
108{
109    type Item = B;
110
111    #[inline]
112    #[ferrocene::prevalidated]
113    fn next(&mut self) -> Option<B> {
114        self.iter.next().map(&mut self.f)
115    }
116
117    #[inline]
118    #[ferrocene::prevalidated]
119    fn size_hint(&self) -> (usize, Option<usize>) {
120        self.iter.size_hint()
121    }
122
123    #[ferrocene::prevalidated]
124    #[inline]
125    fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
126    where
127        Self: Sized,
128        G: FnMut(Acc, Self::Item) -> R,
129        R: Try<Output = Acc>,
130    {
131        self.iter.try_fold(init, map_try_fold(&mut self.f, g))
132    }
133
134    #[ferrocene::prevalidated]
135    #[inline]
136    fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
137    where
138        G: FnMut(Acc, Self::Item) -> Acc,
139    {
140        self.iter.fold(init, map_fold(self.f, g))
141    }
142
143    #[inline]
144    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
145    where
146        Self: TrustedRandomAccessNoCoerce,
147    {
148        // SAFETY: the caller must uphold the contract for
149        // `Iterator::__iterator_get_unchecked`.
150        unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
151    }
152}
153
154#[stable(feature = "rust1", since = "1.0.0")]
155impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
156where
157    F: FnMut(I::Item) -> B,
158{
159    #[inline]
160    #[ferrocene::prevalidated]
161    fn next_back(&mut self) -> Option<B> {
162        self.iter.next_back().map(&mut self.f)
163    }
164
165    #[ferrocene::prevalidated]
166    #[inline]
167    fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
168    where
169        Self: Sized,
170        G: FnMut(Acc, Self::Item) -> R,
171        R: Try<Output = Acc>,
172    {
173        self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
174    }
175
176    #[ferrocene::prevalidated]
177    #[inline]
178    fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
179    where
180        G: FnMut(Acc, Self::Item) -> Acc,
181    {
182        self.iter.rfold(init, map_fold(self.f, g))
183    }
184}
185
186#[stable(feature = "rust1", since = "1.0.0")]
187impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
188where
189    F: FnMut(I::Item) -> B,
190{
191    fn len(&self) -> usize {
192        self.iter.len()
193    }
194
195    fn is_empty(&self) -> bool {
196        self.iter.is_empty()
197    }
198}
199
200#[stable(feature = "fused", since = "1.26.0")]
201impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
202
203#[unstable(issue = "none", feature = "trusted_fused")]
204unsafe impl<I: TrustedFused, F> TrustedFused for Map<I, F> {}
205
206#[unstable(feature = "trusted_len", issue = "37572")]
207unsafe impl<B, I, F> TrustedLen for Map<I, F>
208where
209    I: TrustedLen,
210    F: FnMut(I::Item) -> B,
211{
212}
213
214#[doc(hidden)]
215#[unstable(feature = "trusted_random_access", issue = "none")]
216unsafe impl<I, F> TrustedRandomAccess for Map<I, F> where I: TrustedRandomAccess {}
217
218#[doc(hidden)]
219#[unstable(feature = "trusted_random_access", issue = "none")]
220unsafe impl<I, F> TrustedRandomAccessNoCoerce for Map<I, F>
221where
222    I: TrustedRandomAccessNoCoerce,
223{
224    const MAY_HAVE_SIDE_EFFECT: bool = true;
225}
226
227#[unstable(issue = "none", feature = "inplace_iteration")]
228unsafe impl<I, F> SourceIter for Map<I, F>
229where
230    I: SourceIter,
231{
232    type Source = I::Source;
233
234    #[inline]
235    unsafe fn as_inner(&mut self) -> &mut I::Source {
236        // SAFETY: unsafe function forwarding to unsafe function with the same requirements
237        unsafe { SourceIter::as_inner(&mut self.iter) }
238    }
239}
240
241#[unstable(issue = "none", feature = "inplace_iteration")]
242unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Map<I, F> {
243    const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
244    const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
245}