Skip to main content

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    #[ferrocene::prevalidated]
139    #[inline]
140    #[unstable(feature = "iter_advance_by", issue = "77404")]
141    #[rustc_non_const_trait_method]
142    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
143        for i in 0..n {
144            if self.next_back().is_none() {
145                // SAFETY: `i` is always less than `n`.
146                return Err(unsafe { NonZero::new_unchecked(n - i) });
147            }
148        }
149        Ok(())
150    }
151
152    /// Returns the `n`th element from the end of the iterator.
153    ///
154    /// This is essentially the reversed version of [`Iterator::nth()`].
155    /// Although like most indexing operations, the count starts from zero, so
156    /// `nth_back(0)` returns the first value from the end, `nth_back(1)` the
157    /// second, and so on.
158    ///
159    /// Note that all elements between the end and the returned element will be
160    /// consumed, including the returned element. This also means that calling
161    /// `nth_back(0)` multiple times on the same iterator will return different
162    /// elements.
163    ///
164    /// `nth_back()` will return [`None`] if `n` is greater than or equal to the
165    /// length of the iterator.
166    ///
167    /// # Examples
168    ///
169    /// Basic usage:
170    ///
171    /// ```
172    /// let a = [1, 2, 3];
173    /// assert_eq!(a.iter().nth_back(2), Some(&1));
174    /// ```
175    ///
176    /// Calling `nth_back()` multiple times doesn't rewind the iterator:
177    ///
178    /// ```
179    /// let a = [1, 2, 3];
180    ///
181    /// let mut iter = a.iter();
182    ///
183    /// assert_eq!(iter.nth_back(1), Some(&2));
184    /// assert_eq!(iter.nth_back(1), None);
185    /// ```
186    ///
187    /// Returning `None` if there are less than `n + 1` elements:
188    ///
189    /// ```
190    /// let a = [1, 2, 3];
191    /// assert_eq!(a.iter().nth_back(10), None);
192    /// ```
193    #[ferrocene::prevalidated]
194    #[inline]
195    #[stable(feature = "iter_nth_back", since = "1.37.0")]
196    #[rustc_non_const_trait_method]
197    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
198        if self.advance_back_by(n).is_err() {
199            return None;
200        }
201        self.next_back()
202    }
203
204    /// This is the reverse version of [`Iterator::try_fold()`]: it takes
205    /// elements starting from the back of the iterator.
206    ///
207    /// # Examples
208    ///
209    /// Basic usage:
210    ///
211    /// ```
212    /// let a = ["1", "2", "3"];
213    /// let sum = a.iter()
214    ///     .map(|&s| s.parse::<i32>())
215    ///     .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
216    /// assert_eq!(sum, Ok(6));
217    /// ```
218    ///
219    /// Short-circuiting:
220    ///
221    /// ```
222    /// let a = ["1", "rust", "3"];
223    /// let mut it = a.iter();
224    /// let sum = it
225    ///     .by_ref()
226    ///     .map(|&s| s.parse::<i32>())
227    ///     .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
228    /// assert!(sum.is_err());
229    ///
230    /// // Because it short-circuited, the remaining elements are still
231    /// // available through the iterator.
232    /// assert_eq!(it.next_back(), Some(&"1"));
233    /// ```
234    #[inline]
235    #[stable(feature = "iterator_try_fold", since = "1.27.0")]
236    #[ferrocene::prevalidated]
237    fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
238    where
239        Self: Sized,
240        F: [const] FnMut(B, Self::Item) -> R + [const] Destruct,
241        R: [const] Try<Output = B>,
242    {
243        let mut accum = init;
244        while let Some(x) = self.next_back() {
245            accum = f(accum, x)?;
246        }
247        try { accum }
248    }
249
250    /// An iterator method that reduces the iterator's elements to a single,
251    /// final value, starting from the back.
252    ///
253    /// This is the reverse version of [`Iterator::fold()`]: it takes elements
254    /// starting from the back of the iterator.
255    ///
256    /// `rfold()` takes two arguments: an initial value, and a closure with two
257    /// arguments: an 'accumulator', and an element. The closure returns the value that
258    /// the accumulator should have for the next iteration.
259    ///
260    /// The initial value is the value the accumulator will have on the first
261    /// call.
262    ///
263    /// After applying this closure to every element of the iterator, `rfold()`
264    /// returns the accumulator.
265    ///
266    /// This operation is sometimes called 'reduce' or 'inject'.
267    ///
268    /// Folding is useful whenever you have a collection of something, and want
269    /// to produce a single value from it.
270    ///
271    /// Note: `rfold()` combines elements in a *right-associative* fashion. For associative
272    /// operators like `+`, the order the elements are combined in is not important, but for non-associative
273    /// operators like `-` the order will affect the final result.
274    /// For a *left-associative* version of `rfold()`, see [`Iterator::fold()`].
275    ///
276    /// # Examples
277    ///
278    /// Basic usage:
279    ///
280    /// ```
281    /// let a = [1, 2, 3];
282    ///
283    /// // the sum of all of the elements of a
284    /// let sum = a.iter()
285    ///            .rfold(0, |acc, &x| acc + x);
286    ///
287    /// assert_eq!(sum, 6);
288    /// ```
289    ///
290    /// This example demonstrates the right-associative nature of `rfold()`:
291    /// it builds a string, starting with an initial value
292    /// and continuing with each element from the back until the front:
293    ///
294    /// ```
295    /// let numbers = [1, 2, 3, 4, 5];
296    ///
297    /// let zero = "0".to_string();
298    ///
299    /// let result = numbers.iter().rfold(zero, |acc, &x| {
300    ///     format!("({x} + {acc})")
301    /// });
302    ///
303    /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
304    /// ```
305    #[doc(alias = "foldr")]
306    #[inline]
307    #[stable(feature = "iter_rfold", since = "1.27.0")]
308    #[ferrocene::prevalidated]
309    fn rfold<B, F>(mut self, init: B, mut f: F) -> B
310    where
311        Self: Sized + [const] Destruct,
312        F: [const] FnMut(B, Self::Item) -> B + [const] Destruct,
313    {
314        let mut accum = init;
315        while let Some(x) = self.next_back() {
316            accum = f(accum, x);
317        }
318        accum
319    }
320
321    /// Searches for an element of an iterator from the back that satisfies a predicate.
322    ///
323    /// `rfind()` takes a closure that returns `true` or `false`. It applies
324    /// this closure to each element of the iterator, starting at the end, and if any
325    /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
326    /// `false`, it returns [`None`].
327    ///
328    /// `rfind()` is short-circuiting; in other words, it will stop processing
329    /// as soon as the closure returns `true`.
330    ///
331    /// Because `rfind()` takes a reference, and many iterators iterate over
332    /// references, this leads to a possibly confusing situation where the
333    /// argument is a double reference. You can see this effect in the
334    /// examples below, with `&&x`.
335    ///
336    /// [`Some(element)`]: Some
337    ///
338    /// # Examples
339    ///
340    /// Basic usage:
341    ///
342    /// ```
343    /// let a = [1, 2, 3];
344    ///
345    /// assert_eq!(a.into_iter().rfind(|&x| x == 2), Some(2));
346    /// assert_eq!(a.into_iter().rfind(|&x| x == 5), None);
347    /// ```
348    ///
349    /// Iterating over references:
350    ///
351    /// ```
352    /// let a = [1, 2, 3];
353    ///
354    /// // `iter()` yields references i.e. `&i32` and `rfind()` takes a
355    /// // reference to each element.
356    /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
357    /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
358    /// ```
359    ///
360    /// Stopping at the first `true`:
361    ///
362    /// ```
363    /// let a = [1, 2, 3];
364    ///
365    /// let mut iter = a.iter();
366    ///
367    /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
368    ///
369    /// // we can still use `iter`, as there are more elements.
370    /// assert_eq!(iter.next_back(), Some(&1));
371    /// ```
372    #[ferrocene::prevalidated]
373    #[inline]
374    #[stable(feature = "iter_rfind", since = "1.27.0")]
375    #[rustc_non_const_trait_method]
376    fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
377    where
378        Self: Sized,
379        P: FnMut(&Self::Item) -> bool,
380    {
381        #[inline]
382        #[ferrocene::prevalidated]
383        fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
384            move |(), x| {
385                if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
386            }
387        }
388
389        self.try_rfold((), check(predicate)).break_value()
390    }
391}
392
393#[stable(feature = "rust1", since = "1.0.0")]
394impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
395    fn next_back(&mut self) -> Option<I::Item> {
396        (**self).next_back()
397    }
398    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
399        (**self).advance_back_by(n)
400    }
401    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
402        (**self).nth_back(n)
403    }
404    fn rfold<B, F>(self, init: B, f: F) -> B
405    where
406        F: FnMut(B, Self::Item) -> B,
407    {
408        self.spec_rfold(init, f)
409    }
410    fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
411    where
412        F: FnMut(B, Self::Item) -> R,
413        R: Try<Output = B>,
414    {
415        self.spec_try_rfold(init, f)
416    }
417}
418
419/// Helper trait to specialize `rfold` and `rtry_fold` for `&mut I where I: Sized`
420trait DoubleEndedIteratorRefSpec: DoubleEndedIterator {
421    fn spec_rfold<B, F>(self, init: B, f: F) -> B
422    where
423        F: FnMut(B, Self::Item) -> B;
424
425    fn spec_try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
426    where
427        F: FnMut(B, Self::Item) -> R,
428        R: Try<Output = B>;
429}
430
431impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIteratorRefSpec for &mut I {
432    default fn spec_rfold<B, F>(self, init: B, mut f: F) -> B
433    where
434        F: FnMut(B, Self::Item) -> B,
435    {
436        let mut accum = init;
437        while let Some(x) = self.next_back() {
438            accum = f(accum, x);
439        }
440        accum
441    }
442
443    default fn spec_try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
444    where
445        F: FnMut(B, Self::Item) -> R,
446        R: Try<Output = B>,
447    {
448        let mut accum = init;
449        while let Some(x) = self.next_back() {
450            accum = f(accum, x)?;
451        }
452        try { accum }
453    }
454}
455
456impl<I: DoubleEndedIterator> DoubleEndedIteratorRefSpec for &mut I {
457    impl_fold_via_try_fold! { spec_rfold -> spec_try_rfold }
458
459    fn spec_try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
460    where
461        F: FnMut(B, Self::Item) -> R,
462        R: Try<Output = B>,
463    {
464        (**self).try_rfold(init, f)
465    }
466}