]> git.proxmox.com Git - rustc.git/blob - library/core/src/iter/adapters/map.rs
New upstream version 1.60.0+dfsg1
[rustc.git] / library / core / src / iter / adapters / map.rs
1 use crate::fmt;
2 use crate::iter::adapters::{
3 zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce,
4 };
5 use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
6 use 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 pub struct Map<I, F> {
62 // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods
63 pub(crate) iter: I,
64 f: F,
65 }
66
67 impl<I, F> Map<I, F> {
68 pub(in crate::iter) fn new(iter: I, f: F) -> Map<I, F> {
69 Map { iter, f }
70 }
71 }
72
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()
77 }
78 }
79
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))
85 }
86
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))
92 }
93
94 #[stable(feature = "rust1", since = "1.0.0")]
95 impl<B, I: Iterator, F> Iterator for Map<I, F>
96 where
97 F: FnMut(I::Item) -> B,
98 {
99 type Item = B;
100
101 #[inline]
102 fn next(&mut self) -> Option<B> {
103 self.iter.next().map(&mut self.f)
104 }
105
106 #[inline]
107 fn size_hint(&self) -> (usize, Option<usize>) {
108 self.iter.size_hint()
109 }
110
111 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
112 where
113 Self: Sized,
114 G: FnMut(Acc, Self::Item) -> R,
115 R: Try<Output = Acc>,
116 {
117 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
118 }
119
120 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
121 where
122 G: FnMut(Acc, Self::Item) -> Acc,
123 {
124 self.iter.fold(init, map_fold(self.f, g))
125 }
126
127 #[doc(hidden)]
128 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
129 where
130 Self: TrustedRandomAccessNoCoerce,
131 {
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)) }
135 }
136 }
137
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
140 where
141 F: FnMut(I::Item) -> B,
142 {
143 #[inline]
144 fn next_back(&mut self) -> Option<B> {
145 self.iter.next_back().map(&mut self.f)
146 }
147
148 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
149 where
150 Self: Sized,
151 G: FnMut(Acc, Self::Item) -> R,
152 R: Try<Output = Acc>,
153 {
154 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
155 }
156
157 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
158 where
159 G: FnMut(Acc, Self::Item) -> Acc,
160 {
161 self.iter.rfold(init, map_fold(self.f, g))
162 }
163 }
164
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
167 where
168 F: FnMut(I::Item) -> B,
169 {
170 fn len(&self) -> usize {
171 self.iter.len()
172 }
173
174 fn is_empty(&self) -> bool {
175 self.iter.is_empty()
176 }
177 }
178
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 {}
181
182 #[unstable(feature = "trusted_len", issue = "37572")]
183 unsafe impl<B, I, F> TrustedLen for Map<I, F>
184 where
185 I: TrustedLen,
186 F: FnMut(I::Item) -> B,
187 {
188 }
189
190 #[doc(hidden)]
191 #[unstable(feature = "trusted_random_access", issue = "none")]
192 unsafe impl<I, F> TrustedRandomAccess for Map<I, F> where I: TrustedRandomAccess {}
193
194 #[doc(hidden)]
195 #[unstable(feature = "trusted_random_access", issue = "none")]
196 unsafe impl<I, F> TrustedRandomAccessNoCoerce for Map<I, F>
197 where
198 I: TrustedRandomAccessNoCoerce,
199 {
200 const MAY_HAVE_SIDE_EFFECT: bool = true;
201 }
202
203 #[unstable(issue = "none", feature = "inplace_iteration")]
204 unsafe impl<I, F> SourceIter for Map<I, F>
205 where
206 I: SourceIter,
207 {
208 type Source = I::Source;
209
210 #[inline]
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) }
214 }
215 }
216
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 {}