]> git.proxmox.com Git - rustc.git/blob - library/core/src/iter/adapters/enumerate.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / library / core / src / iter / adapters / enumerate.rs
1 use crate::iter::adapters::{zip::try_get_unchecked, SourceIter, TrustedRandomAccess};
2 use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
3 use crate::ops::Try;
4
5 /// An iterator that yields the current count and the element during iteration.
6 ///
7 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
8 /// documentation for more.
9 ///
10 /// [`enumerate`]: Iterator::enumerate
11 /// [`Iterator`]: trait.Iterator.html
12 #[derive(Clone, Debug)]
13 #[must_use = "iterators are lazy and do nothing unless consumed"]
14 #[stable(feature = "rust1", since = "1.0.0")]
15 pub struct Enumerate<I> {
16 iter: I,
17 count: usize,
18 }
19 impl<I> Enumerate<I> {
20 pub(in crate::iter) fn new(iter: I) -> Enumerate<I> {
21 Enumerate { iter, count: 0 }
22 }
23 }
24
25 #[stable(feature = "rust1", since = "1.0.0")]
26 impl<I> Iterator for Enumerate<I>
27 where
28 I: Iterator,
29 {
30 type Item = (usize, <I as Iterator>::Item);
31
32 /// # Overflow Behavior
33 ///
34 /// The method does no guarding against overflows, so enumerating more than
35 /// `usize::MAX` elements either produces the wrong result or panics. If
36 /// debug assertions are enabled, a panic is guaranteed.
37 ///
38 /// # Panics
39 ///
40 /// Might panic if the index of the element overflows a `usize`.
41 #[inline]
42 #[rustc_inherit_overflow_checks]
43 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
44 let a = self.iter.next()?;
45 let i = self.count;
46 self.count += 1;
47 Some((i, a))
48 }
49
50 #[inline]
51 fn size_hint(&self) -> (usize, Option<usize>) {
52 self.iter.size_hint()
53 }
54
55 #[inline]
56 #[rustc_inherit_overflow_checks]
57 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
58 let a = self.iter.nth(n)?;
59 let i = self.count + n;
60 self.count = i + 1;
61 Some((i, a))
62 }
63
64 #[inline]
65 fn count(self) -> usize {
66 self.iter.count()
67 }
68
69 #[inline]
70 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
71 where
72 Self: Sized,
73 Fold: FnMut(Acc, Self::Item) -> R,
74 R: Try<Ok = Acc>,
75 {
76 #[inline]
77 fn enumerate<'a, T, Acc, R>(
78 count: &'a mut usize,
79 mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a,
80 ) -> impl FnMut(Acc, T) -> R + 'a {
81 #[rustc_inherit_overflow_checks]
82 move |acc, item| {
83 let acc = fold(acc, (*count, item));
84 *count += 1;
85 acc
86 }
87 }
88
89 self.iter.try_fold(init, enumerate(&mut self.count, fold))
90 }
91
92 #[inline]
93 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
94 where
95 Fold: FnMut(Acc, Self::Item) -> Acc,
96 {
97 #[inline]
98 fn enumerate<T, Acc>(
99 mut count: usize,
100 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
101 ) -> impl FnMut(Acc, T) -> Acc {
102 #[rustc_inherit_overflow_checks]
103 move |acc, item| {
104 let acc = fold(acc, (count, item));
105 count += 1;
106 acc
107 }
108 }
109
110 self.iter.fold(init, enumerate(self.count, fold))
111 }
112
113 #[rustc_inherit_overflow_checks]
114 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item
115 where
116 Self: TrustedRandomAccess,
117 {
118 // SAFETY: the caller must uphold the contract for
119 // `Iterator::__iterator_get_unchecked`.
120 let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
121 (self.count + idx, value)
122 }
123 }
124
125 #[stable(feature = "rust1", since = "1.0.0")]
126 impl<I> DoubleEndedIterator for Enumerate<I>
127 where
128 I: ExactSizeIterator + DoubleEndedIterator,
129 {
130 #[inline]
131 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
132 let a = self.iter.next_back()?;
133 let len = self.iter.len();
134 // Can safely add, `ExactSizeIterator` promises that the number of
135 // elements fits into a `usize`.
136 Some((self.count + len, a))
137 }
138
139 #[inline]
140 fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
141 let a = self.iter.nth_back(n)?;
142 let len = self.iter.len();
143 // Can safely add, `ExactSizeIterator` promises that the number of
144 // elements fits into a `usize`.
145 Some((self.count + len, a))
146 }
147
148 #[inline]
149 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
150 where
151 Self: Sized,
152 Fold: FnMut(Acc, Self::Item) -> R,
153 R: Try<Ok = Acc>,
154 {
155 // Can safely add and subtract the count, as `ExactSizeIterator` promises
156 // that the number of elements fits into a `usize`.
157 fn enumerate<T, Acc, R>(
158 mut count: usize,
159 mut fold: impl FnMut(Acc, (usize, T)) -> R,
160 ) -> impl FnMut(Acc, T) -> R {
161 move |acc, item| {
162 count -= 1;
163 fold(acc, (count, item))
164 }
165 }
166
167 let count = self.count + self.iter.len();
168 self.iter.try_rfold(init, enumerate(count, fold))
169 }
170
171 #[inline]
172 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
173 where
174 Fold: FnMut(Acc, Self::Item) -> Acc,
175 {
176 // Can safely add and subtract the count, as `ExactSizeIterator` promises
177 // that the number of elements fits into a `usize`.
178 fn enumerate<T, Acc>(
179 mut count: usize,
180 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
181 ) -> impl FnMut(Acc, T) -> Acc {
182 move |acc, item| {
183 count -= 1;
184 fold(acc, (count, item))
185 }
186 }
187
188 let count = self.count + self.iter.len();
189 self.iter.rfold(init, enumerate(count, fold))
190 }
191 }
192
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl<I> ExactSizeIterator for Enumerate<I>
195 where
196 I: ExactSizeIterator,
197 {
198 fn len(&self) -> usize {
199 self.iter.len()
200 }
201
202 fn is_empty(&self) -> bool {
203 self.iter.is_empty()
204 }
205 }
206
207 #[doc(hidden)]
208 #[unstable(feature = "trusted_random_access", issue = "none")]
209 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
210 where
211 I: TrustedRandomAccess,
212 {
213 const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT;
214 }
215
216 #[stable(feature = "fused", since = "1.26.0")]
217 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
218
219 #[unstable(feature = "trusted_len", issue = "37572")]
220 unsafe impl<I> TrustedLen for Enumerate<I> where I: TrustedLen {}
221
222 #[unstable(issue = "none", feature = "inplace_iteration")]
223 unsafe impl<S: Iterator, I: Iterator> SourceIter for Enumerate<I>
224 where
225 I: SourceIter<Source = S>,
226 {
227 type Source = S;
228
229 #[inline]
230 unsafe fn as_inner(&mut self) -> &mut S {
231 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
232 unsafe { SourceIter::as_inner(&mut self.iter) }
233 }
234 }
235
236 #[unstable(issue = "none", feature = "inplace_iteration")]
237 unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> {}