core/iter/traits/double_ended.rs
1use crate::marker::Destruct;
2use crate::num::NonZero;
3use crate::ops::{ControlFlow, Try};
4
5/// An iterator able to yield elements from both ends.
6///
7/// Something that implements `DoubleEndedIterator` has one extra capability
8/// over something that implements [`Iterator`]: the ability to also take
9/// `Item`s from the back, as well as the front.
10///
11/// It is important to note that both back and forth work on the same range,
12/// and do not cross: iteration is over when they meet in the middle.
13///
14/// In a similar fashion to the [`Iterator`] protocol, once a
15/// `DoubleEndedIterator` returns [`None`] from a [`next_back()`], calling it
16/// again may or may not ever return [`Some`] again. [`next()`] and
17/// [`next_back()`] are interchangeable for this purpose.
18///
19/// [`next_back()`]: DoubleEndedIterator::next_back
20/// [`next()`]: Iterator::next
21///
22/// # Examples
23///
24/// Basic usage:
25///
26/// ```
27/// let numbers = vec![1, 2, 3, 4, 5, 6];
28///
29/// let mut iter = numbers.iter();
30///
31/// assert_eq!(Some(&1), iter.next());
32/// assert_eq!(Some(&6), iter.next_back());
33/// assert_eq!(Some(&5), iter.next_back());
34/// assert_eq!(Some(&2), iter.next());
35/// assert_eq!(Some(&3), iter.next());
36/// assert_eq!(Some(&4), iter.next());
37/// assert_eq!(None, iter.next());
38/// assert_eq!(None, iter.next_back());
39/// ```
40#[stable(feature = "rust1", since = "1.0.0")]
41#[rustc_diagnostic_item = "DoubleEndedIterator"]
42#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
43pub const trait DoubleEndedIterator: [const] Iterator {
44 /// Removes and returns an element from the end of the iterator.
45 ///
46 /// Returns `None` when there are no more elements.
47 ///
48 /// The [trait-level] docs contain more details.
49 ///
50 /// [trait-level]: DoubleEndedIterator
51 ///
52 /// # Examples
53 ///
54 /// Basic usage:
55 ///
56 /// ```
57 /// let numbers = vec![1, 2, 3, 4, 5, 6];
58 ///
59 /// let mut iter = numbers.iter();
60 ///
61 /// assert_eq!(Some(&1), iter.next());
62 /// assert_eq!(Some(&6), iter.next_back());
63 /// assert_eq!(Some(&5), iter.next_back());
64 /// assert_eq!(Some(&2), iter.next());
65 /// assert_eq!(Some(&3), iter.next());
66 /// assert_eq!(Some(&4), iter.next());
67 /// assert_eq!(None, iter.next());
68 /// assert_eq!(None, iter.next_back());
69 /// ```
70 ///
71 /// # Remarks
72 ///
73 /// The elements yielded by `DoubleEndedIterator`'s methods may differ from
74 /// the ones yielded by [`Iterator`]'s methods:
75 ///
76 /// ```
77 /// let vec = vec![(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b')];
78 /// let uniq_by_fst_comp = || {
79 /// let mut seen = std::collections::HashSet::new();
80 /// vec.iter().copied().filter(move |x| seen.insert(x.0))
81 /// };
82 ///
83 /// assert_eq!(uniq_by_fst_comp().last(), Some((2, 'a')));
84 /// assert_eq!(uniq_by_fst_comp().next_back(), Some((2, 'b')));
85 ///
86 /// assert_eq!(
87 /// uniq_by_fst_comp().fold(vec![], |mut v, x| {v.push(x); v}),
88 /// vec![(1, 'a'), (2, 'a')]
89 /// );
90 /// assert_eq!(
91 /// uniq_by_fst_comp().rfold(vec![], |mut v, x| {v.push(x); v}),
92 /// vec![(2, 'b'), (1, 'c')]
93 /// );
94 /// ```
95 #[stable(feature = "rust1", since = "1.0.0")]
96 fn next_back(&mut self) -> Option<Self::Item>;
97
98 /// Advances the iterator from the back by `n` elements.
99 ///
100 /// `advance_back_by` is the reverse version of [`advance_by`]. This method will
101 /// eagerly skip `n` elements starting from the back by calling [`next_back`] up
102 /// to `n` times until [`None`] is encountered.
103 ///
104 /// `advance_back_by(n)` will return `Ok(())` if the iterator successfully advances by
105 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered, where `k`
106 /// is remaining number of steps that could not be advanced because the iterator ran out.
107 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
108 /// Otherwise, `k` is always less than `n`.
109 ///
110 /// Calling `advance_back_by(0)` can do meaningful work, for example [`Flatten`] can advance its
111 /// outer iterator until it finds an inner iterator that is not empty, which then often
112 /// allows it to return a more accurate `size_hint()` than in its initial state.
113 ///
114 /// [`advance_by`]: Iterator::advance_by
115 /// [`Flatten`]: crate::iter::Flatten
116 /// [`next_back`]: DoubleEndedIterator::next_back
117 ///
118 /// # Examples
119 ///
120 /// Basic usage:
121 ///
122 /// ```
123 /// #![feature(iter_advance_by)]
124 ///
125 /// use std::num::NonZero;
126 ///
127 /// let a = [3, 4, 5, 6];
128 /// let mut iter = a.iter();
129 ///
130 /// assert_eq!(iter.advance_back_by(2), Ok(()));
131 /// assert_eq!(iter.next_back(), Some(&4));
132 /// assert_eq!(iter.advance_back_by(0), Ok(()));
133 /// assert_eq!(iter.advance_back_by(100), Err(NonZero::new(99).unwrap())); // only `&3` was skipped
134 /// ```
135 ///
136 /// [`Ok(())`]: Ok
137 /// [`Err(k)`]: Err
138 #[inline]
139 #[unstable(feature = "iter_advance_by", issue = "77404")]
140 #[rustc_non_const_trait_method]
141 fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
142 for i in 0..n {
143 if self.next_back().is_none() {
144 // SAFETY: `i` is always less than `n`.
145 return Err(unsafe { NonZero::new_unchecked(n - i) });
146 }
147 }
148 Ok(())
149 }
150
151 /// Returns the `n`th element from the end of the iterator.
152 ///
153 /// This is essentially the reversed version of [`Iterator::nth()`].
154 /// Although like most indexing operations, the count starts from zero, so
155 /// `nth_back(0)` returns the first value from the end, `nth_back(1)` the
156 /// second, and so on.
157 ///
158 /// Note that all elements between the end and the returned element will be
159 /// consumed, including the returned element. This also means that calling
160 /// `nth_back(0)` multiple times on the same iterator will return different
161 /// elements.
162 ///
163 /// `nth_back()` will return [`None`] if `n` is greater than or equal to the
164 /// length of the iterator.
165 ///
166 /// # Examples
167 ///
168 /// Basic usage:
169 ///
170 /// ```
171 /// let a = [1, 2, 3];
172 /// assert_eq!(a.iter().nth_back(2), Some(&1));
173 /// ```
174 ///
175 /// Calling `nth_back()` multiple times doesn't rewind the iterator:
176 ///
177 /// ```
178 /// let a = [1, 2, 3];
179 ///
180 /// let mut iter = a.iter();
181 ///
182 /// assert_eq!(iter.nth_back(1), Some(&2));
183 /// assert_eq!(iter.nth_back(1), None);
184 /// ```
185 ///
186 /// Returning `None` if there are less than `n + 1` elements:
187 ///
188 /// ```
189 /// let a = [1, 2, 3];
190 /// assert_eq!(a.iter().nth_back(10), None);
191 /// ```
192 #[inline]
193 #[stable(feature = "iter_nth_back", since = "1.37.0")]
194 #[rustc_non_const_trait_method]
195 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
196 if self.advance_back_by(n).is_err() {
197 return None;
198 }
199 self.next_back()
200 }
201
202 /// This is the reverse version of [`Iterator::try_fold()`]: it takes
203 /// elements starting from the back of the iterator.
204 ///
205 /// # Examples
206 ///
207 /// Basic usage:
208 ///
209 /// ```
210 /// let a = ["1", "2", "3"];
211 /// let sum = a.iter()
212 /// .map(|&s| s.parse::<i32>())
213 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
214 /// assert_eq!(sum, Ok(6));
215 /// ```
216 ///
217 /// Short-circuiting:
218 ///
219 /// ```
220 /// let a = ["1", "rust", "3"];
221 /// let mut it = a.iter();
222 /// let sum = it
223 /// .by_ref()
224 /// .map(|&s| s.parse::<i32>())
225 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
226 /// assert!(sum.is_err());
227 ///
228 /// // Because it short-circuited, the remaining elements are still
229 /// // available through the iterator.
230 /// assert_eq!(it.next_back(), Some(&"1"));
231 /// ```
232 #[inline]
233 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
234 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
235 where
236 Self: Sized,
237 F: [const] FnMut(B, Self::Item) -> R + [const] Destruct,
238 R: [const] Try<Output = B>,
239 {
240 let mut accum = init;
241 while let Some(x) = self.next_back() {
242 accum = f(accum, x)?;
243 }
244 try { accum }
245 }
246
247 /// An iterator method that reduces the iterator's elements to a single,
248 /// final value, starting from the back.
249 ///
250 /// This is the reverse version of [`Iterator::fold()`]: it takes elements
251 /// starting from the back of the iterator.
252 ///
253 /// `rfold()` takes two arguments: an initial value, and a closure with two
254 /// arguments: an 'accumulator', and an element. The closure returns the value that
255 /// the accumulator should have for the next iteration.
256 ///
257 /// The initial value is the value the accumulator will have on the first
258 /// call.
259 ///
260 /// After applying this closure to every element of the iterator, `rfold()`
261 /// returns the accumulator.
262 ///
263 /// This operation is sometimes called 'reduce' or 'inject'.
264 ///
265 /// Folding is useful whenever you have a collection of something, and want
266 /// to produce a single value from it.
267 ///
268 /// Note: `rfold()` combines elements in a *right-associative* fashion. For associative
269 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
270 /// operators like `-` the order will affect the final result.
271 /// For a *left-associative* version of `rfold()`, see [`Iterator::fold()`].
272 ///
273 /// # Examples
274 ///
275 /// Basic usage:
276 ///
277 /// ```
278 /// let a = [1, 2, 3];
279 ///
280 /// // the sum of all of the elements of a
281 /// let sum = a.iter()
282 /// .rfold(0, |acc, &x| acc + x);
283 ///
284 /// assert_eq!(sum, 6);
285 /// ```
286 ///
287 /// This example demonstrates the right-associative nature of `rfold()`:
288 /// it builds a string, starting with an initial value
289 /// and continuing with each element from the back until the front:
290 ///
291 /// ```
292 /// let numbers = [1, 2, 3, 4, 5];
293 ///
294 /// let zero = "0".to_string();
295 ///
296 /// let result = numbers.iter().rfold(zero, |acc, &x| {
297 /// format!("({x} + {acc})")
298 /// });
299 ///
300 /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
301 /// ```
302 #[doc(alias = "foldr")]
303 #[inline]
304 #[stable(feature = "iter_rfold", since = "1.27.0")]
305 fn rfold<B, F>(mut self, init: B, mut f: F) -> B
306 where
307 Self: Sized + [const] Destruct,
308 F: [const] FnMut(B, Self::Item) -> B + [const] Destruct,
309 {
310 let mut accum = init;
311 while let Some(x) = self.next_back() {
312 accum = f(accum, x);
313 }
314 accum
315 }
316
317 /// Searches for an element of an iterator from the back that satisfies a predicate.
318 ///
319 /// `rfind()` takes a closure that returns `true` or `false`. It applies
320 /// this closure to each element of the iterator, starting at the end, and if any
321 /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
322 /// `false`, it returns [`None`].
323 ///
324 /// `rfind()` is short-circuiting; in other words, it will stop processing
325 /// as soon as the closure returns `true`.
326 ///
327 /// Because `rfind()` takes a reference, and many iterators iterate over
328 /// references, this leads to a possibly confusing situation where the
329 /// argument is a double reference. You can see this effect in the
330 /// examples below, with `&&x`.
331 ///
332 /// [`Some(element)`]: Some
333 ///
334 /// # Examples
335 ///
336 /// Basic usage:
337 ///
338 /// ```
339 /// let a = [1, 2, 3];
340 ///
341 /// assert_eq!(a.into_iter().rfind(|&x| x == 2), Some(2));
342 /// assert_eq!(a.into_iter().rfind(|&x| x == 5), None);
343 /// ```
344 ///
345 /// Iterating over references:
346 ///
347 /// ```
348 /// let a = [1, 2, 3];
349 ///
350 /// // `iter()` yields references i.e. `&i32` and `rfind()` takes a
351 /// // reference to each element.
352 /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
353 /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
354 /// ```
355 ///
356 /// Stopping at the first `true`:
357 ///
358 /// ```
359 /// let a = [1, 2, 3];
360 ///
361 /// let mut iter = a.iter();
362 ///
363 /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
364 ///
365 /// // we can still use `iter`, as there are more elements.
366 /// assert_eq!(iter.next_back(), Some(&1));
367 /// ```
368 #[inline]
369 #[stable(feature = "iter_rfind", since = "1.27.0")]
370 #[rustc_non_const_trait_method]
371 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
372 where
373 Self: Sized,
374 P: FnMut(&Self::Item) -> bool,
375 {
376 #[inline]
377 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
378 move |(), x| {
379 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
380 }
381 }
382
383 self.try_rfold((), check(predicate)).break_value()
384 }
385}
386
387#[stable(feature = "rust1", since = "1.0.0")]
388impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
389 fn next_back(&mut self) -> Option<I::Item> {
390 (**self).next_back()
391 }
392 fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
393 (**self).advance_back_by(n)
394 }
395 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
396 (**self).nth_back(n)
397 }
398 fn rfold<B, F>(self, init: B, f: F) -> B
399 where
400 F: FnMut(B, Self::Item) -> B,
401 {
402 self.spec_rfold(init, f)
403 }
404 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
405 where
406 F: FnMut(B, Self::Item) -> R,
407 R: Try<Output = B>,
408 {
409 self.spec_try_rfold(init, f)
410 }
411}
412
413/// Helper trait to specialize `rfold` and `rtry_fold` for `&mut I where I: Sized`
414trait DoubleEndedIteratorRefSpec: DoubleEndedIterator {
415 fn spec_rfold<B, F>(self, init: B, f: F) -> B
416 where
417 F: FnMut(B, Self::Item) -> B;
418
419 fn spec_try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
420 where
421 F: FnMut(B, Self::Item) -> R,
422 R: Try<Output = B>;
423}
424
425impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIteratorRefSpec for &mut I {
426 default fn spec_rfold<B, F>(self, init: B, mut f: F) -> B
427 where
428 F: FnMut(B, Self::Item) -> B,
429 {
430 let mut accum = init;
431 while let Some(x) = self.next_back() {
432 accum = f(accum, x);
433 }
434 accum
435 }
436
437 default fn spec_try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
438 where
439 F: FnMut(B, Self::Item) -> R,
440 R: Try<Output = B>,
441 {
442 let mut accum = init;
443 while let Some(x) = self.next_back() {
444 accum = f(accum, x)?;
445 }
446 try { accum }
447 }
448}
449
450impl<I: DoubleEndedIterator> DoubleEndedIteratorRefSpec for &mut I {
451 impl_fold_via_try_fold! { spec_rfold -> spec_try_rfold }
452
453 fn spec_try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
454 where
455 F: FnMut(B, Self::Item) -> R,
456 R: Try<Output = B>,
457 {
458 (**self).try_rfold(init, f)
459 }
460}