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