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