]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/adapters/map.rs
Rollup merge of #79293 - Havvy:test-eval-order-compound-assign, r=Mark-Simulacrum
[rust.git] / library / core / src / iter / adapters / map.rs
1 use crate::fmt;
2 use crate::iter::adapters::{zip::try_get_unchecked, SourceIter, TrustedRandomAccess};
3 use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
4 use crate::ops::Try;
5
6 /// An iterator that maps the values of `iter` with `f`.
7 ///
8 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
9 /// documentation for more.
10 ///
11 /// [`map`]: Iterator::map
12 /// [`Iterator`]: trait.Iterator.html
13 ///
14 /// # Notes about side effects
15 ///
16 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
17 /// you can also [`map`] backwards:
18 ///
19 /// ```rust
20 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
21 ///
22 /// assert_eq!(v, [4, 3, 2]);
23 /// ```
24 ///
25 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
26 ///
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:
29 ///
30 /// ```rust
31 /// let mut c = 0;
32 ///
33 /// for pair in vec!['a', 'b', 'c'].into_iter()
34 ///                                .map(|letter| { c += 1; (letter, c) }) {
35 ///     println!("{:?}", pair);
36 /// }
37 /// ```
38 ///
39 /// This will print "('a', 1), ('b', 2), ('c', 3)".
40 ///
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.
46 ///
47 /// ```rust
48 /// let mut c = 0;
49 ///
50 /// for pair in vec!['a', 'b', 'c'].into_iter()
51 ///                                .map(|letter| { c += 1; (letter, c) })
52 ///                                .rev() {
53 ///     println!("{:?}", pair);
54 /// }
55 /// ```
56 #[must_use = "iterators are lazy and do nothing unless consumed"]
57 #[stable(feature = "rust1", since = "1.0.0")]
58 #[derive(Clone)]
59 pub struct Map<I, F> {
60     iter: I,
61     f: F,
62 }
63 impl<I, F> Map<I, F> {
64     pub(in crate::iter) fn new(iter: I, f: F) -> Map<I, F> {
65         Map { iter, f }
66     }
67 }
68
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()
73     }
74 }
75
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))
81 }
82
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))
88 }
89
90 #[stable(feature = "rust1", since = "1.0.0")]
91 impl<B, I: Iterator, F> Iterator for Map<I, F>
92 where
93     F: FnMut(I::Item) -> B,
94 {
95     type Item = B;
96
97     #[inline]
98     fn next(&mut self) -> Option<B> {
99         self.iter.next().map(&mut self.f)
100     }
101
102     #[inline]
103     fn size_hint(&self) -> (usize, Option<usize>) {
104         self.iter.size_hint()
105     }
106
107     fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
108     where
109         Self: Sized,
110         G: FnMut(Acc, Self::Item) -> R,
111         R: Try<Ok = Acc>,
112     {
113         self.iter.try_fold(init, map_try_fold(&mut self.f, g))
114     }
115
116     fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
117     where
118         G: FnMut(Acc, Self::Item) -> Acc,
119     {
120         self.iter.fold(init, map_fold(self.f, g))
121     }
122
123     unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
124     where
125         Self: TrustedRandomAccess,
126     {
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)) }
130     }
131 }
132
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
135 where
136     F: FnMut(I::Item) -> B,
137 {
138     #[inline]
139     fn next_back(&mut self) -> Option<B> {
140         self.iter.next_back().map(&mut self.f)
141     }
142
143     fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
144     where
145         Self: Sized,
146         G: FnMut(Acc, Self::Item) -> R,
147         R: Try<Ok = Acc>,
148     {
149         self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
150     }
151
152     fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
153     where
154         G: FnMut(Acc, Self::Item) -> Acc,
155     {
156         self.iter.rfold(init, map_fold(self.f, g))
157     }
158 }
159
160 #[stable(feature = "rust1", since = "1.0.0")]
161 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
162 where
163     F: FnMut(I::Item) -> B,
164 {
165     fn len(&self) -> usize {
166         self.iter.len()
167     }
168
169     fn is_empty(&self) -> bool {
170         self.iter.is_empty()
171     }
172 }
173
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 {}
176
177 #[unstable(feature = "trusted_len", issue = "37572")]
178 unsafe impl<B, I, F> TrustedLen for Map<I, F>
179 where
180     I: TrustedLen,
181     F: FnMut(I::Item) -> B,
182 {
183 }
184
185 #[doc(hidden)]
186 #[unstable(feature = "trusted_random_access", issue = "none")]
187 unsafe impl<I, F> TrustedRandomAccess for Map<I, F>
188 where
189     I: TrustedRandomAccess,
190 {
191     #[inline]
192     fn may_have_side_effect() -> bool {
193         true
194     }
195 }
196
197 #[unstable(issue = "none", feature = "inplace_iteration")]
198 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for Map<I, F>
199 where
200     F: FnMut(I::Item) -> B,
201     I: SourceIter<Source = S>,
202 {
203     type Source = S;
204
205     #[inline]
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) }
209     }
210 }
211
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 {}