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