core/iter/traits/iterator.rs
1#[cfg(not(feature = "ferrocene_subset"))]
2use super::super::{
3 ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap,
4 Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable,
5 Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce,
6 Zip, try_process,
7};
8use super::TrustedLen;
9#[cfg(not(feature = "ferrocene_subset"))]
10use crate::array;
11use crate::cmp::{self, Ordering};
12use crate::num::NonZero;
13#[cfg(not(feature = "ferrocene_subset"))]
14use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
15
16// Ferrocene addition: imports for certified subset
17#[cfg(feature = "ferrocene_subset")]
18#[rustfmt::skip]
19use {
20 super::super::{
21 Chain, Cloned, Copied, DoubleEndedIterator, Enumerate, Filter, FlatMap, Fuse, Map, Rev,
22 Skip, StepBy, Sum, Take, TakeWhile, Zip,
23 },
24 crate::ops::{ControlFlow, Try},
25};
26
27#[cfg(not(feature = "ferrocene_subset"))]
28fn _assert_is_dyn_compatible(_: &dyn Iterator<Item = ()>) {}
29
30/// A trait for dealing with iterators.
31///
32/// This is the main iterator trait. For more about the concept of iterators
33/// generally, please see the [module-level documentation]. In particular, you
34/// may want to know how to [implement `Iterator`][impl].
35///
36/// [module-level documentation]: crate::iter
37/// [impl]: crate::iter#implementing-iterator
38#[stable(feature = "rust1", since = "1.0.0")]
39#[rustc_on_unimplemented(
40 on(
41 Self = "core::ops::range::RangeTo<Idx>",
42 note = "you might have meant to use a bounded `Range`"
43 ),
44 on(
45 Self = "core::ops::range::RangeToInclusive<Idx>",
46 note = "you might have meant to use a bounded `RangeInclusive`"
47 ),
48 label = "`{Self}` is not an iterator",
49 message = "`{Self}` is not an iterator"
50)]
51#[cfg_attr(not(feature = "ferrocene_subset"), doc(notable_trait))]
52#[lang = "iterator"]
53#[rustc_diagnostic_item = "Iterator"]
54#[must_use = "iterators are lazy and do nothing unless consumed"]
55#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
56pub const trait Iterator {
57 /// The type of the elements being iterated over.
58 #[rustc_diagnostic_item = "IteratorItem"]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 type Item;
61
62 /// Advances the iterator and returns the next value.
63 ///
64 /// Returns [`None`] when iteration is finished. Individual iterator
65 /// implementations may choose to resume iteration, and so calling `next()`
66 /// again may or may not eventually start returning [`Some(Item)`] again at some
67 /// point.
68 ///
69 /// [`Some(Item)`]: Some
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// let a = [1, 2, 3];
75 ///
76 /// let mut iter = a.into_iter();
77 ///
78 /// // A call to next() returns the next value...
79 /// assert_eq!(Some(1), iter.next());
80 /// assert_eq!(Some(2), iter.next());
81 /// assert_eq!(Some(3), iter.next());
82 ///
83 /// // ... and then None once it's over.
84 /// assert_eq!(None, iter.next());
85 ///
86 /// // More calls may or may not return `None`. Here, they always will.
87 /// assert_eq!(None, iter.next());
88 /// assert_eq!(None, iter.next());
89 /// ```
90 #[lang = "next"]
91 #[stable(feature = "rust1", since = "1.0.0")]
92 fn next(&mut self) -> Option<Self::Item>;
93
94 /// Advances the iterator and returns an array containing the next `N` values.
95 ///
96 /// If there are not enough elements to fill the array then `Err` is returned
97 /// containing an iterator over the remaining elements.
98 ///
99 /// # Examples
100 ///
101 /// Basic usage:
102 ///
103 /// ```
104 /// #![feature(iter_next_chunk)]
105 ///
106 /// let mut iter = "lorem".chars();
107 ///
108 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
109 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
110 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
111 /// ```
112 ///
113 /// Split a string and get the first three items.
114 ///
115 /// ```
116 /// #![feature(iter_next_chunk)]
117 ///
118 /// let quote = "not all those who wander are lost";
119 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
120 /// assert_eq!(first, "not");
121 /// assert_eq!(second, "all");
122 /// assert_eq!(third, "those");
123 /// ```
124 #[inline]
125 #[unstable(feature = "iter_next_chunk", issue = "98326")]
126 #[cfg(not(feature = "ferrocene_subset"))]
127 #[rustc_non_const_trait_method]
128 fn next_chunk<const N: usize>(
129 &mut self,
130 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
131 where
132 Self: Sized,
133 {
134 array::iter_next_chunk(self)
135 }
136
137 /// Returns the bounds on the remaining length of the iterator.
138 ///
139 /// Specifically, `size_hint()` returns a tuple where the first element
140 /// is the lower bound, and the second element is the upper bound.
141 ///
142 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
143 /// A [`None`] here means that either there is no known upper bound, or the
144 /// upper bound is larger than [`usize`].
145 ///
146 /// # Implementation notes
147 ///
148 /// It is not enforced that an iterator implementation yields the declared
149 /// number of elements. A buggy iterator may yield less than the lower bound
150 /// or more than the upper bound of elements.
151 ///
152 /// `size_hint()` is primarily intended to be used for optimizations such as
153 /// reserving space for the elements of the iterator, but must not be
154 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
155 /// implementation of `size_hint()` should not lead to memory safety
156 /// violations.
157 ///
158 /// That said, the implementation should provide a correct estimation,
159 /// because otherwise it would be a violation of the trait's protocol.
160 ///
161 /// The default implementation returns <code>(0, [None])</code> which is correct for any
162 /// iterator.
163 ///
164 /// # Examples
165 ///
166 /// Basic usage:
167 ///
168 /// ```
169 /// let a = [1, 2, 3];
170 /// let mut iter = a.iter();
171 ///
172 /// assert_eq!((3, Some(3)), iter.size_hint());
173 /// let _ = iter.next();
174 /// assert_eq!((2, Some(2)), iter.size_hint());
175 /// ```
176 ///
177 /// A more complex example:
178 ///
179 /// ```
180 /// // The even numbers in the range of zero to nine.
181 /// let iter = (0..10).filter(|x| x % 2 == 0);
182 ///
183 /// // We might iterate from zero to ten times. Knowing that it's five
184 /// // exactly wouldn't be possible without executing filter().
185 /// assert_eq!((0, Some(10)), iter.size_hint());
186 ///
187 /// // Let's add five more numbers with chain()
188 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
189 ///
190 /// // now both bounds are increased by five
191 /// assert_eq!((5, Some(15)), iter.size_hint());
192 /// ```
193 ///
194 /// Returning `None` for an upper bound:
195 ///
196 /// ```
197 /// // an infinite iterator has no upper bound
198 /// // and the maximum possible lower bound
199 /// let iter = 0..;
200 ///
201 /// assert_eq!((usize::MAX, None), iter.size_hint());
202 /// ```
203 #[inline]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn size_hint(&self) -> (usize, Option<usize>) {
206 (0, None)
207 }
208
209 /// Consumes the iterator, counting the number of iterations and returning it.
210 ///
211 /// This method will call [`next`] repeatedly until [`None`] is encountered,
212 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213 /// called at least once even if the iterator does not have any elements.
214 ///
215 /// [`next`]: Iterator::next
216 ///
217 /// # Overflow Behavior
218 ///
219 /// The method does no guarding against overflows, so counting elements of
220 /// an iterator with more than [`usize::MAX`] elements either produces the
221 /// wrong result or panics. If overflow checks are enabled, a panic is
222 /// guaranteed.
223 ///
224 /// # Panics
225 ///
226 /// This function might panic if the iterator has more than [`usize::MAX`]
227 /// elements.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// let a = [1, 2, 3];
233 /// assert_eq!(a.iter().count(), 3);
234 ///
235 /// let a = [1, 2, 3, 4, 5];
236 /// assert_eq!(a.iter().count(), 5);
237 /// ```
238 #[inline]
239 #[stable(feature = "rust1", since = "1.0.0")]
240 #[rustc_non_const_trait_method]
241 fn count(self) -> usize
242 where
243 Self: Sized,
244 {
245 self.fold(
246 0,
247 #[rustc_inherit_overflow_checks]
248 |count, _| count + 1,
249 )
250 }
251
252 /// Consumes the iterator, returning the last element.
253 ///
254 /// This method will evaluate the iterator until it returns [`None`]. While
255 /// doing so, it keeps track of the current element. After [`None`] is
256 /// returned, `last()` will then return the last element it saw.
257 ///
258 /// # Panics
259 ///
260 /// This function might panic if the iterator is infinite.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// let a = [1, 2, 3];
266 /// assert_eq!(a.into_iter().last(), Some(3));
267 ///
268 /// let a = [1, 2, 3, 4, 5];
269 /// assert_eq!(a.into_iter().last(), Some(5));
270 /// ```
271 #[inline]
272 #[stable(feature = "rust1", since = "1.0.0")]
273 #[rustc_non_const_trait_method]
274 fn last(self) -> Option<Self::Item>
275 where
276 Self: Sized,
277 {
278 #[inline]
279 fn some<T>(_: Option<T>, x: T) -> Option<T> {
280 Some(x)
281 }
282
283 self.fold(None, some)
284 }
285
286 /// Advances the iterator by `n` elements.
287 ///
288 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
289 /// times until [`None`] is encountered.
290 ///
291 /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
292 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
293 /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
294 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
295 /// Otherwise, `k` is always less than `n`.
296 ///
297 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
298 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
299 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
300 ///
301 /// [`Flatten`]: crate::iter::Flatten
302 /// [`next`]: Iterator::next
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// #![feature(iter_advance_by)]
308 ///
309 /// use std::num::NonZero;
310 ///
311 /// let a = [1, 2, 3, 4];
312 /// let mut iter = a.into_iter();
313 ///
314 /// assert_eq!(iter.advance_by(2), Ok(()));
315 /// assert_eq!(iter.next(), Some(3));
316 /// assert_eq!(iter.advance_by(0), Ok(()));
317 /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
318 /// ```
319 #[inline]
320 #[unstable(feature = "iter_advance_by", issue = "77404")]
321 #[rustc_non_const_trait_method]
322 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
323 /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.
324 trait SpecAdvanceBy {
325 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
326 }
327
328 impl<I: Iterator + ?Sized> SpecAdvanceBy for I {
329 default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
330 for i in 0..n {
331 if self.next().is_none() {
332 // SAFETY: `i` is always less than `n`.
333 return Err(unsafe { NonZero::new_unchecked(n - i) });
334 }
335 }
336 Ok(())
337 }
338 }
339
340 impl<I: Iterator> SpecAdvanceBy for I {
341 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
342 let Some(n) = NonZero::new(n) else {
343 return Ok(());
344 };
345
346 let res = self.try_fold(n, |n, _| NonZero::new(n.get() - 1));
347
348 match res {
349 None => Ok(()),
350 Some(n) => Err(n),
351 }
352 }
353 }
354
355 self.spec_advance_by(n)
356 }
357
358 /// Returns the `n`th element of the iterator.
359 ///
360 /// Like most indexing operations, the count starts from zero, so `nth(0)`
361 /// returns the first value, `nth(1)` the second, and so on.
362 ///
363 /// Note that all preceding elements, as well as the returned element, will be
364 /// consumed from the iterator. That means that the preceding elements will be
365 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
366 /// will return different elements.
367 ///
368 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
369 /// iterator.
370 ///
371 /// # Examples
372 ///
373 /// Basic usage:
374 ///
375 /// ```
376 /// let a = [1, 2, 3];
377 /// assert_eq!(a.into_iter().nth(1), Some(2));
378 /// ```
379 ///
380 /// Calling `nth()` multiple times doesn't rewind the iterator:
381 ///
382 /// ```
383 /// let a = [1, 2, 3];
384 ///
385 /// let mut iter = a.into_iter();
386 ///
387 /// assert_eq!(iter.nth(1), Some(2));
388 /// assert_eq!(iter.nth(1), None);
389 /// ```
390 ///
391 /// Returning `None` if there are less than `n + 1` elements:
392 ///
393 /// ```
394 /// let a = [1, 2, 3];
395 /// assert_eq!(a.into_iter().nth(10), None);
396 /// ```
397 #[inline]
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[rustc_non_const_trait_method]
400 fn nth(&mut self, n: usize) -> Option<Self::Item> {
401 self.advance_by(n).ok()?;
402 self.next()
403 }
404
405 /// Creates an iterator starting at the same point, but stepping by
406 /// the given amount at each iteration.
407 ///
408 /// Note 1: The first element of the iterator will always be returned,
409 /// regardless of the step given.
410 ///
411 /// Note 2: The time at which ignored elements are pulled is not fixed.
412 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
413 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
414 /// `advance_n_and_return_first(&mut self, step)`,
415 /// `advance_n_and_return_first(&mut self, step)`, …
416 /// Which way is used may change for some iterators for performance reasons.
417 /// The second way will advance the iterator earlier and may consume more items.
418 ///
419 /// `advance_n_and_return_first` is the equivalent of:
420 /// ```
421 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
422 /// where
423 /// I: Iterator,
424 /// {
425 /// let next = iter.next();
426 /// if n > 1 {
427 /// iter.nth(n - 2);
428 /// }
429 /// next
430 /// }
431 /// ```
432 ///
433 /// # Panics
434 ///
435 /// The method will panic if the given step is `0`.
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// let a = [0, 1, 2, 3, 4, 5];
441 /// let mut iter = a.into_iter().step_by(2);
442 ///
443 /// assert_eq!(iter.next(), Some(0));
444 /// assert_eq!(iter.next(), Some(2));
445 /// assert_eq!(iter.next(), Some(4));
446 /// assert_eq!(iter.next(), None);
447 /// ```
448 #[inline]
449 #[stable(feature = "iterator_step_by", since = "1.28.0")]
450 #[rustc_non_const_trait_method]
451 fn step_by(self, step: usize) -> StepBy<Self>
452 where
453 Self: Sized,
454 {
455 StepBy::new(self, step)
456 }
457
458 /// Takes two iterators and creates a new iterator over both in sequence.
459 ///
460 /// `chain()` will return a new iterator which will first iterate over
461 /// values from the first iterator and then over values from the second
462 /// iterator.
463 ///
464 /// In other words, it links two iterators together, in a chain. 🔗
465 ///
466 /// [`once`] is commonly used to adapt a single value into a chain of
467 /// other kinds of iteration.
468 ///
469 /// # Examples
470 ///
471 /// Basic usage:
472 ///
473 /// ```
474 /// let s1 = "abc".chars();
475 /// let s2 = "def".chars();
476 ///
477 /// let mut iter = s1.chain(s2);
478 ///
479 /// assert_eq!(iter.next(), Some('a'));
480 /// assert_eq!(iter.next(), Some('b'));
481 /// assert_eq!(iter.next(), Some('c'));
482 /// assert_eq!(iter.next(), Some('d'));
483 /// assert_eq!(iter.next(), Some('e'));
484 /// assert_eq!(iter.next(), Some('f'));
485 /// assert_eq!(iter.next(), None);
486 /// ```
487 ///
488 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
489 /// anything that can be converted into an [`Iterator`], not just an
490 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
491 /// [`IntoIterator`], and so can be passed to `chain()` directly:
492 ///
493 /// ```
494 /// let a1 = [1, 2, 3];
495 /// let a2 = [4, 5, 6];
496 ///
497 /// let mut iter = a1.into_iter().chain(a2);
498 ///
499 /// assert_eq!(iter.next(), Some(1));
500 /// assert_eq!(iter.next(), Some(2));
501 /// assert_eq!(iter.next(), Some(3));
502 /// assert_eq!(iter.next(), Some(4));
503 /// assert_eq!(iter.next(), Some(5));
504 /// assert_eq!(iter.next(), Some(6));
505 /// assert_eq!(iter.next(), None);
506 /// ```
507 ///
508 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
509 ///
510 /// ```
511 /// #[cfg(windows)]
512 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
513 /// use std::os::windows::ffi::OsStrExt;
514 /// s.encode_wide().chain(std::iter::once(0)).collect()
515 /// }
516 /// ```
517 ///
518 /// [`once`]: crate::iter::once
519 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
520 #[inline]
521 #[stable(feature = "rust1", since = "1.0.0")]
522 #[rustc_non_const_trait_method]
523 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
524 where
525 Self: Sized,
526 U: IntoIterator<Item = Self::Item>,
527 {
528 Chain::new(self, other.into_iter())
529 }
530
531 /// 'Zips up' two iterators into a single iterator of pairs.
532 ///
533 /// `zip()` returns a new iterator that will iterate over two other
534 /// iterators, returning a tuple where the first element comes from the
535 /// first iterator, and the second element comes from the second iterator.
536 ///
537 /// In other words, it zips two iterators together, into a single one.
538 ///
539 /// If either iterator returns [`None`], [`next`] from the zipped iterator
540 /// will return [`None`].
541 /// If the zipped iterator has no more elements to return then each further attempt to advance
542 /// it will first try to advance the first iterator at most one time and if it still yielded an item
543 /// try to advance the second iterator at most one time.
544 ///
545 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
546 ///
547 /// [`unzip`]: Iterator::unzip
548 ///
549 /// # Examples
550 ///
551 /// Basic usage:
552 ///
553 /// ```
554 /// let s1 = "abc".chars();
555 /// let s2 = "def".chars();
556 ///
557 /// let mut iter = s1.zip(s2);
558 ///
559 /// assert_eq!(iter.next(), Some(('a', 'd')));
560 /// assert_eq!(iter.next(), Some(('b', 'e')));
561 /// assert_eq!(iter.next(), Some(('c', 'f')));
562 /// assert_eq!(iter.next(), None);
563 /// ```
564 ///
565 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
566 /// anything that can be converted into an [`Iterator`], not just an
567 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
568 /// [`IntoIterator`], and so can be passed to `zip()` directly:
569 ///
570 /// ```
571 /// let a1 = [1, 2, 3];
572 /// let a2 = [4, 5, 6];
573 ///
574 /// let mut iter = a1.into_iter().zip(a2);
575 ///
576 /// assert_eq!(iter.next(), Some((1, 4)));
577 /// assert_eq!(iter.next(), Some((2, 5)));
578 /// assert_eq!(iter.next(), Some((3, 6)));
579 /// assert_eq!(iter.next(), None);
580 /// ```
581 ///
582 /// `zip()` is often used to zip an infinite iterator to a finite one.
583 /// This works because the finite iterator will eventually return [`None`],
584 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
585 ///
586 /// ```
587 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
588 ///
589 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
590 ///
591 /// assert_eq!((0, 'f'), enumerate[0]);
592 /// assert_eq!((0, 'f'), zipper[0]);
593 ///
594 /// assert_eq!((1, 'o'), enumerate[1]);
595 /// assert_eq!((1, 'o'), zipper[1]);
596 ///
597 /// assert_eq!((2, 'o'), enumerate[2]);
598 /// assert_eq!((2, 'o'), zipper[2]);
599 /// ```
600 ///
601 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
602 ///
603 /// ```
604 /// use std::iter::zip;
605 ///
606 /// let a = [1, 2, 3];
607 /// let b = [2, 3, 4];
608 ///
609 /// let mut zipped = zip(
610 /// a.into_iter().map(|x| x * 2).skip(1),
611 /// b.into_iter().map(|x| x * 2).skip(1),
612 /// );
613 ///
614 /// assert_eq!(zipped.next(), Some((4, 6)));
615 /// assert_eq!(zipped.next(), Some((6, 8)));
616 /// assert_eq!(zipped.next(), None);
617 /// ```
618 ///
619 /// compared to:
620 ///
621 /// ```
622 /// # let a = [1, 2, 3];
623 /// # let b = [2, 3, 4];
624 /// #
625 /// let mut zipped = a
626 /// .into_iter()
627 /// .map(|x| x * 2)
628 /// .skip(1)
629 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
630 /// #
631 /// # assert_eq!(zipped.next(), Some((4, 6)));
632 /// # assert_eq!(zipped.next(), Some((6, 8)));
633 /// # assert_eq!(zipped.next(), None);
634 /// ```
635 ///
636 /// [`enumerate`]: Iterator::enumerate
637 /// [`next`]: Iterator::next
638 /// [`zip`]: crate::iter::zip
639 #[inline]
640 #[stable(feature = "rust1", since = "1.0.0")]
641 #[rustc_non_const_trait_method]
642 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
643 where
644 Self: Sized,
645 U: IntoIterator,
646 {
647 Zip::new(self, other.into_iter())
648 }
649
650 /// Creates a new iterator which places a copy of `separator` between items
651 /// of the original iterator.
652 ///
653 /// Specifically on fused iterators, it is guaranteed that the new iterator
654 /// places a copy of `separator` between adjacent `Some(_)` items. However,
655 /// for non-fused iterators, [`intersperse`] will create a new iterator that
656 /// is a fused version of the original iterator and place a copy of `separator`
657 /// between adjacent `Some(_)` items. This behavior for non-fused iterators
658 /// is subject to change.
659 ///
660 /// In case `separator` does not implement [`Clone`] or needs to be
661 /// computed every time, use [`intersperse_with`].
662 ///
663 /// # Examples
664 ///
665 /// Basic usage:
666 ///
667 /// ```
668 /// #![feature(iter_intersperse)]
669 ///
670 /// let mut a = [0, 1, 2].into_iter().intersperse(100);
671 /// assert_eq!(a.next(), Some(0)); // The first element from `a`.
672 /// assert_eq!(a.next(), Some(100)); // The separator.
673 /// assert_eq!(a.next(), Some(1)); // The next element from `a`.
674 /// assert_eq!(a.next(), Some(100)); // The separator.
675 /// assert_eq!(a.next(), Some(2)); // The last element from `a`.
676 /// assert_eq!(a.next(), None); // The iterator is finished.
677 /// ```
678 ///
679 /// `intersperse` can be very useful to join an iterator's items using a common element:
680 /// ```
681 /// #![feature(iter_intersperse)]
682 ///
683 /// let words = ["Hello", "World", "!"];
684 /// let hello: String = words.into_iter().intersperse(" ").collect();
685 /// assert_eq!(hello, "Hello World !");
686 /// ```
687 ///
688 /// [`Clone`]: crate::clone::Clone
689 /// [`intersperse`]: Iterator::intersperse
690 /// [`intersperse_with`]: Iterator::intersperse_with
691 #[inline]
692 #[unstable(feature = "iter_intersperse", issue = "79524")]
693 #[cfg(not(feature = "ferrocene_subset"))]
694 #[rustc_non_const_trait_method]
695 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
696 where
697 Self: Sized,
698 Self::Item: Clone,
699 {
700 Intersperse::new(self, separator)
701 }
702
703 /// Creates a new iterator which places an item generated by `separator`
704 /// between items of the original iterator.
705 ///
706 /// Specifically on fused iterators, it is guaranteed that the new iterator
707 /// places an item generated by `separator` between adjacent `Some(_)` items.
708 /// However, for non-fused iterators, [`intersperse_with`] will create a new
709 /// iterator that is a fused version of the original iterator and place an item
710 /// generated by `separator` between adjacent `Some(_)` items. This
711 /// behavior for non-fused iterators is subject to change.
712 ///
713 /// The `separator` closure will be called exactly once each time an item
714 /// is placed between two adjacent items from the underlying iterator;
715 /// specifically, the closure is not called if the underlying iterator yields
716 /// less than two items and after the last item is yielded.
717 ///
718 /// If the iterator's item implements [`Clone`], it may be easier to use
719 /// [`intersperse`].
720 ///
721 /// # Examples
722 ///
723 /// Basic usage:
724 ///
725 /// ```
726 /// #![feature(iter_intersperse)]
727 ///
728 /// #[derive(PartialEq, Debug)]
729 /// struct NotClone(usize);
730 ///
731 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
732 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
733 ///
734 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
735 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
736 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
737 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
738 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
739 /// assert_eq!(it.next(), None); // The iterator is finished.
740 /// ```
741 ///
742 /// `intersperse_with` can be used in situations where the separator needs
743 /// to be computed:
744 /// ```
745 /// #![feature(iter_intersperse)]
746 ///
747 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
748 ///
749 /// // The closure mutably borrows its context to generate an item.
750 /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
751 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
752 ///
753 /// let result = src.intersperse_with(separator).collect::<String>();
754 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
755 /// ```
756 /// [`Clone`]: crate::clone::Clone
757 /// [`intersperse`]: Iterator::intersperse
758 /// [`intersperse_with`]: Iterator::intersperse_with
759 #[inline]
760 #[unstable(feature = "iter_intersperse", issue = "79524")]
761 #[cfg(not(feature = "ferrocene_subset"))]
762 #[rustc_non_const_trait_method]
763 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
764 where
765 Self: Sized,
766 G: FnMut() -> Self::Item,
767 {
768 IntersperseWith::new(self, separator)
769 }
770
771 /// Takes a closure and creates an iterator which calls that closure on each
772 /// element.
773 ///
774 /// `map()` transforms one iterator into another, by means of its argument:
775 /// something that implements [`FnMut`]. It produces a new iterator which
776 /// calls this closure on each element of the original iterator.
777 ///
778 /// If you are good at thinking in types, you can think of `map()` like this:
779 /// If you have an iterator that gives you elements of some type `A`, and
780 /// you want an iterator of some other type `B`, you can use `map()`,
781 /// passing a closure that takes an `A` and returns a `B`.
782 ///
783 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
784 /// lazy, it is best used when you're already working with other iterators.
785 /// If you're doing some sort of looping for a side effect, it's considered
786 /// more idiomatic to use [`for`] than `map()`.
787 ///
788 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
789 ///
790 /// # Examples
791 ///
792 /// Basic usage:
793 ///
794 /// ```
795 /// let a = [1, 2, 3];
796 ///
797 /// let mut iter = a.iter().map(|x| 2 * x);
798 ///
799 /// assert_eq!(iter.next(), Some(2));
800 /// assert_eq!(iter.next(), Some(4));
801 /// assert_eq!(iter.next(), Some(6));
802 /// assert_eq!(iter.next(), None);
803 /// ```
804 ///
805 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
806 ///
807 /// ```
808 /// # #![allow(unused_must_use)]
809 /// // don't do this:
810 /// (0..5).map(|x| println!("{x}"));
811 ///
812 /// // it won't even execute, as it is lazy. Rust will warn you about this.
813 ///
814 /// // Instead, use a for-loop:
815 /// for x in 0..5 {
816 /// println!("{x}");
817 /// }
818 /// ```
819 #[rustc_diagnostic_item = "IteratorMap"]
820 #[inline]
821 #[stable(feature = "rust1", since = "1.0.0")]
822 #[rustc_non_const_trait_method]
823 fn map<B, F>(self, f: F) -> Map<Self, F>
824 where
825 Self: Sized,
826 F: FnMut(Self::Item) -> B,
827 {
828 Map::new(self, f)
829 }
830
831 /// Calls a closure on each element of an iterator.
832 ///
833 /// This is equivalent to using a [`for`] loop on the iterator, although
834 /// `break` and `continue` are not possible from a closure. It's generally
835 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
836 /// when processing items at the end of longer iterator chains. In some
837 /// cases `for_each` may also be faster than a loop, because it will use
838 /// internal iteration on adapters like `Chain`.
839 ///
840 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
841 ///
842 /// # Examples
843 ///
844 /// Basic usage:
845 ///
846 /// ```
847 /// use std::sync::mpsc::channel;
848 ///
849 /// let (tx, rx) = channel();
850 /// (0..5).map(|x| x * 2 + 1)
851 /// .for_each(move |x| tx.send(x).unwrap());
852 ///
853 /// let v: Vec<_> = rx.iter().collect();
854 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
855 /// ```
856 ///
857 /// For such a small example, a `for` loop may be cleaner, but `for_each`
858 /// might be preferable to keep a functional style with longer iterators:
859 ///
860 /// ```
861 /// (0..5).flat_map(|x| (x * 100)..(x * 110))
862 /// .enumerate()
863 /// .filter(|&(i, x)| (i + x) % 3 == 0)
864 /// .for_each(|(i, x)| println!("{i}:{x}"));
865 /// ```
866 #[inline]
867 #[stable(feature = "iterator_for_each", since = "1.21.0")]
868 #[rustc_non_const_trait_method]
869 fn for_each<F>(self, f: F)
870 where
871 Self: Sized,
872 F: FnMut(Self::Item),
873 {
874 #[inline]
875 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
876 move |(), item| f(item)
877 }
878
879 self.fold((), call(f));
880 }
881
882 /// Creates an iterator which uses a closure to determine if an element
883 /// should be yielded.
884 ///
885 /// Given an element the closure must return `true` or `false`. The returned
886 /// iterator will yield only the elements for which the closure returns
887 /// `true`.
888 ///
889 /// # Examples
890 ///
891 /// Basic usage:
892 ///
893 /// ```
894 /// let a = [0i32, 1, 2];
895 ///
896 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
897 ///
898 /// assert_eq!(iter.next(), Some(1));
899 /// assert_eq!(iter.next(), Some(2));
900 /// assert_eq!(iter.next(), None);
901 /// ```
902 ///
903 /// Because the closure passed to `filter()` takes a reference, and many
904 /// iterators iterate over references, this leads to a possibly confusing
905 /// situation, where the type of the closure is a double reference:
906 ///
907 /// ```
908 /// let s = &[0, 1, 2];
909 ///
910 /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!
911 ///
912 /// assert_eq!(iter.next(), Some(&2));
913 /// assert_eq!(iter.next(), None);
914 /// ```
915 ///
916 /// It's common to instead use destructuring on the argument to strip away one:
917 ///
918 /// ```
919 /// let s = &[0, 1, 2];
920 ///
921 /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *
922 ///
923 /// assert_eq!(iter.next(), Some(&2));
924 /// assert_eq!(iter.next(), None);
925 /// ```
926 ///
927 /// or both:
928 ///
929 /// ```
930 /// let s = &[0, 1, 2];
931 ///
932 /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s
933 ///
934 /// assert_eq!(iter.next(), Some(&2));
935 /// assert_eq!(iter.next(), None);
936 /// ```
937 ///
938 /// of these layers.
939 ///
940 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
941 #[inline]
942 #[stable(feature = "rust1", since = "1.0.0")]
943 #[rustc_diagnostic_item = "iter_filter"]
944 #[rustc_non_const_trait_method]
945 fn filter<P>(self, predicate: P) -> Filter<Self, P>
946 where
947 Self: Sized,
948 P: FnMut(&Self::Item) -> bool,
949 {
950 Filter::new(self, predicate)
951 }
952
953 /// Creates an iterator that both filters and maps.
954 ///
955 /// The returned iterator yields only the `value`s for which the supplied
956 /// closure returns `Some(value)`.
957 ///
958 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
959 /// concise. The example below shows how a `map().filter().map()` can be
960 /// shortened to a single call to `filter_map`.
961 ///
962 /// [`filter`]: Iterator::filter
963 /// [`map`]: Iterator::map
964 ///
965 /// # Examples
966 ///
967 /// Basic usage:
968 ///
969 /// ```
970 /// let a = ["1", "two", "NaN", "four", "5"];
971 ///
972 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
973 ///
974 /// assert_eq!(iter.next(), Some(1));
975 /// assert_eq!(iter.next(), Some(5));
976 /// assert_eq!(iter.next(), None);
977 /// ```
978 ///
979 /// Here's the same example, but with [`filter`] and [`map`]:
980 ///
981 /// ```
982 /// let a = ["1", "two", "NaN", "four", "5"];
983 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
984 /// assert_eq!(iter.next(), Some(1));
985 /// assert_eq!(iter.next(), Some(5));
986 /// assert_eq!(iter.next(), None);
987 /// ```
988 #[inline]
989 #[stable(feature = "rust1", since = "1.0.0")]
990 #[cfg(not(feature = "ferrocene_subset"))]
991 #[rustc_non_const_trait_method]
992 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
993 where
994 Self: Sized,
995 F: FnMut(Self::Item) -> Option<B>,
996 {
997 FilterMap::new(self, f)
998 }
999
1000 /// Creates an iterator which gives the current iteration count as well as
1001 /// the next value.
1002 ///
1003 /// The iterator returned yields pairs `(i, val)`, where `i` is the
1004 /// current index of iteration and `val` is the value returned by the
1005 /// iterator.
1006 ///
1007 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
1008 /// different sized integer, the [`zip`] function provides similar
1009 /// functionality.
1010 ///
1011 /// # Overflow Behavior
1012 ///
1013 /// The method does no guarding against overflows, so enumerating more than
1014 /// [`usize::MAX`] elements either produces the wrong result or panics. If
1015 /// overflow checks are enabled, a panic is guaranteed.
1016 ///
1017 /// # Panics
1018 ///
1019 /// The returned iterator might panic if the to-be-returned index would
1020 /// overflow a [`usize`].
1021 ///
1022 /// [`zip`]: Iterator::zip
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```
1027 /// let a = ['a', 'b', 'c'];
1028 ///
1029 /// let mut iter = a.into_iter().enumerate();
1030 ///
1031 /// assert_eq!(iter.next(), Some((0, 'a')));
1032 /// assert_eq!(iter.next(), Some((1, 'b')));
1033 /// assert_eq!(iter.next(), Some((2, 'c')));
1034 /// assert_eq!(iter.next(), None);
1035 /// ```
1036 #[inline]
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 #[rustc_diagnostic_item = "enumerate_method"]
1039 #[rustc_non_const_trait_method]
1040 fn enumerate(self) -> Enumerate<Self>
1041 where
1042 Self: Sized,
1043 {
1044 Enumerate::new(self)
1045 }
1046
1047 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
1048 /// to look at the next element of the iterator without consuming it. See
1049 /// their documentation for more information.
1050 ///
1051 /// Note that the underlying iterator is still advanced when [`peek`] or
1052 /// [`peek_mut`] are called for the first time: In order to retrieve the
1053 /// next element, [`next`] is called on the underlying iterator, hence any
1054 /// side effects (i.e. anything other than fetching the next value) of
1055 /// the [`next`] method will occur.
1056 ///
1057 ///
1058 /// # Examples
1059 ///
1060 /// Basic usage:
1061 ///
1062 /// ```
1063 /// let xs = [1, 2, 3];
1064 ///
1065 /// let mut iter = xs.into_iter().peekable();
1066 ///
1067 /// // peek() lets us see into the future
1068 /// assert_eq!(iter.peek(), Some(&1));
1069 /// assert_eq!(iter.next(), Some(1));
1070 ///
1071 /// assert_eq!(iter.next(), Some(2));
1072 ///
1073 /// // we can peek() multiple times, the iterator won't advance
1074 /// assert_eq!(iter.peek(), Some(&3));
1075 /// assert_eq!(iter.peek(), Some(&3));
1076 ///
1077 /// assert_eq!(iter.next(), Some(3));
1078 ///
1079 /// // after the iterator is finished, so is peek()
1080 /// assert_eq!(iter.peek(), None);
1081 /// assert_eq!(iter.next(), None);
1082 /// ```
1083 ///
1084 /// Using [`peek_mut`] to mutate the next item without advancing the
1085 /// iterator:
1086 ///
1087 /// ```
1088 /// let xs = [1, 2, 3];
1089 ///
1090 /// let mut iter = xs.into_iter().peekable();
1091 ///
1092 /// // `peek_mut()` lets us see into the future
1093 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1094 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1095 /// assert_eq!(iter.next(), Some(1));
1096 ///
1097 /// if let Some(p) = iter.peek_mut() {
1098 /// assert_eq!(*p, 2);
1099 /// // put a value into the iterator
1100 /// *p = 1000;
1101 /// }
1102 ///
1103 /// // The value reappears as the iterator continues
1104 /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);
1105 /// ```
1106 /// [`peek`]: Peekable::peek
1107 /// [`peek_mut`]: Peekable::peek_mut
1108 /// [`next`]: Iterator::next
1109 #[inline]
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 #[cfg(not(feature = "ferrocene_subset"))]
1112 #[rustc_non_const_trait_method]
1113 fn peekable(self) -> Peekable<Self>
1114 where
1115 Self: Sized,
1116 {
1117 Peekable::new(self)
1118 }
1119
1120 /// Creates an iterator that [`skip`]s elements based on a predicate.
1121 ///
1122 /// [`skip`]: Iterator::skip
1123 ///
1124 /// `skip_while()` takes a closure as an argument. It will call this
1125 /// closure on each element of the iterator, and ignore elements
1126 /// until it returns `false`.
1127 ///
1128 /// After `false` is returned, `skip_while()`'s job is over, and the
1129 /// rest of the elements are yielded.
1130 ///
1131 /// # Examples
1132 ///
1133 /// Basic usage:
1134 ///
1135 /// ```
1136 /// let a = [-1i32, 0, 1];
1137 ///
1138 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
1139 ///
1140 /// assert_eq!(iter.next(), Some(0));
1141 /// assert_eq!(iter.next(), Some(1));
1142 /// assert_eq!(iter.next(), None);
1143 /// ```
1144 ///
1145 /// Because the closure passed to `skip_while()` takes a reference, and many
1146 /// iterators iterate over references, this leads to a possibly confusing
1147 /// situation, where the type of the closure argument is a double reference:
1148 ///
1149 /// ```
1150 /// let s = &[-1, 0, 1];
1151 ///
1152 /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!
1153 ///
1154 /// assert_eq!(iter.next(), Some(&0));
1155 /// assert_eq!(iter.next(), Some(&1));
1156 /// assert_eq!(iter.next(), None);
1157 /// ```
1158 ///
1159 /// Stopping after an initial `false`:
1160 ///
1161 /// ```
1162 /// let a = [-1, 0, 1, -2];
1163 ///
1164 /// let mut iter = a.into_iter().skip_while(|&x| x < 0);
1165 ///
1166 /// assert_eq!(iter.next(), Some(0));
1167 /// assert_eq!(iter.next(), Some(1));
1168 ///
1169 /// // while this would have been false, since we already got a false,
1170 /// // skip_while() isn't used any more
1171 /// assert_eq!(iter.next(), Some(-2));
1172 ///
1173 /// assert_eq!(iter.next(), None);
1174 /// ```
1175 #[inline]
1176 #[doc(alias = "drop_while")]
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 #[cfg(not(feature = "ferrocene_subset"))]
1179 #[rustc_non_const_trait_method]
1180 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1181 where
1182 Self: Sized,
1183 P: FnMut(&Self::Item) -> bool,
1184 {
1185 SkipWhile::new(self, predicate)
1186 }
1187
1188 /// Creates an iterator that yields elements based on a predicate.
1189 ///
1190 /// `take_while()` takes a closure as an argument. It will call this
1191 /// closure on each element of the iterator, and yield elements
1192 /// while it returns `true`.
1193 ///
1194 /// After `false` is returned, `take_while()`'s job is over, and the
1195 /// rest of the elements are ignored.
1196 ///
1197 /// # Examples
1198 ///
1199 /// Basic usage:
1200 ///
1201 /// ```
1202 /// let a = [-1i32, 0, 1];
1203 ///
1204 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1205 ///
1206 /// assert_eq!(iter.next(), Some(-1));
1207 /// assert_eq!(iter.next(), None);
1208 /// ```
1209 ///
1210 /// Because the closure passed to `take_while()` takes a reference, and many
1211 /// iterators iterate over references, this leads to a possibly confusing
1212 /// situation, where the type of the closure is a double reference:
1213 ///
1214 /// ```
1215 /// let s = &[-1, 0, 1];
1216 ///
1217 /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!
1218 ///
1219 /// assert_eq!(iter.next(), Some(&-1));
1220 /// assert_eq!(iter.next(), None);
1221 /// ```
1222 ///
1223 /// Stopping after an initial `false`:
1224 ///
1225 /// ```
1226 /// let a = [-1, 0, 1, -2];
1227 ///
1228 /// let mut iter = a.into_iter().take_while(|&x| x < 0);
1229 ///
1230 /// assert_eq!(iter.next(), Some(-1));
1231 ///
1232 /// // We have more elements that are less than zero, but since we already
1233 /// // got a false, take_while() ignores the remaining elements.
1234 /// assert_eq!(iter.next(), None);
1235 /// ```
1236 ///
1237 /// Because `take_while()` needs to look at the value in order to see if it
1238 /// should be included or not, consuming iterators will see that it is
1239 /// removed:
1240 ///
1241 /// ```
1242 /// let a = [1, 2, 3, 4];
1243 /// let mut iter = a.into_iter();
1244 ///
1245 /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();
1246 ///
1247 /// assert_eq!(result, [1, 2]);
1248 ///
1249 /// let result: Vec<i32> = iter.collect();
1250 ///
1251 /// assert_eq!(result, [4]);
1252 /// ```
1253 ///
1254 /// The `3` is no longer there, because it was consumed in order to see if
1255 /// the iteration should stop, but wasn't placed back into the iterator.
1256 #[inline]
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 #[rustc_non_const_trait_method]
1259 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1260 where
1261 Self: Sized,
1262 P: FnMut(&Self::Item) -> bool,
1263 {
1264 TakeWhile::new(self, predicate)
1265 }
1266
1267 /// Creates an iterator that both yields elements based on a predicate and maps.
1268 ///
1269 /// `map_while()` takes a closure as an argument. It will call this
1270 /// closure on each element of the iterator, and yield elements
1271 /// while it returns [`Some(_)`][`Some`].
1272 ///
1273 /// # Examples
1274 ///
1275 /// Basic usage:
1276 ///
1277 /// ```
1278 /// let a = [-1i32, 4, 0, 1];
1279 ///
1280 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1281 ///
1282 /// assert_eq!(iter.next(), Some(-16));
1283 /// assert_eq!(iter.next(), Some(4));
1284 /// assert_eq!(iter.next(), None);
1285 /// ```
1286 ///
1287 /// Here's the same example, but with [`take_while`] and [`map`]:
1288 ///
1289 /// [`take_while`]: Iterator::take_while
1290 /// [`map`]: Iterator::map
1291 ///
1292 /// ```
1293 /// let a = [-1i32, 4, 0, 1];
1294 ///
1295 /// let mut iter = a.into_iter()
1296 /// .map(|x| 16i32.checked_div(x))
1297 /// .take_while(|x| x.is_some())
1298 /// .map(|x| x.unwrap());
1299 ///
1300 /// assert_eq!(iter.next(), Some(-16));
1301 /// assert_eq!(iter.next(), Some(4));
1302 /// assert_eq!(iter.next(), None);
1303 /// ```
1304 ///
1305 /// Stopping after an initial [`None`]:
1306 ///
1307 /// ```
1308 /// let a = [0, 1, 2, -3, 4, 5, -6];
1309 ///
1310 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1311 /// let vec: Vec<_> = iter.collect();
1312 ///
1313 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1314 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1315 /// assert_eq!(vec, [0, 1, 2]);
1316 /// ```
1317 ///
1318 /// Because `map_while()` needs to look at the value in order to see if it
1319 /// should be included or not, consuming iterators will see that it is
1320 /// removed:
1321 ///
1322 /// ```
1323 /// let a = [1, 2, -3, 4];
1324 /// let mut iter = a.into_iter();
1325 ///
1326 /// let result: Vec<u32> = iter.by_ref()
1327 /// .map_while(|n| u32::try_from(n).ok())
1328 /// .collect();
1329 ///
1330 /// assert_eq!(result, [1, 2]);
1331 ///
1332 /// let result: Vec<i32> = iter.collect();
1333 ///
1334 /// assert_eq!(result, [4]);
1335 /// ```
1336 ///
1337 /// The `-3` is no longer there, because it was consumed in order to see if
1338 /// the iteration should stop, but wasn't placed back into the iterator.
1339 ///
1340 /// Note that unlike [`take_while`] this iterator is **not** fused.
1341 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1342 /// If you need a fused iterator, use [`fuse`].
1343 ///
1344 /// [`fuse`]: Iterator::fuse
1345 #[inline]
1346 #[stable(feature = "iter_map_while", since = "1.57.0")]
1347 #[cfg(not(feature = "ferrocene_subset"))]
1348 #[rustc_non_const_trait_method]
1349 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1350 where
1351 Self: Sized,
1352 P: FnMut(Self::Item) -> Option<B>,
1353 {
1354 MapWhile::new(self, predicate)
1355 }
1356
1357 /// Creates an iterator that skips the first `n` elements.
1358 ///
1359 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1360 /// iterator is reached (whichever happens first). After that, all the remaining
1361 /// elements are yielded. In particular, if the original iterator is too short,
1362 /// then the returned iterator is empty.
1363 ///
1364 /// Rather than overriding this method directly, instead override the `nth` method.
1365 ///
1366 /// # Examples
1367 ///
1368 /// ```
1369 /// let a = [1, 2, 3];
1370 ///
1371 /// let mut iter = a.into_iter().skip(2);
1372 ///
1373 /// assert_eq!(iter.next(), Some(3));
1374 /// assert_eq!(iter.next(), None);
1375 /// ```
1376 #[inline]
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 #[rustc_non_const_trait_method]
1379 fn skip(self, n: usize) -> Skip<Self>
1380 where
1381 Self: Sized,
1382 {
1383 Skip::new(self, n)
1384 }
1385
1386 /// Creates an iterator that yields the first `n` elements, or fewer
1387 /// if the underlying iterator ends sooner.
1388 ///
1389 /// `take(n)` yields elements until `n` elements are yielded or the end of
1390 /// the iterator is reached (whichever happens first).
1391 /// The returned iterator is a prefix of length `n` if the original iterator
1392 /// contains at least `n` elements, otherwise it contains all of the
1393 /// (fewer than `n`) elements of the original iterator.
1394 ///
1395 /// # Examples
1396 ///
1397 /// Basic usage:
1398 ///
1399 /// ```
1400 /// let a = [1, 2, 3];
1401 ///
1402 /// let mut iter = a.into_iter().take(2);
1403 ///
1404 /// assert_eq!(iter.next(), Some(1));
1405 /// assert_eq!(iter.next(), Some(2));
1406 /// assert_eq!(iter.next(), None);
1407 /// ```
1408 ///
1409 /// `take()` is often used with an infinite iterator, to make it finite:
1410 ///
1411 /// ```
1412 /// let mut iter = (0..).take(3);
1413 ///
1414 /// assert_eq!(iter.next(), Some(0));
1415 /// assert_eq!(iter.next(), Some(1));
1416 /// assert_eq!(iter.next(), Some(2));
1417 /// assert_eq!(iter.next(), None);
1418 /// ```
1419 ///
1420 /// If less than `n` elements are available,
1421 /// `take` will limit itself to the size of the underlying iterator:
1422 ///
1423 /// ```
1424 /// let v = [1, 2];
1425 /// let mut iter = v.into_iter().take(5);
1426 /// assert_eq!(iter.next(), Some(1));
1427 /// assert_eq!(iter.next(), Some(2));
1428 /// assert_eq!(iter.next(), None);
1429 /// ```
1430 ///
1431 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1432 /// continue using the original iterator:
1433 ///
1434 /// ```
1435 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1436 ///
1437 /// // Take the first two words.
1438 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1439 /// assert_eq!(hello_world, vec!["hello", "world"]);
1440 ///
1441 /// // Collect the rest of the words.
1442 /// // We can only do this because we used `by_ref` earlier.
1443 /// let of_rust: Vec<_> = words.collect();
1444 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1445 /// ```
1446 ///
1447 /// [`by_ref`]: Iterator::by_ref
1448 #[doc(alias = "limit")]
1449 #[inline]
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 #[rustc_non_const_trait_method]
1452 fn take(self, n: usize) -> Take<Self>
1453 where
1454 Self: Sized,
1455 {
1456 Take::new(self, n)
1457 }
1458
1459 /// An iterator adapter which, like [`fold`], holds internal state, but
1460 /// unlike [`fold`], produces a new iterator.
1461 ///
1462 /// [`fold`]: Iterator::fold
1463 ///
1464 /// `scan()` takes two arguments: an initial value which seeds the internal
1465 /// state, and a closure with two arguments, the first being a mutable
1466 /// reference to the internal state and the second an iterator element.
1467 /// The closure can assign to the internal state to share state between
1468 /// iterations.
1469 ///
1470 /// On iteration, the closure will be applied to each element of the
1471 /// iterator and the return value from the closure, an [`Option`], is
1472 /// returned by the `next` method. Thus the closure can return
1473 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1474 ///
1475 /// # Examples
1476 ///
1477 /// ```
1478 /// let a = [1, 2, 3, 4];
1479 ///
1480 /// let mut iter = a.into_iter().scan(1, |state, x| {
1481 /// // each iteration, we'll multiply the state by the element ...
1482 /// *state = *state * x;
1483 ///
1484 /// // ... and terminate if the state exceeds 6
1485 /// if *state > 6 {
1486 /// return None;
1487 /// }
1488 /// // ... else yield the negation of the state
1489 /// Some(-*state)
1490 /// });
1491 ///
1492 /// assert_eq!(iter.next(), Some(-1));
1493 /// assert_eq!(iter.next(), Some(-2));
1494 /// assert_eq!(iter.next(), Some(-6));
1495 /// assert_eq!(iter.next(), None);
1496 /// ```
1497 #[inline]
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 #[cfg(not(feature = "ferrocene_subset"))]
1500 #[rustc_non_const_trait_method]
1501 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1502 where
1503 Self: Sized,
1504 F: FnMut(&mut St, Self::Item) -> Option<B>,
1505 {
1506 Scan::new(self, initial_state, f)
1507 }
1508
1509 /// Creates an iterator that works like map, but flattens nested structure.
1510 ///
1511 /// The [`map`] adapter is very useful, but only when the closure
1512 /// argument produces values. If it produces an iterator instead, there's
1513 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1514 /// on its own.
1515 ///
1516 /// You can think of `flat_map(f)` as the semantic equivalent
1517 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1518 ///
1519 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1520 /// one item for each element, and `flat_map()`'s closure returns an
1521 /// iterator for each element.
1522 ///
1523 /// [`map`]: Iterator::map
1524 /// [`flatten`]: Iterator::flatten
1525 ///
1526 /// # Examples
1527 ///
1528 /// ```
1529 /// let words = ["alpha", "beta", "gamma"];
1530 ///
1531 /// // chars() returns an iterator
1532 /// let merged: String = words.iter()
1533 /// .flat_map(|s| s.chars())
1534 /// .collect();
1535 /// assert_eq!(merged, "alphabetagamma");
1536 /// ```
1537 #[inline]
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 #[rustc_non_const_trait_method]
1540 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1541 where
1542 Self: Sized,
1543 U: IntoIterator,
1544 F: FnMut(Self::Item) -> U,
1545 {
1546 FlatMap::new(self, f)
1547 }
1548
1549 /// Creates an iterator that flattens nested structure.
1550 ///
1551 /// This is useful when you have an iterator of iterators or an iterator of
1552 /// things that can be turned into iterators and you want to remove one
1553 /// level of indirection.
1554 ///
1555 /// # Examples
1556 ///
1557 /// Basic usage:
1558 ///
1559 /// ```
1560 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1561 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1562 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1563 /// ```
1564 ///
1565 /// Mapping and then flattening:
1566 ///
1567 /// ```
1568 /// let words = ["alpha", "beta", "gamma"];
1569 ///
1570 /// // chars() returns an iterator
1571 /// let merged: String = words.iter()
1572 /// .map(|s| s.chars())
1573 /// .flatten()
1574 /// .collect();
1575 /// assert_eq!(merged, "alphabetagamma");
1576 /// ```
1577 ///
1578 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1579 /// in this case since it conveys intent more clearly:
1580 ///
1581 /// ```
1582 /// let words = ["alpha", "beta", "gamma"];
1583 ///
1584 /// // chars() returns an iterator
1585 /// let merged: String = words.iter()
1586 /// .flat_map(|s| s.chars())
1587 /// .collect();
1588 /// assert_eq!(merged, "alphabetagamma");
1589 /// ```
1590 ///
1591 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1592 ///
1593 /// ```
1594 /// let options = vec![Some(123), Some(321), None, Some(231)];
1595 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1596 /// assert_eq!(flattened_options, [123, 321, 231]);
1597 ///
1598 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1599 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1600 /// assert_eq!(flattened_results, [123, 321, 231]);
1601 /// ```
1602 ///
1603 /// Flattening only removes one level of nesting at a time:
1604 ///
1605 /// ```
1606 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1607 ///
1608 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1609 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1610 ///
1611 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1612 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1613 /// ```
1614 ///
1615 /// Here we see that `flatten()` does not perform a "deep" flatten.
1616 /// Instead, only one level of nesting is removed. That is, if you
1617 /// `flatten()` a three-dimensional array, the result will be
1618 /// two-dimensional and not one-dimensional. To get a one-dimensional
1619 /// structure, you have to `flatten()` again.
1620 ///
1621 /// [`flat_map()`]: Iterator::flat_map
1622 #[inline]
1623 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1624 #[cfg(not(feature = "ferrocene_subset"))]
1625 #[rustc_non_const_trait_method]
1626 fn flatten(self) -> Flatten<Self>
1627 where
1628 Self: Sized,
1629 Self::Item: IntoIterator,
1630 {
1631 Flatten::new(self)
1632 }
1633
1634 /// Calls the given function `f` for each contiguous window of size `N` over
1635 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1636 /// the windows during mapping overlap as well.
1637 ///
1638 /// In the following example, the closure is called three times with the
1639 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1640 ///
1641 /// ```
1642 /// #![feature(iter_map_windows)]
1643 ///
1644 /// let strings = "abcd".chars()
1645 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1646 /// .collect::<Vec<String>>();
1647 ///
1648 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1649 /// ```
1650 ///
1651 /// Note that the const parameter `N` is usually inferred by the
1652 /// destructured argument in the closure.
1653 ///
1654 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1655 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1656 /// empty iterator.
1657 ///
1658 /// The returned iterator implements [`FusedIterator`], because once `self`
1659 /// returns `None`, even if it returns a `Some(T)` again in the next iterations,
1660 /// we cannot put it into a contiguous array buffer, and thus the returned iterator
1661 /// should be fused.
1662 ///
1663 /// [`slice::windows()`]: slice::windows
1664 /// [`FusedIterator`]: crate::iter::FusedIterator
1665 ///
1666 /// # Panics
1667 ///
1668 /// Panics if `N` is zero. This check will most probably get changed to a
1669 /// compile time error before this method gets stabilized.
1670 ///
1671 /// ```should_panic
1672 /// #![feature(iter_map_windows)]
1673 ///
1674 /// let iter = std::iter::repeat(0).map_windows(|&[]| ());
1675 /// ```
1676 ///
1677 /// # Examples
1678 ///
1679 /// Building the sums of neighboring numbers.
1680 ///
1681 /// ```
1682 /// #![feature(iter_map_windows)]
1683 ///
1684 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1685 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1686 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1687 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1688 /// assert_eq!(it.next(), None);
1689 /// ```
1690 ///
1691 /// Since the elements in the following example implement `Copy`, we can
1692 /// just copy the array and get an iterator over the windows.
1693 ///
1694 /// ```
1695 /// #![feature(iter_map_windows)]
1696 ///
1697 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1698 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1699 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1700 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1701 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1702 /// assert_eq!(it.next(), None);
1703 /// ```
1704 ///
1705 /// You can also use this function to check the sortedness of an iterator.
1706 /// For the simple case, rather use [`Iterator::is_sorted`].
1707 ///
1708 /// ```
1709 /// #![feature(iter_map_windows)]
1710 ///
1711 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1712 /// .map_windows(|[a, b]| a <= b);
1713 ///
1714 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1715 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1716 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1717 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1718 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1719 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1720 /// assert_eq!(it.next(), None);
1721 /// ```
1722 ///
1723 /// For non-fused iterators, they are fused after `map_windows`.
1724 ///
1725 /// ```
1726 /// #![feature(iter_map_windows)]
1727 ///
1728 /// #[derive(Default)]
1729 /// struct NonFusedIterator {
1730 /// state: i32,
1731 /// }
1732 ///
1733 /// impl Iterator for NonFusedIterator {
1734 /// type Item = i32;
1735 ///
1736 /// fn next(&mut self) -> Option<i32> {
1737 /// let val = self.state;
1738 /// self.state = self.state + 1;
1739 ///
1740 /// // yields `0..5` first, then only even numbers since `6..`.
1741 /// if val < 5 || val % 2 == 0 {
1742 /// Some(val)
1743 /// } else {
1744 /// None
1745 /// }
1746 /// }
1747 /// }
1748 ///
1749 ///
1750 /// let mut iter = NonFusedIterator::default();
1751 ///
1752 /// // yields 0..5 first.
1753 /// assert_eq!(iter.next(), Some(0));
1754 /// assert_eq!(iter.next(), Some(1));
1755 /// assert_eq!(iter.next(), Some(2));
1756 /// assert_eq!(iter.next(), Some(3));
1757 /// assert_eq!(iter.next(), Some(4));
1758 /// // then we can see our iterator going back and forth
1759 /// assert_eq!(iter.next(), None);
1760 /// assert_eq!(iter.next(), Some(6));
1761 /// assert_eq!(iter.next(), None);
1762 /// assert_eq!(iter.next(), Some(8));
1763 /// assert_eq!(iter.next(), None);
1764 ///
1765 /// // however, with `.map_windows()`, it is fused.
1766 /// let mut iter = NonFusedIterator::default()
1767 /// .map_windows(|arr: &[_; 2]| *arr);
1768 ///
1769 /// assert_eq!(iter.next(), Some([0, 1]));
1770 /// assert_eq!(iter.next(), Some([1, 2]));
1771 /// assert_eq!(iter.next(), Some([2, 3]));
1772 /// assert_eq!(iter.next(), Some([3, 4]));
1773 /// assert_eq!(iter.next(), None);
1774 ///
1775 /// // it will always return `None` after the first time.
1776 /// assert_eq!(iter.next(), None);
1777 /// assert_eq!(iter.next(), None);
1778 /// assert_eq!(iter.next(), None);
1779 /// ```
1780 #[inline]
1781 #[unstable(feature = "iter_map_windows", issue = "87155")]
1782 #[cfg(not(feature = "ferrocene_subset"))]
1783 #[rustc_non_const_trait_method]
1784 fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
1785 where
1786 Self: Sized,
1787 F: FnMut(&[Self::Item; N]) -> R,
1788 {
1789 MapWindows::new(self, f)
1790 }
1791
1792 /// Creates an iterator which ends after the first [`None`].
1793 ///
1794 /// After an iterator returns [`None`], future calls may or may not yield
1795 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1796 /// [`None`] is given, it will always return [`None`] forever.
1797 ///
1798 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1799 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1800 /// if the [`FusedIterator`] trait is improperly implemented.
1801 ///
1802 /// [`Some(T)`]: Some
1803 /// [`FusedIterator`]: crate::iter::FusedIterator
1804 ///
1805 /// # Examples
1806 ///
1807 /// ```
1808 /// // an iterator which alternates between Some and None
1809 /// struct Alternate {
1810 /// state: i32,
1811 /// }
1812 ///
1813 /// impl Iterator for Alternate {
1814 /// type Item = i32;
1815 ///
1816 /// fn next(&mut self) -> Option<i32> {
1817 /// let val = self.state;
1818 /// self.state = self.state + 1;
1819 ///
1820 /// // if it's even, Some(i32), else None
1821 /// (val % 2 == 0).then_some(val)
1822 /// }
1823 /// }
1824 ///
1825 /// let mut iter = Alternate { state: 0 };
1826 ///
1827 /// // we can see our iterator going back and forth
1828 /// assert_eq!(iter.next(), Some(0));
1829 /// assert_eq!(iter.next(), None);
1830 /// assert_eq!(iter.next(), Some(2));
1831 /// assert_eq!(iter.next(), None);
1832 ///
1833 /// // however, once we fuse it...
1834 /// let mut iter = iter.fuse();
1835 ///
1836 /// assert_eq!(iter.next(), Some(4));
1837 /// assert_eq!(iter.next(), None);
1838 ///
1839 /// // it will always return `None` after the first time.
1840 /// assert_eq!(iter.next(), None);
1841 /// assert_eq!(iter.next(), None);
1842 /// assert_eq!(iter.next(), None);
1843 /// ```
1844 #[inline]
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 #[rustc_non_const_trait_method]
1847 fn fuse(self) -> Fuse<Self>
1848 where
1849 Self: Sized,
1850 {
1851 Fuse::new(self)
1852 }
1853
1854 /// Does something with each element of an iterator, passing the value on.
1855 ///
1856 /// When using iterators, you'll often chain several of them together.
1857 /// While working on such code, you might want to check out what's
1858 /// happening at various parts in the pipeline. To do that, insert
1859 /// a call to `inspect()`.
1860 ///
1861 /// It's more common for `inspect()` to be used as a debugging tool than to
1862 /// exist in your final code, but applications may find it useful in certain
1863 /// situations when errors need to be logged before being discarded.
1864 ///
1865 /// # Examples
1866 ///
1867 /// Basic usage:
1868 ///
1869 /// ```
1870 /// let a = [1, 4, 2, 3];
1871 ///
1872 /// // this iterator sequence is complex.
1873 /// let sum = a.iter()
1874 /// .cloned()
1875 /// .filter(|x| x % 2 == 0)
1876 /// .fold(0, |sum, i| sum + i);
1877 ///
1878 /// println!("{sum}");
1879 ///
1880 /// // let's add some inspect() calls to investigate what's happening
1881 /// let sum = a.iter()
1882 /// .cloned()
1883 /// .inspect(|x| println!("about to filter: {x}"))
1884 /// .filter(|x| x % 2 == 0)
1885 /// .inspect(|x| println!("made it through filter: {x}"))
1886 /// .fold(0, |sum, i| sum + i);
1887 ///
1888 /// println!("{sum}");
1889 /// ```
1890 ///
1891 /// This will print:
1892 ///
1893 /// ```text
1894 /// 6
1895 /// about to filter: 1
1896 /// about to filter: 4
1897 /// made it through filter: 4
1898 /// about to filter: 2
1899 /// made it through filter: 2
1900 /// about to filter: 3
1901 /// 6
1902 /// ```
1903 ///
1904 /// Logging errors before discarding them:
1905 ///
1906 /// ```
1907 /// let lines = ["1", "2", "a"];
1908 ///
1909 /// let sum: i32 = lines
1910 /// .iter()
1911 /// .map(|line| line.parse::<i32>())
1912 /// .inspect(|num| {
1913 /// if let Err(ref e) = *num {
1914 /// println!("Parsing error: {e}");
1915 /// }
1916 /// })
1917 /// .filter_map(Result::ok)
1918 /// .sum();
1919 ///
1920 /// println!("Sum: {sum}");
1921 /// ```
1922 ///
1923 /// This will print:
1924 ///
1925 /// ```text
1926 /// Parsing error: invalid digit found in string
1927 /// Sum: 3
1928 /// ```
1929 #[inline]
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 #[cfg(not(feature = "ferrocene_subset"))]
1932 #[rustc_non_const_trait_method]
1933 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1934 where
1935 Self: Sized,
1936 F: FnMut(&Self::Item),
1937 {
1938 Inspect::new(self, f)
1939 }
1940
1941 /// Creates a "by reference" adapter for this instance of `Iterator`.
1942 ///
1943 /// Consuming method calls (direct or indirect calls to `next`)
1944 /// on the "by reference" adapter will consume the original iterator,
1945 /// but ownership-taking methods (those with a `self` parameter)
1946 /// only take ownership of the "by reference" iterator.
1947 ///
1948 /// This is useful for applying ownership-taking methods
1949 /// (such as `take` in the example below)
1950 /// without giving up ownership of the original iterator,
1951 /// so you can use the original iterator afterwards.
1952 ///
1953 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I).
1954 ///
1955 /// # Examples
1956 ///
1957 /// ```
1958 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1959 ///
1960 /// // Take the first two words.
1961 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1962 /// assert_eq!(hello_world, vec!["hello", "world"]);
1963 ///
1964 /// // Collect the rest of the words.
1965 /// // We can only do this because we used `by_ref` earlier.
1966 /// let of_rust: Vec<_> = words.collect();
1967 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1968 /// ```
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 fn by_ref(&mut self) -> &mut Self
1971 where
1972 Self: Sized,
1973 {
1974 self
1975 }
1976
1977 /// Transforms an iterator into a collection.
1978 ///
1979 /// `collect()` takes ownership of an iterator and produces whichever
1980 /// collection type you request. The iterator itself carries no knowledge of
1981 /// the eventual container; the target collection is chosen entirely by the
1982 /// type you ask `collect()` to return. This makes `collect()` one of the
1983 /// more powerful methods in the standard library, and it shows up in a wide
1984 /// variety of contexts.
1985 ///
1986 /// The most basic pattern in which `collect()` is used is to turn one
1987 /// collection into another. You take a collection, call [`iter`] on it,
1988 /// do a bunch of transformations, and then `collect()` at the end.
1989 ///
1990 /// `collect()` can also create instances of types that are not typical
1991 /// collections. For example, a [`String`] can be built from [`char`]s,
1992 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1993 /// into `Result<Collection<T>, E>`. See the examples below for more.
1994 ///
1995 /// Because `collect()` is so general, it can cause problems with type
1996 /// inference. As such, `collect()` is one of the few times you'll see
1997 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1998 /// helps the inference algorithm understand specifically which collection
1999 /// you're trying to collect into.
2000 ///
2001 /// # Examples
2002 ///
2003 /// Basic usage:
2004 ///
2005 /// ```
2006 /// let a = [1, 2, 3];
2007 ///
2008 /// let doubled: Vec<i32> = a.iter()
2009 /// .map(|x| x * 2)
2010 /// .collect();
2011 ///
2012 /// assert_eq!(vec![2, 4, 6], doubled);
2013 /// ```
2014 ///
2015 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
2016 /// we could collect into, for example, a [`VecDeque<T>`] instead:
2017 ///
2018 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
2019 ///
2020 /// ```
2021 /// use std::collections::VecDeque;
2022 ///
2023 /// let a = [1, 2, 3];
2024 ///
2025 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
2026 ///
2027 /// assert_eq!(2, doubled[0]);
2028 /// assert_eq!(4, doubled[1]);
2029 /// assert_eq!(6, doubled[2]);
2030 /// ```
2031 ///
2032 /// Using the 'turbofish' instead of annotating `doubled`:
2033 ///
2034 /// ```
2035 /// let a = [1, 2, 3];
2036 ///
2037 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
2038 ///
2039 /// assert_eq!(vec![2, 4, 6], doubled);
2040 /// ```
2041 ///
2042 /// Because `collect()` only cares about what you're collecting into, you can
2043 /// still use a partial type hint, `_`, with the turbofish:
2044 ///
2045 /// ```
2046 /// let a = [1, 2, 3];
2047 ///
2048 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2049 ///
2050 /// assert_eq!(vec![2, 4, 6], doubled);
2051 /// ```
2052 ///
2053 /// Using `collect()` to make a [`String`]:
2054 ///
2055 /// ```
2056 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2057 ///
2058 /// let hello: String = chars.into_iter()
2059 /// .map(|x| x as u8)
2060 /// .map(|x| (x + 1) as char)
2061 /// .collect();
2062 ///
2063 /// assert_eq!("hello", hello);
2064 /// ```
2065 ///
2066 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2067 /// see if any of them failed:
2068 ///
2069 /// ```
2070 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2071 ///
2072 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2073 ///
2074 /// // gives us the first error
2075 /// assert_eq!(Err("nope"), result);
2076 ///
2077 /// let results = [Ok(1), Ok(3)];
2078 ///
2079 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2080 ///
2081 /// // gives us the list of answers
2082 /// assert_eq!(Ok(vec![1, 3]), result);
2083 /// ```
2084 ///
2085 /// [`iter`]: Iterator::next
2086 /// [`String`]: ../../std/string/struct.String.html
2087 /// [`char`]: type@char
2088 #[inline]
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2091 #[rustc_diagnostic_item = "iterator_collect_fn"]
2092 #[rustc_non_const_trait_method]
2093 fn collect<B: FromIterator<Self::Item>>(self) -> B
2094 where
2095 Self: Sized,
2096 {
2097 // This is too aggressive to turn on for everything all the time, but PR#137908
2098 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2099 // so this will help catch such things in debug-assertions-std runners,
2100 // even if users won't actually ever see it.
2101 #[ferrocene::annotation("We ship `core` with debug assertions enabled")]
2102 if cfg!(debug_assertions) {
2103 let hint = self.size_hint();
2104 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2105 }
2106
2107 FromIterator::from_iter(self)
2108 }
2109
2110 /// Fallibly transforms an iterator into a collection, short circuiting if
2111 /// a failure is encountered.
2112 ///
2113 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2114 /// conversions during collection. Its main use case is simplifying conversions from
2115 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2116 /// types (e.g. [`Result`]).
2117 ///
2118 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2119 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2120 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2121 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2122 ///
2123 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2124 /// may continue to be used, in which case it will continue iterating starting after the element that
2125 /// triggered the failure. See the last example below for an example of how this works.
2126 ///
2127 /// # Examples
2128 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2129 /// ```
2130 /// #![feature(iterator_try_collect)]
2131 ///
2132 /// let u = vec![Some(1), Some(2), Some(3)];
2133 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2134 /// assert_eq!(v, Some(vec![1, 2, 3]));
2135 /// ```
2136 ///
2137 /// Failing to collect in the same way:
2138 /// ```
2139 /// #![feature(iterator_try_collect)]
2140 ///
2141 /// let u = vec![Some(1), Some(2), None, Some(3)];
2142 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2143 /// assert_eq!(v, None);
2144 /// ```
2145 ///
2146 /// A similar example, but with `Result`:
2147 /// ```
2148 /// #![feature(iterator_try_collect)]
2149 ///
2150 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2151 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2152 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2153 ///
2154 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2155 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2156 /// assert_eq!(v, Err(()));
2157 /// ```
2158 ///
2159 /// Finally, even [`ControlFlow`] works, despite the fact that it
2160 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2161 /// continue to be used, even if a failure is encountered:
2162 ///
2163 /// ```
2164 /// #![feature(iterator_try_collect)]
2165 ///
2166 /// use core::ops::ControlFlow::{Break, Continue};
2167 ///
2168 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2169 /// let mut it = u.into_iter();
2170 ///
2171 /// let v = it.try_collect::<Vec<_>>();
2172 /// assert_eq!(v, Break(3));
2173 ///
2174 /// let v = it.try_collect::<Vec<_>>();
2175 /// assert_eq!(v, Continue(vec![4, 5]));
2176 /// ```
2177 ///
2178 /// [`collect`]: Iterator::collect
2179 #[inline]
2180 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2181 #[cfg(not(feature = "ferrocene_subset"))]
2182 #[rustc_non_const_trait_method]
2183 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2184 where
2185 Self: Sized,
2186 Self::Item: Try<Residual: Residual<B>>,
2187 B: FromIterator<<Self::Item as Try>::Output>,
2188 {
2189 try_process(ByRefSized(self), |i| i.collect())
2190 }
2191
2192 /// Collects all the items from an iterator into a collection.
2193 ///
2194 /// This method consumes the iterator and adds all its items to the
2195 /// passed collection. The collection is then returned, so the call chain
2196 /// can be continued.
2197 ///
2198 /// This is useful when you already have a collection and want to add
2199 /// the iterator items to it.
2200 ///
2201 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2202 /// but instead of being called on a collection, it's called on an iterator.
2203 ///
2204 /// # Examples
2205 ///
2206 /// Basic usage:
2207 ///
2208 /// ```
2209 /// #![feature(iter_collect_into)]
2210 ///
2211 /// let a = [1, 2, 3];
2212 /// let mut vec: Vec::<i32> = vec![0, 1];
2213 ///
2214 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2215 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2216 ///
2217 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2218 /// ```
2219 ///
2220 /// `Vec` can have a manual set capacity to avoid reallocating it:
2221 ///
2222 /// ```
2223 /// #![feature(iter_collect_into)]
2224 ///
2225 /// let a = [1, 2, 3];
2226 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2227 ///
2228 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2229 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2230 ///
2231 /// assert_eq!(6, vec.capacity());
2232 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2233 /// ```
2234 ///
2235 /// The returned mutable reference can be used to continue the call chain:
2236 ///
2237 /// ```
2238 /// #![feature(iter_collect_into)]
2239 ///
2240 /// let a = [1, 2, 3];
2241 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2242 ///
2243 /// let count = a.iter().collect_into(&mut vec).iter().count();
2244 ///
2245 /// assert_eq!(count, vec.len());
2246 /// assert_eq!(vec, vec![1, 2, 3]);
2247 ///
2248 /// let count = a.iter().collect_into(&mut vec).iter().count();
2249 ///
2250 /// assert_eq!(count, vec.len());
2251 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2252 /// ```
2253 #[inline]
2254 #[unstable(feature = "iter_collect_into", issue = "94780")]
2255 #[cfg(not(feature = "ferrocene_subset"))]
2256 #[rustc_non_const_trait_method]
2257 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2258 where
2259 Self: Sized,
2260 {
2261 collection.extend(self);
2262 collection
2263 }
2264
2265 /// Consumes an iterator, creating two collections from it.
2266 ///
2267 /// The predicate passed to `partition()` can return `true`, or `false`.
2268 /// `partition()` returns a pair, all of the elements for which it returned
2269 /// `true`, and all of the elements for which it returned `false`.
2270 ///
2271 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2272 ///
2273 /// [`is_partitioned()`]: Iterator::is_partitioned
2274 /// [`partition_in_place()`]: Iterator::partition_in_place
2275 ///
2276 /// # Examples
2277 ///
2278 /// ```
2279 /// let a = [1, 2, 3];
2280 ///
2281 /// let (even, odd): (Vec<_>, Vec<_>) = a
2282 /// .into_iter()
2283 /// .partition(|n| n % 2 == 0);
2284 ///
2285 /// assert_eq!(even, [2]);
2286 /// assert_eq!(odd, [1, 3]);
2287 /// ```
2288 #[stable(feature = "rust1", since = "1.0.0")]
2289 #[cfg(not(feature = "ferrocene_subset"))]
2290 #[rustc_non_const_trait_method]
2291 fn partition<B, F>(self, f: F) -> (B, B)
2292 where
2293 Self: Sized,
2294 B: Default + Extend<Self::Item>,
2295 F: FnMut(&Self::Item) -> bool,
2296 {
2297 #[inline]
2298 fn extend<'a, T, B: Extend<T>>(
2299 mut f: impl FnMut(&T) -> bool + 'a,
2300 left: &'a mut B,
2301 right: &'a mut B,
2302 ) -> impl FnMut((), T) + 'a {
2303 move |(), x| {
2304 if f(&x) {
2305 left.extend_one(x);
2306 } else {
2307 right.extend_one(x);
2308 }
2309 }
2310 }
2311
2312 let mut left: B = Default::default();
2313 let mut right: B = Default::default();
2314
2315 self.fold((), extend(f, &mut left, &mut right));
2316
2317 (left, right)
2318 }
2319
2320 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2321 /// such that all those that return `true` precede all those that return `false`.
2322 /// Returns the number of `true` elements found.
2323 ///
2324 /// The relative order of partitioned items is not maintained.
2325 ///
2326 /// # Current implementation
2327 ///
2328 /// The current algorithm tries to find the first element for which the predicate evaluates
2329 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2330 ///
2331 /// Time complexity: *O*(*n*)
2332 ///
2333 /// See also [`is_partitioned()`] and [`partition()`].
2334 ///
2335 /// [`is_partitioned()`]: Iterator::is_partitioned
2336 /// [`partition()`]: Iterator::partition
2337 ///
2338 /// # Examples
2339 ///
2340 /// ```
2341 /// #![feature(iter_partition_in_place)]
2342 ///
2343 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2344 ///
2345 /// // Partition in-place between evens and odds
2346 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2347 ///
2348 /// assert_eq!(i, 3);
2349 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2350 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2351 /// ```
2352 #[unstable(feature = "iter_partition_in_place", issue = "62543")]
2353 #[cfg(not(feature = "ferrocene_subset"))]
2354 #[rustc_non_const_trait_method]
2355 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2356 where
2357 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2358 P: FnMut(&T) -> bool,
2359 {
2360 // FIXME: should we worry about the count overflowing? The only way to have more than
2361 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2362
2363 // These closure "factory" functions exist to avoid genericity in `Self`.
2364
2365 #[inline]
2366 fn is_false<'a, T>(
2367 predicate: &'a mut impl FnMut(&T) -> bool,
2368 true_count: &'a mut usize,
2369 ) -> impl FnMut(&&mut T) -> bool + 'a {
2370 move |x| {
2371 let p = predicate(&**x);
2372 *true_count += p as usize;
2373 !p
2374 }
2375 }
2376
2377 #[inline]
2378 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2379 move |x| predicate(&**x)
2380 }
2381
2382 // Repeatedly find the first `false` and swap it with the last `true`.
2383 let mut true_count = 0;
2384 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2385 if let Some(tail) = self.rfind(is_true(predicate)) {
2386 crate::mem::swap(head, tail);
2387 true_count += 1;
2388 } else {
2389 break;
2390 }
2391 }
2392 true_count
2393 }
2394
2395 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2396 /// such that all those that return `true` precede all those that return `false`.
2397 ///
2398 /// See also [`partition()`] and [`partition_in_place()`].
2399 ///
2400 /// [`partition()`]: Iterator::partition
2401 /// [`partition_in_place()`]: Iterator::partition_in_place
2402 ///
2403 /// # Examples
2404 ///
2405 /// ```
2406 /// #![feature(iter_is_partitioned)]
2407 ///
2408 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2409 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2410 /// ```
2411 #[unstable(feature = "iter_is_partitioned", issue = "62544")]
2412 #[cfg(not(feature = "ferrocene_subset"))]
2413 #[rustc_non_const_trait_method]
2414 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2415 where
2416 Self: Sized,
2417 P: FnMut(Self::Item) -> bool,
2418 {
2419 // Either all items test `true`, or the first clause stops at `false`
2420 // and we check that there are no more `true` items after that.
2421 self.all(&mut predicate) || !self.any(predicate)
2422 }
2423
2424 /// An iterator method that applies a function as long as it returns
2425 /// successfully, producing a single, final value.
2426 ///
2427 /// `try_fold()` takes two arguments: an initial value, and a closure with
2428 /// two arguments: an 'accumulator', and an element. The closure either
2429 /// returns successfully, with the value that the accumulator should have
2430 /// for the next iteration, or it returns failure, with an error value that
2431 /// is propagated back to the caller immediately (short-circuiting).
2432 ///
2433 /// The initial value is the value the accumulator will have on the first
2434 /// call. If applying the closure succeeded against every element of the
2435 /// iterator, `try_fold()` returns the final accumulator as success.
2436 ///
2437 /// Folding is useful whenever you have a collection of something, and want
2438 /// to produce a single value from it.
2439 ///
2440 /// # Note to Implementors
2441 ///
2442 /// Several of the other (forward) methods have default implementations in
2443 /// terms of this one, so try to implement this explicitly if it can
2444 /// do something better than the default `for` loop implementation.
2445 ///
2446 /// In particular, try to have this call `try_fold()` on the internal parts
2447 /// from which this iterator is composed. If multiple calls are needed,
2448 /// the `?` operator may be convenient for chaining the accumulator value
2449 /// along, but beware any invariants that need to be upheld before those
2450 /// early returns. This is a `&mut self` method, so iteration needs to be
2451 /// resumable after hitting an error here.
2452 ///
2453 /// # Examples
2454 ///
2455 /// Basic usage:
2456 ///
2457 /// ```
2458 /// let a = [1, 2, 3];
2459 ///
2460 /// // the checked sum of all of the elements of the array
2461 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2462 ///
2463 /// assert_eq!(sum, Some(6));
2464 /// ```
2465 ///
2466 /// Short-circuiting:
2467 ///
2468 /// ```
2469 /// let a = [10, 20, 30, 100, 40, 50];
2470 /// let mut iter = a.into_iter();
2471 ///
2472 /// // This sum overflows when adding the 100 element
2473 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2474 /// assert_eq!(sum, None);
2475 ///
2476 /// // Because it short-circuited, the remaining elements are still
2477 /// // available through the iterator.
2478 /// assert_eq!(iter.len(), 2);
2479 /// assert_eq!(iter.next(), Some(40));
2480 /// ```
2481 ///
2482 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2483 /// a similar idea:
2484 ///
2485 /// ```
2486 /// use std::ops::ControlFlow;
2487 ///
2488 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2489 /// if let Some(next) = prev.checked_add(x) {
2490 /// ControlFlow::Continue(next)
2491 /// } else {
2492 /// ControlFlow::Break(prev)
2493 /// }
2494 /// });
2495 /// assert_eq!(triangular, ControlFlow::Break(120));
2496 ///
2497 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2498 /// if let Some(next) = prev.checked_add(x) {
2499 /// ControlFlow::Continue(next)
2500 /// } else {
2501 /// ControlFlow::Break(prev)
2502 /// }
2503 /// });
2504 /// assert_eq!(triangular, ControlFlow::Continue(435));
2505 /// ```
2506 #[inline]
2507 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2508 #[rustc_non_const_trait_method]
2509 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2510 where
2511 Self: Sized,
2512 F: FnMut(B, Self::Item) -> R,
2513 R: Try<Output = B>,
2514 {
2515 let mut accum = init;
2516 while let Some(x) = self.next() {
2517 accum = f(accum, x)?;
2518 }
2519 try { accum }
2520 }
2521
2522 /// An iterator method that applies a fallible function to each item in the
2523 /// iterator, stopping at the first error and returning that error.
2524 ///
2525 /// This can also be thought of as the fallible form of [`for_each()`]
2526 /// or as the stateless version of [`try_fold()`].
2527 ///
2528 /// [`for_each()`]: Iterator::for_each
2529 /// [`try_fold()`]: Iterator::try_fold
2530 ///
2531 /// # Examples
2532 ///
2533 /// ```
2534 /// use std::fs::rename;
2535 /// use std::io::{stdout, Write};
2536 /// use std::path::Path;
2537 ///
2538 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2539 ///
2540 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2541 /// assert!(res.is_ok());
2542 ///
2543 /// let mut it = data.iter().cloned();
2544 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2545 /// assert!(res.is_err());
2546 /// // It short-circuited, so the remaining items are still in the iterator:
2547 /// assert_eq!(it.next(), Some("stale_bread.json"));
2548 /// ```
2549 ///
2550 /// The [`ControlFlow`] type can be used with this method for the situations
2551 /// in which you'd use `break` and `continue` in a normal loop:
2552 ///
2553 /// ```
2554 /// use std::ops::ControlFlow;
2555 ///
2556 /// let r = (2..100).try_for_each(|x| {
2557 /// if 323 % x == 0 {
2558 /// return ControlFlow::Break(x)
2559 /// }
2560 ///
2561 /// ControlFlow::Continue(())
2562 /// });
2563 /// assert_eq!(r, ControlFlow::Break(17));
2564 /// ```
2565 #[inline]
2566 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2567 #[rustc_non_const_trait_method]
2568 fn try_for_each<F, R>(&mut self, f: F) -> R
2569 where
2570 Self: Sized,
2571 F: FnMut(Self::Item) -> R,
2572 R: Try<Output = ()>,
2573 {
2574 #[inline]
2575 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2576 move |(), x| f(x)
2577 }
2578
2579 self.try_fold((), call(f))
2580 }
2581
2582 /// Folds every element into an accumulator by applying an operation,
2583 /// returning the final result.
2584 ///
2585 /// `fold()` takes two arguments: an initial value, and a closure with two
2586 /// arguments: an 'accumulator', and an element. The closure returns the value that
2587 /// the accumulator should have for the next iteration.
2588 ///
2589 /// The initial value is the value the accumulator will have on the first
2590 /// call.
2591 ///
2592 /// After applying this closure to every element of the iterator, `fold()`
2593 /// returns the accumulator.
2594 ///
2595 /// This operation is sometimes called 'reduce' or 'inject'.
2596 ///
2597 /// Folding is useful whenever you have a collection of something, and want
2598 /// to produce a single value from it.
2599 ///
2600 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2601 /// might not terminate for infinite iterators, even on traits for which a
2602 /// result is determinable in finite time.
2603 ///
2604 /// Note: [`reduce()`] can be used to use the first element as the initial
2605 /// value, if the accumulator type and item type is the same.
2606 ///
2607 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2608 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2609 /// operators like `-` the order will affect the final result.
2610 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2611 ///
2612 /// # Note to Implementors
2613 ///
2614 /// Several of the other (forward) methods have default implementations in
2615 /// terms of this one, so try to implement this explicitly if it can
2616 /// do something better than the default `for` loop implementation.
2617 ///
2618 /// In particular, try to have this call `fold()` on the internal parts
2619 /// from which this iterator is composed.
2620 ///
2621 /// # Examples
2622 ///
2623 /// Basic usage:
2624 ///
2625 /// ```
2626 /// let a = [1, 2, 3];
2627 ///
2628 /// // the sum of all of the elements of the array
2629 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2630 ///
2631 /// assert_eq!(sum, 6);
2632 /// ```
2633 ///
2634 /// Let's walk through each step of the iteration here:
2635 ///
2636 /// | element | acc | x | result |
2637 /// |---------|-----|---|--------|
2638 /// | | 0 | | |
2639 /// | 1 | 0 | 1 | 1 |
2640 /// | 2 | 1 | 2 | 3 |
2641 /// | 3 | 3 | 3 | 6 |
2642 ///
2643 /// And so, our final result, `6`.
2644 ///
2645 /// This example demonstrates the left-associative nature of `fold()`:
2646 /// it builds a string, starting with an initial value
2647 /// and continuing with each element from the front until the back:
2648 ///
2649 /// ```
2650 /// let numbers = [1, 2, 3, 4, 5];
2651 ///
2652 /// let zero = "0".to_string();
2653 ///
2654 /// let result = numbers.iter().fold(zero, |acc, &x| {
2655 /// format!("({acc} + {x})")
2656 /// });
2657 ///
2658 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2659 /// ```
2660 /// It's common for people who haven't used iterators a lot to
2661 /// use a `for` loop with a list of things to build up a result. Those
2662 /// can be turned into `fold()`s:
2663 ///
2664 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2665 ///
2666 /// ```
2667 /// let numbers = [1, 2, 3, 4, 5];
2668 ///
2669 /// let mut result = 0;
2670 ///
2671 /// // for loop:
2672 /// for i in &numbers {
2673 /// result = result + i;
2674 /// }
2675 ///
2676 /// // fold:
2677 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2678 ///
2679 /// // they're the same
2680 /// assert_eq!(result, result2);
2681 /// ```
2682 ///
2683 /// [`reduce()`]: Iterator::reduce
2684 #[doc(alias = "inject", alias = "foldl")]
2685 #[inline]
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 #[rustc_non_const_trait_method]
2688 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2689 where
2690 Self: Sized,
2691 F: FnMut(B, Self::Item) -> B,
2692 {
2693 let mut accum = init;
2694 while let Some(x) = self.next() {
2695 accum = f(accum, x);
2696 }
2697 accum
2698 }
2699
2700 /// Reduces the elements to a single one, by repeatedly applying a reducing
2701 /// operation.
2702 ///
2703 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2704 /// result of the reduction.
2705 ///
2706 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2707 /// For iterators with at least one element, this is the same as [`fold()`]
2708 /// with the first element of the iterator as the initial accumulator value, folding
2709 /// every subsequent element into it.
2710 ///
2711 /// [`fold()`]: Iterator::fold
2712 ///
2713 /// # Example
2714 ///
2715 /// ```
2716 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2717 /// assert_eq!(reduced, 45);
2718 ///
2719 /// // Which is equivalent to doing it with `fold`:
2720 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2721 /// assert_eq!(reduced, folded);
2722 /// ```
2723 #[inline]
2724 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2725 #[rustc_non_const_trait_method]
2726 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2727 where
2728 Self: Sized,
2729 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2730 {
2731 let first = self.next()?;
2732 Some(self.fold(first, f))
2733 }
2734
2735 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2736 /// closure returns a failure, the failure is propagated back to the caller immediately.
2737 ///
2738 /// The return type of this method depends on the return type of the closure. If the closure
2739 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2740 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2741 /// `Option<Option<Self::Item>>`.
2742 ///
2743 /// When called on an empty iterator, this function will return either `Some(None)` or
2744 /// `Ok(None)` depending on the type of the provided closure.
2745 ///
2746 /// For iterators with at least one element, this is essentially the same as calling
2747 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2748 ///
2749 /// [`try_fold()`]: Iterator::try_fold
2750 ///
2751 /// # Examples
2752 ///
2753 /// Safely calculate the sum of a series of numbers:
2754 ///
2755 /// ```
2756 /// #![feature(iterator_try_reduce)]
2757 ///
2758 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2759 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2760 /// assert_eq!(sum, Some(Some(58)));
2761 /// ```
2762 ///
2763 /// Determine when a reduction short circuited:
2764 ///
2765 /// ```
2766 /// #![feature(iterator_try_reduce)]
2767 ///
2768 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2769 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2770 /// assert_eq!(sum, None);
2771 /// ```
2772 ///
2773 /// Determine when a reduction was not performed because there are no elements:
2774 ///
2775 /// ```
2776 /// #![feature(iterator_try_reduce)]
2777 ///
2778 /// let numbers: Vec<usize> = Vec::new();
2779 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2780 /// assert_eq!(sum, Some(None));
2781 /// ```
2782 ///
2783 /// Use a [`Result`] instead of an [`Option`]:
2784 ///
2785 /// ```
2786 /// #![feature(iterator_try_reduce)]
2787 ///
2788 /// let numbers = vec!["1", "2", "3", "4", "5"];
2789 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2790 /// numbers.into_iter().try_reduce(|x, y| {
2791 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2792 /// });
2793 /// assert_eq!(max, Ok(Some("5")));
2794 /// ```
2795 #[inline]
2796 #[unstable(feature = "iterator_try_reduce", issue = "87053")]
2797 #[cfg(not(feature = "ferrocene_subset"))]
2798 #[rustc_non_const_trait_method]
2799 fn try_reduce<R>(
2800 &mut self,
2801 f: impl FnMut(Self::Item, Self::Item) -> R,
2802 ) -> ChangeOutputType<R, Option<R::Output>>
2803 where
2804 Self: Sized,
2805 R: Try<Output = Self::Item, Residual: Residual<Option<Self::Item>>>,
2806 {
2807 let first = match self.next() {
2808 Some(i) => i,
2809 None => return Try::from_output(None),
2810 };
2811
2812 match self.try_fold(first, f).branch() {
2813 ControlFlow::Break(r) => FromResidual::from_residual(r),
2814 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2815 }
2816 }
2817
2818 /// Tests if every element of the iterator matches a predicate.
2819 ///
2820 /// `all()` takes a closure that returns `true` or `false`. It applies
2821 /// this closure to each element of the iterator, and if they all return
2822 /// `true`, then so does `all()`. If any of them return `false`, it
2823 /// returns `false`.
2824 ///
2825 /// `all()` is short-circuiting; in other words, it will stop processing
2826 /// as soon as it finds a `false`, given that no matter what else happens,
2827 /// the result will also be `false`.
2828 ///
2829 /// An empty iterator returns `true`.
2830 ///
2831 /// # Examples
2832 ///
2833 /// Basic usage:
2834 ///
2835 /// ```
2836 /// let a = [1, 2, 3];
2837 ///
2838 /// assert!(a.into_iter().all(|x| x > 0));
2839 ///
2840 /// assert!(!a.into_iter().all(|x| x > 2));
2841 /// ```
2842 ///
2843 /// Stopping at the first `false`:
2844 ///
2845 /// ```
2846 /// let a = [1, 2, 3];
2847 ///
2848 /// let mut iter = a.into_iter();
2849 ///
2850 /// assert!(!iter.all(|x| x != 2));
2851 ///
2852 /// // we can still use `iter`, as there are more elements.
2853 /// assert_eq!(iter.next(), Some(3));
2854 /// ```
2855 #[inline]
2856 #[stable(feature = "rust1", since = "1.0.0")]
2857 #[rustc_non_const_trait_method]
2858 fn all<F>(&mut self, f: F) -> bool
2859 where
2860 Self: Sized,
2861 F: FnMut(Self::Item) -> bool,
2862 {
2863 #[inline]
2864 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2865 move |(), x| {
2866 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2867 }
2868 }
2869 self.try_fold((), check(f)) == ControlFlow::Continue(())
2870 }
2871
2872 /// Tests if any element of the iterator matches a predicate.
2873 ///
2874 /// `any()` takes a closure that returns `true` or `false`. It applies
2875 /// this closure to each element of the iterator, and if any of them return
2876 /// `true`, then so does `any()`. If they all return `false`, it
2877 /// returns `false`.
2878 ///
2879 /// `any()` is short-circuiting; in other words, it will stop processing
2880 /// as soon as it finds a `true`, given that no matter what else happens,
2881 /// the result will also be `true`.
2882 ///
2883 /// An empty iterator returns `false`.
2884 ///
2885 /// # Examples
2886 ///
2887 /// Basic usage:
2888 ///
2889 /// ```
2890 /// let a = [1, 2, 3];
2891 ///
2892 /// assert!(a.into_iter().any(|x| x > 0));
2893 ///
2894 /// assert!(!a.into_iter().any(|x| x > 5));
2895 /// ```
2896 ///
2897 /// Stopping at the first `true`:
2898 ///
2899 /// ```
2900 /// let a = [1, 2, 3];
2901 ///
2902 /// let mut iter = a.into_iter();
2903 ///
2904 /// assert!(iter.any(|x| x != 2));
2905 ///
2906 /// // we can still use `iter`, as there are more elements.
2907 /// assert_eq!(iter.next(), Some(2));
2908 /// ```
2909 #[inline]
2910 #[stable(feature = "rust1", since = "1.0.0")]
2911 #[rustc_non_const_trait_method]
2912 fn any<F>(&mut self, f: F) -> bool
2913 where
2914 Self: Sized,
2915 F: FnMut(Self::Item) -> bool,
2916 {
2917 #[inline]
2918 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2919 move |(), x| {
2920 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2921 }
2922 }
2923
2924 self.try_fold((), check(f)) == ControlFlow::Break(())
2925 }
2926
2927 /// Searches for an element of an iterator that satisfies a predicate.
2928 ///
2929 /// `find()` takes a closure that returns `true` or `false`. It applies
2930 /// this closure to each element of the iterator, and if any of them return
2931 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2932 /// `false`, it returns [`None`].
2933 ///
2934 /// `find()` is short-circuiting; in other words, it will stop processing
2935 /// as soon as the closure returns `true`.
2936 ///
2937 /// Because `find()` takes a reference, and many iterators iterate over
2938 /// references, this leads to a possibly confusing situation where the
2939 /// argument is a double reference. You can see this effect in the
2940 /// examples below, with `&&x`.
2941 ///
2942 /// If you need the index of the element, see [`position()`].
2943 ///
2944 /// [`Some(element)`]: Some
2945 /// [`position()`]: Iterator::position
2946 ///
2947 /// # Examples
2948 ///
2949 /// Basic usage:
2950 ///
2951 /// ```
2952 /// let a = [1, 2, 3];
2953 ///
2954 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2955 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2956 /// ```
2957 ///
2958 /// Iterating over references:
2959 ///
2960 /// ```
2961 /// let a = [1, 2, 3];
2962 ///
2963 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2964 /// // reference to each element.
2965 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2966 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2967 /// ```
2968 ///
2969 /// Stopping at the first `true`:
2970 ///
2971 /// ```
2972 /// let a = [1, 2, 3];
2973 ///
2974 /// let mut iter = a.into_iter();
2975 ///
2976 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2977 ///
2978 /// // we can still use `iter`, as there are more elements.
2979 /// assert_eq!(iter.next(), Some(3));
2980 /// ```
2981 ///
2982 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2983 #[inline]
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 #[rustc_non_const_trait_method]
2986 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2987 where
2988 Self: Sized,
2989 P: FnMut(&Self::Item) -> bool,
2990 {
2991 #[inline]
2992 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2993 move |(), x| {
2994 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2995 }
2996 }
2997
2998 self.try_fold((), check(predicate)).break_value()
2999 }
3000
3001 /// Applies function to the elements of iterator and returns
3002 /// the first non-none result.
3003 ///
3004 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
3005 ///
3006 /// # Examples
3007 ///
3008 /// ```
3009 /// let a = ["lol", "NaN", "2", "5"];
3010 ///
3011 /// let first_number = a.iter().find_map(|s| s.parse().ok());
3012 ///
3013 /// assert_eq!(first_number, Some(2));
3014 /// ```
3015 #[inline]
3016 #[stable(feature = "iterator_find_map", since = "1.30.0")]
3017 #[cfg(not(feature = "ferrocene_subset"))]
3018 #[rustc_non_const_trait_method]
3019 fn find_map<B, F>(&mut self, f: F) -> Option<B>
3020 where
3021 Self: Sized,
3022 F: FnMut(Self::Item) -> Option<B>,
3023 {
3024 #[inline]
3025 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
3026 move |(), x| match f(x) {
3027 Some(x) => ControlFlow::Break(x),
3028 None => ControlFlow::Continue(()),
3029 }
3030 }
3031
3032 self.try_fold((), check(f)).break_value()
3033 }
3034
3035 /// Applies function to the elements of iterator and returns
3036 /// the first true result or the first error.
3037 ///
3038 /// The return type of this method depends on the return type of the closure.
3039 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
3040 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
3041 ///
3042 /// # Examples
3043 ///
3044 /// ```
3045 /// #![feature(try_find)]
3046 ///
3047 /// let a = ["1", "2", "lol", "NaN", "5"];
3048 ///
3049 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
3050 /// Ok(s.parse::<i32>()? == search)
3051 /// };
3052 ///
3053 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
3054 /// assert_eq!(result, Ok(Some("2")));
3055 ///
3056 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
3057 /// assert!(result.is_err());
3058 /// ```
3059 ///
3060 /// This also supports other types which implement [`Try`], not just [`Result`].
3061 ///
3062 /// ```
3063 /// #![feature(try_find)]
3064 ///
3065 /// use std::num::NonZero;
3066 ///
3067 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
3068 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3069 /// assert_eq!(result, Some(Some(4)));
3070 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3071 /// assert_eq!(result, Some(None));
3072 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3073 /// assert_eq!(result, None);
3074 /// ```
3075 #[inline]
3076 #[unstable(feature = "try_find", issue = "63178")]
3077 #[cfg(not(feature = "ferrocene_subset"))]
3078 #[rustc_non_const_trait_method]
3079 fn try_find<R>(
3080 &mut self,
3081 f: impl FnMut(&Self::Item) -> R,
3082 ) -> ChangeOutputType<R, Option<Self::Item>>
3083 where
3084 Self: Sized,
3085 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3086 {
3087 #[inline]
3088 fn check<I, V, R>(
3089 mut f: impl FnMut(&I) -> V,
3090 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3091 where
3092 V: Try<Output = bool, Residual = R>,
3093 R: Residual<Option<I>>,
3094 {
3095 move |(), x| match f(&x).branch() {
3096 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3097 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3098 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3099 }
3100 }
3101
3102 match self.try_fold((), check(f)) {
3103 ControlFlow::Break(x) => x,
3104 ControlFlow::Continue(()) => Try::from_output(None),
3105 }
3106 }
3107
3108 /// Searches for an element in an iterator, returning its index.
3109 ///
3110 /// `position()` takes a closure that returns `true` or `false`. It applies
3111 /// this closure to each element of the iterator, and if one of them
3112 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3113 /// them return `false`, it returns [`None`].
3114 ///
3115 /// `position()` is short-circuiting; in other words, it will stop
3116 /// processing as soon as it finds a `true`.
3117 ///
3118 /// # Overflow Behavior
3119 ///
3120 /// The method does no guarding against overflows, so if there are more
3121 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3122 /// result or panics. If overflow checks are enabled, a panic is
3123 /// guaranteed.
3124 ///
3125 /// # Panics
3126 ///
3127 /// This function might panic if the iterator has more than `usize::MAX`
3128 /// non-matching elements.
3129 ///
3130 /// [`Some(index)`]: Some
3131 ///
3132 /// # Examples
3133 ///
3134 /// Basic usage:
3135 ///
3136 /// ```
3137 /// let a = [1, 2, 3];
3138 ///
3139 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3140 ///
3141 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3142 /// ```
3143 ///
3144 /// Stopping at the first `true`:
3145 ///
3146 /// ```
3147 /// let a = [1, 2, 3, 4];
3148 ///
3149 /// let mut iter = a.into_iter();
3150 ///
3151 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3152 ///
3153 /// // we can still use `iter`, as there are more elements.
3154 /// assert_eq!(iter.next(), Some(3));
3155 ///
3156 /// // The returned index depends on iterator state
3157 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3158 ///
3159 /// ```
3160 #[inline]
3161 #[stable(feature = "rust1", since = "1.0.0")]
3162 #[rustc_non_const_trait_method]
3163 fn position<P>(&mut self, predicate: P) -> Option<usize>
3164 where
3165 Self: Sized,
3166 P: FnMut(Self::Item) -> bool,
3167 {
3168 #[inline]
3169 fn check<'a, T>(
3170 mut predicate: impl FnMut(T) -> bool + 'a,
3171 acc: &'a mut usize,
3172 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3173 #[rustc_inherit_overflow_checks]
3174 move |_, x| {
3175 if predicate(x) {
3176 ControlFlow::Break(*acc)
3177 } else {
3178 *acc += 1;
3179 ControlFlow::Continue(())
3180 }
3181 }
3182 }
3183
3184 let mut acc = 0;
3185 self.try_fold((), check(predicate, &mut acc)).break_value()
3186 }
3187
3188 /// Searches for an element in an iterator from the right, returning its
3189 /// index.
3190 ///
3191 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3192 /// this closure to each element of the iterator, starting from the end,
3193 /// and if one of them returns `true`, then `rposition()` returns
3194 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3195 ///
3196 /// `rposition()` is short-circuiting; in other words, it will stop
3197 /// processing as soon as it finds a `true`.
3198 ///
3199 /// [`Some(index)`]: Some
3200 ///
3201 /// # Examples
3202 ///
3203 /// Basic usage:
3204 ///
3205 /// ```
3206 /// let a = [1, 2, 3];
3207 ///
3208 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3209 ///
3210 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3211 /// ```
3212 ///
3213 /// Stopping at the first `true`:
3214 ///
3215 /// ```
3216 /// let a = [-1, 2, 3, 4];
3217 ///
3218 /// let mut iter = a.into_iter();
3219 ///
3220 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3221 ///
3222 /// // we can still use `iter`, as there are more elements.
3223 /// assert_eq!(iter.next(), Some(-1));
3224 /// assert_eq!(iter.next_back(), Some(3));
3225 /// ```
3226 #[inline]
3227 #[stable(feature = "rust1", since = "1.0.0")]
3228 #[rustc_non_const_trait_method]
3229 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3230 where
3231 P: FnMut(Self::Item) -> bool,
3232 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3233 {
3234 // No need for an overflow check here, because `ExactSizeIterator`
3235 // implies that the number of elements fits into a `usize`.
3236 #[inline]
3237 fn check<T>(
3238 mut predicate: impl FnMut(T) -> bool,
3239 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3240 move |i, x| {
3241 let i = i - 1;
3242 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3243 }
3244 }
3245
3246 let n = self.len();
3247 self.try_rfold(n, check(predicate)).break_value()
3248 }
3249
3250 /// Returns the maximum element of an iterator.
3251 ///
3252 /// If several elements are equally maximum, the last element is
3253 /// returned. If the iterator is empty, [`None`] is returned.
3254 ///
3255 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3256 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3257 /// ```
3258 /// assert_eq!(
3259 /// [2.4, f32::NAN, 1.3]
3260 /// .into_iter()
3261 /// .reduce(f32::max)
3262 /// .unwrap_or(0.),
3263 /// 2.4
3264 /// );
3265 /// ```
3266 ///
3267 /// # Examples
3268 ///
3269 /// ```
3270 /// let a = [1, 2, 3];
3271 /// let b: [u32; 0] = [];
3272 ///
3273 /// assert_eq!(a.into_iter().max(), Some(3));
3274 /// assert_eq!(b.into_iter().max(), None);
3275 /// ```
3276 #[inline]
3277 #[stable(feature = "rust1", since = "1.0.0")]
3278 #[cfg(not(feature = "ferrocene_subset"))]
3279 #[rustc_non_const_trait_method]
3280 fn max(self) -> Option<Self::Item>
3281 where
3282 Self: Sized,
3283 Self::Item: Ord,
3284 {
3285 self.max_by(Ord::cmp)
3286 }
3287
3288 /// Returns the minimum element of an iterator.
3289 ///
3290 /// If several elements are equally minimum, the first element is returned.
3291 /// If the iterator is empty, [`None`] is returned.
3292 ///
3293 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3294 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3295 /// ```
3296 /// assert_eq!(
3297 /// [2.4, f32::NAN, 1.3]
3298 /// .into_iter()
3299 /// .reduce(f32::min)
3300 /// .unwrap_or(0.),
3301 /// 1.3
3302 /// );
3303 /// ```
3304 ///
3305 /// # Examples
3306 ///
3307 /// ```
3308 /// let a = [1, 2, 3];
3309 /// let b: [u32; 0] = [];
3310 ///
3311 /// assert_eq!(a.into_iter().min(), Some(1));
3312 /// assert_eq!(b.into_iter().min(), None);
3313 /// ```
3314 #[inline]
3315 #[stable(feature = "rust1", since = "1.0.0")]
3316 #[cfg(not(feature = "ferrocene_subset"))]
3317 #[rustc_non_const_trait_method]
3318 fn min(self) -> Option<Self::Item>
3319 where
3320 Self: Sized,
3321 Self::Item: Ord,
3322 {
3323 self.min_by(Ord::cmp)
3324 }
3325
3326 /// Returns the element that gives the maximum value from the
3327 /// specified function.
3328 ///
3329 /// If several elements are equally maximum, the last element is
3330 /// returned. If the iterator is empty, [`None`] is returned.
3331 ///
3332 /// # Examples
3333 ///
3334 /// ```
3335 /// let a = [-3_i32, 0, 1, 5, -10];
3336 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3337 /// ```
3338 #[inline]
3339 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3340 #[cfg(not(feature = "ferrocene_subset"))]
3341 #[rustc_non_const_trait_method]
3342 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3343 where
3344 Self: Sized,
3345 F: FnMut(&Self::Item) -> B,
3346 {
3347 #[inline]
3348 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3349 move |x| (f(&x), x)
3350 }
3351
3352 #[inline]
3353 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3354 x_p.cmp(y_p)
3355 }
3356
3357 let (_, x) = self.map(key(f)).max_by(compare)?;
3358 Some(x)
3359 }
3360
3361 /// Returns the element that gives the maximum value with respect to the
3362 /// specified comparison function.
3363 ///
3364 /// If several elements are equally maximum, the last element is
3365 /// returned. If the iterator is empty, [`None`] is returned.
3366 ///
3367 /// # Examples
3368 ///
3369 /// ```
3370 /// let a = [-3_i32, 0, 1, 5, -10];
3371 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3372 /// ```
3373 #[inline]
3374 #[stable(feature = "iter_max_by", since = "1.15.0")]
3375 #[rustc_non_const_trait_method]
3376 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3377 where
3378 Self: Sized,
3379 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3380 {
3381 #[inline]
3382 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3383 move |x, y| cmp::max_by(x, y, &mut compare)
3384 }
3385
3386 self.reduce(fold(compare))
3387 }
3388
3389 /// Returns the element that gives the minimum value from the
3390 /// specified function.
3391 ///
3392 /// If several elements are equally minimum, the first element is
3393 /// returned. If the iterator is empty, [`None`] is returned.
3394 ///
3395 /// # Examples
3396 ///
3397 /// ```
3398 /// let a = [-3_i32, 0, 1, 5, -10];
3399 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3400 /// ```
3401 #[inline]
3402 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3403 #[cfg(not(feature = "ferrocene_subset"))]
3404 #[rustc_non_const_trait_method]
3405 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3406 where
3407 Self: Sized,
3408 F: FnMut(&Self::Item) -> B,
3409 {
3410 #[inline]
3411 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3412 move |x| (f(&x), x)
3413 }
3414
3415 #[inline]
3416 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3417 x_p.cmp(y_p)
3418 }
3419
3420 let (_, x) = self.map(key(f)).min_by(compare)?;
3421 Some(x)
3422 }
3423
3424 /// Returns the element that gives the minimum value with respect to the
3425 /// specified comparison function.
3426 ///
3427 /// If several elements are equally minimum, the first element is
3428 /// returned. If the iterator is empty, [`None`] is returned.
3429 ///
3430 /// # Examples
3431 ///
3432 /// ```
3433 /// let a = [-3_i32, 0, 1, 5, -10];
3434 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3435 /// ```
3436 #[inline]
3437 #[stable(feature = "iter_min_by", since = "1.15.0")]
3438 #[cfg(not(feature = "ferrocene_subset"))]
3439 #[rustc_non_const_trait_method]
3440 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3441 where
3442 Self: Sized,
3443 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3444 {
3445 #[inline]
3446 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3447 move |x, y| cmp::min_by(x, y, &mut compare)
3448 }
3449
3450 self.reduce(fold(compare))
3451 }
3452
3453 /// Reverses an iterator's direction.
3454 ///
3455 /// Usually, iterators iterate from left to right. After using `rev()`,
3456 /// an iterator will instead iterate from right to left.
3457 ///
3458 /// This is only possible if the iterator has an end, so `rev()` only
3459 /// works on [`DoubleEndedIterator`]s.
3460 ///
3461 /// # Examples
3462 ///
3463 /// ```
3464 /// let a = [1, 2, 3];
3465 ///
3466 /// let mut iter = a.into_iter().rev();
3467 ///
3468 /// assert_eq!(iter.next(), Some(3));
3469 /// assert_eq!(iter.next(), Some(2));
3470 /// assert_eq!(iter.next(), Some(1));
3471 ///
3472 /// assert_eq!(iter.next(), None);
3473 /// ```
3474 #[inline]
3475 #[doc(alias = "reverse")]
3476 #[stable(feature = "rust1", since = "1.0.0")]
3477 #[rustc_non_const_trait_method]
3478 fn rev(self) -> Rev<Self>
3479 where
3480 Self: Sized + DoubleEndedIterator,
3481 {
3482 Rev::new(self)
3483 }
3484
3485 /// Converts an iterator of pairs into a pair of containers.
3486 ///
3487 /// `unzip()` consumes an entire iterator of pairs, producing two
3488 /// collections: one from the left elements of the pairs, and one
3489 /// from the right elements.
3490 ///
3491 /// This function is, in some sense, the opposite of [`zip`].
3492 ///
3493 /// [`zip`]: Iterator::zip
3494 ///
3495 /// # Examples
3496 ///
3497 /// ```
3498 /// let a = [(1, 2), (3, 4), (5, 6)];
3499 ///
3500 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3501 ///
3502 /// assert_eq!(left, [1, 3, 5]);
3503 /// assert_eq!(right, [2, 4, 6]);
3504 ///
3505 /// // you can also unzip multiple nested tuples at once
3506 /// let a = [(1, (2, 3)), (4, (5, 6))];
3507 ///
3508 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3509 /// assert_eq!(x, [1, 4]);
3510 /// assert_eq!(y, [2, 5]);
3511 /// assert_eq!(z, [3, 6]);
3512 /// ```
3513 #[stable(feature = "rust1", since = "1.0.0")]
3514 #[cfg(not(feature = "ferrocene_subset"))]
3515 #[rustc_non_const_trait_method]
3516 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3517 where
3518 FromA: Default + Extend<A>,
3519 FromB: Default + Extend<B>,
3520 Self: Sized + Iterator<Item = (A, B)>,
3521 {
3522 let mut unzipped: (FromA, FromB) = Default::default();
3523 unzipped.extend(self);
3524 unzipped
3525 }
3526
3527 /// Creates an iterator which copies all of its elements.
3528 ///
3529 /// This is useful when you have an iterator over `&T`, but you need an
3530 /// iterator over `T`.
3531 ///
3532 /// # Examples
3533 ///
3534 /// ```
3535 /// let a = [1, 2, 3];
3536 ///
3537 /// let v_copied: Vec<_> = a.iter().copied().collect();
3538 ///
3539 /// // copied is the same as .map(|&x| x)
3540 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3541 ///
3542 /// assert_eq!(v_copied, [1, 2, 3]);
3543 /// assert_eq!(v_map, [1, 2, 3]);
3544 /// ```
3545 #[stable(feature = "iter_copied", since = "1.36.0")]
3546 #[rustc_diagnostic_item = "iter_copied"]
3547 #[rustc_non_const_trait_method]
3548 fn copied<'a, T>(self) -> Copied<Self>
3549 where
3550 T: Copy + 'a,
3551 Self: Sized + Iterator<Item = &'a T>,
3552 {
3553 Copied::new(self)
3554 }
3555
3556 /// Creates an iterator which [`clone`]s all of its elements.
3557 ///
3558 /// This is useful when you have an iterator over `&T`, but you need an
3559 /// iterator over `T`.
3560 ///
3561 /// There is no guarantee whatsoever about the `clone` method actually
3562 /// being called *or* optimized away. So code should not depend on
3563 /// either.
3564 ///
3565 /// [`clone`]: Clone::clone
3566 ///
3567 /// # Examples
3568 ///
3569 /// Basic usage:
3570 ///
3571 /// ```
3572 /// let a = [1, 2, 3];
3573 ///
3574 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3575 ///
3576 /// // cloned is the same as .map(|&x| x), for integers
3577 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3578 ///
3579 /// assert_eq!(v_cloned, [1, 2, 3]);
3580 /// assert_eq!(v_map, [1, 2, 3]);
3581 /// ```
3582 ///
3583 /// To get the best performance, try to clone late:
3584 ///
3585 /// ```
3586 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3587 /// // don't do this:
3588 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3589 /// assert_eq!(&[vec![23]], &slower[..]);
3590 /// // instead call `cloned` late
3591 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3592 /// assert_eq!(&[vec![23]], &faster[..]);
3593 /// ```
3594 #[stable(feature = "rust1", since = "1.0.0")]
3595 #[rustc_diagnostic_item = "iter_cloned"]
3596 #[rustc_non_const_trait_method]
3597 fn cloned<'a, T>(self) -> Cloned<Self>
3598 where
3599 T: Clone + 'a,
3600 Self: Sized + Iterator<Item = &'a T>,
3601 {
3602 Cloned::new(self)
3603 }
3604
3605 /// Repeats an iterator endlessly.
3606 ///
3607 /// Instead of stopping at [`None`], the iterator will instead start again,
3608 /// from the beginning. After iterating again, it will start at the
3609 /// beginning again. And again. And again. Forever. Note that in case the
3610 /// original iterator is empty, the resulting iterator will also be empty.
3611 ///
3612 /// # Examples
3613 ///
3614 /// ```
3615 /// let a = [1, 2, 3];
3616 ///
3617 /// let mut iter = a.into_iter().cycle();
3618 ///
3619 /// loop {
3620 /// assert_eq!(iter.next(), Some(1));
3621 /// assert_eq!(iter.next(), Some(2));
3622 /// assert_eq!(iter.next(), Some(3));
3623 /// # break;
3624 /// }
3625 /// ```
3626 #[stable(feature = "rust1", since = "1.0.0")]
3627 #[inline]
3628 #[cfg(not(feature = "ferrocene_subset"))]
3629 #[rustc_non_const_trait_method]
3630 fn cycle(self) -> Cycle<Self>
3631 where
3632 Self: Sized + Clone,
3633 {
3634 Cycle::new(self)
3635 }
3636
3637 /// Returns an iterator over `N` elements of the iterator at a time.
3638 ///
3639 /// The chunks do not overlap. If `N` does not divide the length of the
3640 /// iterator, then the last up to `N-1` elements will be omitted and can be
3641 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3642 /// function of the iterator.
3643 ///
3644 /// # Panics
3645 ///
3646 /// Panics if `N` is zero.
3647 ///
3648 /// # Examples
3649 ///
3650 /// Basic usage:
3651 ///
3652 /// ```
3653 /// #![feature(iter_array_chunks)]
3654 ///
3655 /// let mut iter = "lorem".chars().array_chunks();
3656 /// assert_eq!(iter.next(), Some(['l', 'o']));
3657 /// assert_eq!(iter.next(), Some(['r', 'e']));
3658 /// assert_eq!(iter.next(), None);
3659 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3660 /// ```
3661 ///
3662 /// ```
3663 /// #![feature(iter_array_chunks)]
3664 ///
3665 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3666 /// // ^-----^ ^------^
3667 /// for [x, y, z] in data.iter().array_chunks() {
3668 /// assert_eq!(x + y + z, 4);
3669 /// }
3670 /// ```
3671 #[track_caller]
3672 #[unstable(feature = "iter_array_chunks", issue = "100450")]
3673 #[cfg(not(feature = "ferrocene_subset"))]
3674 #[rustc_non_const_trait_method]
3675 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3676 where
3677 Self: Sized,
3678 {
3679 ArrayChunks::new(self)
3680 }
3681
3682 /// Sums the elements of an iterator.
3683 ///
3684 /// Takes each element, adds them together, and returns the result.
3685 ///
3686 /// An empty iterator returns the *additive identity* ("zero") of the type,
3687 /// which is `0` for integers and `-0.0` for floats.
3688 ///
3689 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3690 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3691 ///
3692 /// # Panics
3693 ///
3694 /// When calling `sum()` and a primitive integer type is being returned, this
3695 /// method will panic if the computation overflows and overflow checks are
3696 /// enabled.
3697 ///
3698 /// # Examples
3699 ///
3700 /// ```
3701 /// let a = [1, 2, 3];
3702 /// let sum: i32 = a.iter().sum();
3703 ///
3704 /// assert_eq!(sum, 6);
3705 ///
3706 /// let b: Vec<f32> = vec![];
3707 /// let sum: f32 = b.iter().sum();
3708 /// assert_eq!(sum, -0.0_f32);
3709 /// ```
3710 #[stable(feature = "iter_arith", since = "1.11.0")]
3711 #[rustc_non_const_trait_method]
3712 fn sum<S>(self) -> S
3713 where
3714 Self: Sized,
3715 S: Sum<Self::Item>,
3716 {
3717 Sum::sum(self)
3718 }
3719
3720 /// Iterates over the entire iterator, multiplying all the elements
3721 ///
3722 /// An empty iterator returns the one value of the type.
3723 ///
3724 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3725 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3726 ///
3727 /// # Panics
3728 ///
3729 /// When calling `product()` and a primitive integer type is being returned,
3730 /// method will panic if the computation overflows and overflow checks are
3731 /// enabled.
3732 ///
3733 /// # Examples
3734 ///
3735 /// ```
3736 /// fn factorial(n: u32) -> u32 {
3737 /// (1..=n).product()
3738 /// }
3739 /// assert_eq!(factorial(0), 1);
3740 /// assert_eq!(factorial(1), 1);
3741 /// assert_eq!(factorial(5), 120);
3742 /// ```
3743 #[stable(feature = "iter_arith", since = "1.11.0")]
3744 #[cfg(not(feature = "ferrocene_subset"))]
3745 #[rustc_non_const_trait_method]
3746 fn product<P>(self) -> P
3747 where
3748 Self: Sized,
3749 P: Product<Self::Item>,
3750 {
3751 Product::product(self)
3752 }
3753
3754 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3755 /// of another.
3756 ///
3757 /// # Examples
3758 ///
3759 /// ```
3760 /// use std::cmp::Ordering;
3761 ///
3762 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3763 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3764 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3765 /// ```
3766 #[stable(feature = "iter_order", since = "1.5.0")]
3767 #[rustc_non_const_trait_method]
3768 fn cmp<I>(self, other: I) -> Ordering
3769 where
3770 I: IntoIterator<Item = Self::Item>,
3771 Self::Item: Ord,
3772 Self: Sized,
3773 {
3774 self.cmp_by(other, |x, y| x.cmp(&y))
3775 }
3776
3777 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3778 /// of another with respect to the specified comparison function.
3779 ///
3780 /// # Examples
3781 ///
3782 /// ```
3783 /// #![feature(iter_order_by)]
3784 ///
3785 /// use std::cmp::Ordering;
3786 ///
3787 /// let xs = [1, 2, 3, 4];
3788 /// let ys = [1, 4, 9, 16];
3789 ///
3790 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3791 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3792 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3793 /// ```
3794 #[unstable(feature = "iter_order_by", issue = "64295")]
3795 #[rustc_non_const_trait_method]
3796 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3797 where
3798 Self: Sized,
3799 I: IntoIterator,
3800 F: FnMut(Self::Item, I::Item) -> Ordering,
3801 {
3802 #[inline]
3803 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3804 where
3805 F: FnMut(X, Y) -> Ordering,
3806 {
3807 move |x, y| match cmp(x, y) {
3808 Ordering::Equal => ControlFlow::Continue(()),
3809 non_eq => ControlFlow::Break(non_eq),
3810 }
3811 }
3812
3813 match iter_compare(self, other.into_iter(), compare(cmp)) {
3814 ControlFlow::Continue(ord) => ord,
3815 ControlFlow::Break(ord) => ord,
3816 }
3817 }
3818
3819 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3820 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3821 /// evaluation, returning a result without comparing the remaining elements.
3822 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3823 ///
3824 /// # Examples
3825 ///
3826 /// ```
3827 /// use std::cmp::Ordering;
3828 ///
3829 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3830 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3831 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3832 /// ```
3833 ///
3834 /// For floating-point numbers, NaN does not have a total order and will result
3835 /// in `None` when compared:
3836 ///
3837 /// ```
3838 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3839 /// ```
3840 ///
3841 /// The results are determined by the order of evaluation.
3842 ///
3843 /// ```
3844 /// use std::cmp::Ordering;
3845 ///
3846 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3847 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3848 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3849 /// ```
3850 ///
3851 #[stable(feature = "iter_order", since = "1.5.0")]
3852 #[cfg(not(feature = "ferrocene_subset"))]
3853 #[rustc_non_const_trait_method]
3854 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3855 where
3856 I: IntoIterator,
3857 Self::Item: PartialOrd<I::Item>,
3858 Self: Sized,
3859 {
3860 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3861 }
3862
3863 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3864 /// of another with respect to the specified comparison function.
3865 ///
3866 /// # Examples
3867 ///
3868 /// ```
3869 /// #![feature(iter_order_by)]
3870 ///
3871 /// use std::cmp::Ordering;
3872 ///
3873 /// let xs = [1.0, 2.0, 3.0, 4.0];
3874 /// let ys = [1.0, 4.0, 9.0, 16.0];
3875 ///
3876 /// assert_eq!(
3877 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3878 /// Some(Ordering::Less)
3879 /// );
3880 /// assert_eq!(
3881 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3882 /// Some(Ordering::Equal)
3883 /// );
3884 /// assert_eq!(
3885 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3886 /// Some(Ordering::Greater)
3887 /// );
3888 /// ```
3889 #[unstable(feature = "iter_order_by", issue = "64295")]
3890 #[cfg(not(feature = "ferrocene_subset"))]
3891 #[rustc_non_const_trait_method]
3892 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3893 where
3894 Self: Sized,
3895 I: IntoIterator,
3896 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3897 {
3898 #[inline]
3899 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3900 where
3901 F: FnMut(X, Y) -> Option<Ordering>,
3902 {
3903 move |x, y| match partial_cmp(x, y) {
3904 Some(Ordering::Equal) => ControlFlow::Continue(()),
3905 non_eq => ControlFlow::Break(non_eq),
3906 }
3907 }
3908
3909 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3910 ControlFlow::Continue(ord) => Some(ord),
3911 ControlFlow::Break(ord) => ord,
3912 }
3913 }
3914
3915 /// Determines if the elements of this [`Iterator`] are equal to those of
3916 /// another.
3917 ///
3918 /// # Examples
3919 ///
3920 /// ```
3921 /// assert_eq!([1].iter().eq([1].iter()), true);
3922 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3923 /// ```
3924 #[stable(feature = "iter_order", since = "1.5.0")]
3925 #[rustc_non_const_trait_method]
3926 fn eq<I>(self, other: I) -> bool
3927 where
3928 I: IntoIterator,
3929 Self::Item: PartialEq<I::Item>,
3930 Self: Sized,
3931 {
3932 self.eq_by(other, |x, y| x == y)
3933 }
3934
3935 /// Determines if the elements of this [`Iterator`] are equal to those of
3936 /// another with respect to the specified equality function.
3937 ///
3938 /// # Examples
3939 ///
3940 /// ```
3941 /// #![feature(iter_order_by)]
3942 ///
3943 /// let xs = [1, 2, 3, 4];
3944 /// let ys = [1, 4, 9, 16];
3945 ///
3946 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3947 /// ```
3948 #[unstable(feature = "iter_order_by", issue = "64295")]
3949 #[rustc_non_const_trait_method]
3950 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3951 where
3952 Self: Sized,
3953 I: IntoIterator,
3954 F: FnMut(Self::Item, I::Item) -> bool,
3955 {
3956 #[inline]
3957 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3958 where
3959 F: FnMut(X, Y) -> bool,
3960 {
3961 move |x, y| {
3962 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3963 }
3964 }
3965
3966 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3967 }
3968
3969 /// Determines if the elements of this [`Iterator`] are not equal to those of
3970 /// another.
3971 ///
3972 /// # Examples
3973 ///
3974 /// ```
3975 /// assert_eq!([1].iter().ne([1].iter()), false);
3976 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3977 /// ```
3978 #[stable(feature = "iter_order", since = "1.5.0")]
3979 #[cfg(not(feature = "ferrocene_subset"))]
3980 #[rustc_non_const_trait_method]
3981 fn ne<I>(self, other: I) -> bool
3982 where
3983 I: IntoIterator,
3984 Self::Item: PartialEq<I::Item>,
3985 Self: Sized,
3986 {
3987 !self.eq(other)
3988 }
3989
3990 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3991 /// less than those of another.
3992 ///
3993 /// # Examples
3994 ///
3995 /// ```
3996 /// assert_eq!([1].iter().lt([1].iter()), false);
3997 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3998 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3999 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
4000 /// ```
4001 #[stable(feature = "iter_order", since = "1.5.0")]
4002 #[cfg(not(feature = "ferrocene_subset"))]
4003 #[rustc_non_const_trait_method]
4004 fn lt<I>(self, other: I) -> bool
4005 where
4006 I: IntoIterator,
4007 Self::Item: PartialOrd<I::Item>,
4008 Self: Sized,
4009 {
4010 self.partial_cmp(other) == Some(Ordering::Less)
4011 }
4012
4013 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4014 /// less or equal to those of another.
4015 ///
4016 /// # Examples
4017 ///
4018 /// ```
4019 /// assert_eq!([1].iter().le([1].iter()), true);
4020 /// assert_eq!([1].iter().le([1, 2].iter()), true);
4021 /// assert_eq!([1, 2].iter().le([1].iter()), false);
4022 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
4023 /// ```
4024 #[stable(feature = "iter_order", since = "1.5.0")]
4025 #[cfg(not(feature = "ferrocene_subset"))]
4026 #[rustc_non_const_trait_method]
4027 fn le<I>(self, other: I) -> bool
4028 where
4029 I: IntoIterator,
4030 Self::Item: PartialOrd<I::Item>,
4031 Self: Sized,
4032 {
4033 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
4034 }
4035
4036 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4037 /// greater than those of another.
4038 ///
4039 /// # Examples
4040 ///
4041 /// ```
4042 /// assert_eq!([1].iter().gt([1].iter()), false);
4043 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
4044 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
4045 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
4046 /// ```
4047 #[stable(feature = "iter_order", since = "1.5.0")]
4048 #[cfg(not(feature = "ferrocene_subset"))]
4049 #[rustc_non_const_trait_method]
4050 fn gt<I>(self, other: I) -> bool
4051 where
4052 I: IntoIterator,
4053 Self::Item: PartialOrd<I::Item>,
4054 Self: Sized,
4055 {
4056 self.partial_cmp(other) == Some(Ordering::Greater)
4057 }
4058
4059 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4060 /// greater than or equal to those of another.
4061 ///
4062 /// # Examples
4063 ///
4064 /// ```
4065 /// assert_eq!([1].iter().ge([1].iter()), true);
4066 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
4067 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
4068 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
4069 /// ```
4070 #[stable(feature = "iter_order", since = "1.5.0")]
4071 #[cfg(not(feature = "ferrocene_subset"))]
4072 #[rustc_non_const_trait_method]
4073 fn ge<I>(self, other: I) -> bool
4074 where
4075 I: IntoIterator,
4076 Self::Item: PartialOrd<I::Item>,
4077 Self: Sized,
4078 {
4079 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
4080 }
4081
4082 /// Checks if the elements of this iterator are sorted.
4083 ///
4084 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4085 /// iterator yields exactly zero or one element, `true` is returned.
4086 ///
4087 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4088 /// implies that this function returns `false` if any two consecutive items are not
4089 /// comparable.
4090 ///
4091 /// # Examples
4092 ///
4093 /// ```
4094 /// assert!([1, 2, 2, 9].iter().is_sorted());
4095 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4096 /// assert!([0].iter().is_sorted());
4097 /// assert!(std::iter::empty::<i32>().is_sorted());
4098 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4099 /// ```
4100 #[inline]
4101 #[stable(feature = "is_sorted", since = "1.82.0")]
4102 #[cfg(not(feature = "ferrocene_subset"))]
4103 #[rustc_non_const_trait_method]
4104 fn is_sorted(self) -> bool
4105 where
4106 Self: Sized,
4107 Self::Item: PartialOrd,
4108 {
4109 self.is_sorted_by(|a, b| a <= b)
4110 }
4111
4112 /// Checks if the elements of this iterator are sorted using the given comparator function.
4113 ///
4114 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4115 /// function to determine whether two elements are to be considered in sorted order.
4116 ///
4117 /// # Examples
4118 ///
4119 /// ```
4120 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4121 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4122 ///
4123 /// assert!([0].iter().is_sorted_by(|a, b| true));
4124 /// assert!([0].iter().is_sorted_by(|a, b| false));
4125 ///
4126 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4127 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4128 /// ```
4129 #[stable(feature = "is_sorted", since = "1.82.0")]
4130 #[cfg(not(feature = "ferrocene_subset"))]
4131 #[rustc_non_const_trait_method]
4132 fn is_sorted_by<F>(mut self, compare: F) -> bool
4133 where
4134 Self: Sized,
4135 F: FnMut(&Self::Item, &Self::Item) -> bool,
4136 {
4137 #[inline]
4138 fn check<'a, T>(
4139 last: &'a mut T,
4140 mut compare: impl FnMut(&T, &T) -> bool + 'a,
4141 ) -> impl FnMut(T) -> bool + 'a {
4142 move |curr| {
4143 if !compare(&last, &curr) {
4144 return false;
4145 }
4146 *last = curr;
4147 true
4148 }
4149 }
4150
4151 let mut last = match self.next() {
4152 Some(e) => e,
4153 None => return true,
4154 };
4155
4156 self.all(check(&mut last, compare))
4157 }
4158
4159 /// Checks if the elements of this iterator are sorted using the given key extraction
4160 /// function.
4161 ///
4162 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4163 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4164 /// its documentation for more information.
4165 ///
4166 /// [`is_sorted`]: Iterator::is_sorted
4167 ///
4168 /// # Examples
4169 ///
4170 /// ```
4171 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4172 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4173 /// ```
4174 #[inline]
4175 #[stable(feature = "is_sorted", since = "1.82.0")]
4176 #[cfg(not(feature = "ferrocene_subset"))]
4177 #[rustc_non_const_trait_method]
4178 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4179 where
4180 Self: Sized,
4181 F: FnMut(Self::Item) -> K,
4182 K: PartialOrd,
4183 {
4184 self.map(f).is_sorted()
4185 }
4186
4187 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4188 // The unusual name is to avoid name collisions in method resolution
4189 // see #76479.
4190 #[inline]
4191 #[doc(hidden)]
4192 #[unstable(feature = "trusted_random_access", issue = "none")]
4193 #[cfg(not(feature = "ferrocene_subset"))]
4194 #[rustc_non_const_trait_method]
4195 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4196 where
4197 Self: TrustedRandomAccessNoCoerce,
4198 {
4199 unreachable!("Always specialized");
4200 }
4201}
4202
4203trait SpecIterEq<B: Iterator>: Iterator {
4204 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4205 where
4206 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4207}
4208
4209impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4210 #[inline]
4211 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4212 where
4213 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4214 {
4215 iter_eq(self, b, f)
4216 }
4217}
4218
4219impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4220 #[inline]
4221 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4222 where
4223 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4224 {
4225 // we *can't* short-circuit if:
4226 match (self.size_hint(), b.size_hint()) {
4227 // ... both iterators have the same length
4228 ((_, Some(a)), (_, Some(b))) if a == b => {}
4229 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4230 ((_, None), (_, None)) => {}
4231 // otherwise, we can ascertain that they are unequal without actually comparing items
4232 _ => return false,
4233 }
4234
4235 iter_eq(self, b, f)
4236 }
4237}
4238
4239/// Compares two iterators element-wise using the given function.
4240///
4241/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4242/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4243/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4244/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4245/// the iterators.
4246///
4247/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4248/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4249#[inline]
4250fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4251where
4252 A: Iterator,
4253 B: Iterator,
4254 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4255{
4256 #[inline]
4257 fn compare<'a, B, X, T>(
4258 b: &'a mut B,
4259 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4260 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4261 where
4262 B: Iterator,
4263 {
4264 move |x| match b.next() {
4265 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4266 Some(y) => f(x, y).map_break(ControlFlow::Break),
4267 }
4268 }
4269
4270 match a.try_for_each(compare(&mut b, f)) {
4271 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4272 None => Ordering::Equal,
4273 Some(_) => Ordering::Less,
4274 }),
4275 ControlFlow::Break(x) => x,
4276 }
4277}
4278
4279#[inline]
4280fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4281where
4282 A: Iterator,
4283 B: Iterator,
4284 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4285{
4286 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4287}
4288
4289/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4290///
4291/// This implementation passes all method calls on to the original iterator.
4292#[stable(feature = "rust1", since = "1.0.0")]
4293impl<I: Iterator + ?Sized> Iterator for &mut I {
4294 type Item = I::Item;
4295 #[inline]
4296 fn next(&mut self) -> Option<I::Item> {
4297 (**self).next()
4298 }
4299 fn size_hint(&self) -> (usize, Option<usize>) {
4300 (**self).size_hint()
4301 }
4302 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4303 (**self).advance_by(n)
4304 }
4305 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4306 (**self).nth(n)
4307 }
4308 #[cfg(not(feature = "ferrocene_subset"))]
4309 fn fold<B, F>(self, init: B, f: F) -> B
4310 where
4311 F: FnMut(B, Self::Item) -> B,
4312 {
4313 self.spec_fold(init, f)
4314 }
4315 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4316 where
4317 F: FnMut(B, Self::Item) -> R,
4318 R: Try<Output = B>,
4319 {
4320 self.spec_try_fold(init, f)
4321 }
4322}
4323
4324/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4325trait IteratorRefSpec: Iterator {
4326 #[cfg(not(feature = "ferrocene_subset"))]
4327 fn spec_fold<B, F>(self, init: B, f: F) -> B
4328 where
4329 F: FnMut(B, Self::Item) -> B;
4330
4331 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4332 where
4333 F: FnMut(B, Self::Item) -> R,
4334 R: Try<Output = B>;
4335}
4336
4337impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4338 #[cfg(not(feature = "ferrocene_subset"))]
4339 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4340 where
4341 F: FnMut(B, Self::Item) -> B,
4342 {
4343 let mut accum = init;
4344 while let Some(x) = self.next() {
4345 accum = f(accum, x);
4346 }
4347 accum
4348 }
4349
4350 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4351 where
4352 F: FnMut(B, Self::Item) -> R,
4353 R: Try<Output = B>,
4354 {
4355 let mut accum = init;
4356 while let Some(x) = self.next() {
4357 accum = f(accum, x)?;
4358 }
4359 try { accum }
4360 }
4361}
4362
4363#[cfg(not(feature = "ferrocene_subset"))]
4364impl<I: Iterator> IteratorRefSpec for &mut I {
4365 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4366
4367 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4368 where
4369 F: FnMut(B, Self::Item) -> R,
4370 R: Try<Output = B>,
4371 {
4372 (**self).try_fold(init, f)
4373 }
4374}