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 /// [`slice::windows()`]: slice::windows
1661 /// [`FusedIterator`]: crate::iter::FusedIterator
1662 ///
1663 /// # Panics
1664 ///
1665 /// Panics if `N` is zero. This check will most probably get changed to a
1666 /// compile time error before this method gets stabilized.
1667 ///
1668 /// ```should_panic
1669 /// #![feature(iter_map_windows)]
1670 ///
1671 /// let iter = std::iter::repeat(0).map_windows(|&[]| ());
1672 /// ```
1673 ///
1674 /// # Examples
1675 ///
1676 /// Building the sums of neighboring numbers.
1677 ///
1678 /// ```
1679 /// #![feature(iter_map_windows)]
1680 ///
1681 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1682 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1683 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1684 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1685 /// assert_eq!(it.next(), None);
1686 /// ```
1687 ///
1688 /// Since the elements in the following example implement `Copy`, we can
1689 /// just copy the array and get an iterator over the windows.
1690 ///
1691 /// ```
1692 /// #![feature(iter_map_windows)]
1693 ///
1694 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1695 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1696 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1697 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1698 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1699 /// assert_eq!(it.next(), None);
1700 /// ```
1701 ///
1702 /// You can also use this function to check the sortedness of an iterator.
1703 /// For the simple case, rather use [`Iterator::is_sorted`].
1704 ///
1705 /// ```
1706 /// #![feature(iter_map_windows)]
1707 ///
1708 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1709 /// .map_windows(|[a, b]| a <= b);
1710 ///
1711 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1712 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1713 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1714 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1715 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1716 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1717 /// assert_eq!(it.next(), None);
1718 /// ```
1719 ///
1720 /// For non-fused iterators, the window is reset after `None` is yielded.
1721 ///
1722 /// ```
1723 /// #![feature(iter_map_windows)]
1724 ///
1725 /// #[derive(Default)]
1726 /// struct NonFusedIterator {
1727 /// state: i32,
1728 /// }
1729 ///
1730 /// impl Iterator for NonFusedIterator {
1731 /// type Item = i32;
1732 ///
1733 /// fn next(&mut self) -> Option<i32> {
1734 /// let val = self.state;
1735 /// self.state = self.state + 1;
1736 ///
1737 /// // Skip every 5th number
1738 /// if (val + 1) % 5 == 0 {
1739 /// None
1740 /// } else {
1741 /// Some(val)
1742 /// }
1743 /// }
1744 /// }
1745 ///
1746 ///
1747 /// let mut iter = NonFusedIterator::default();
1748 ///
1749 /// assert_eq!(iter.next(), Some(0));
1750 /// assert_eq!(iter.next(), Some(1));
1751 /// assert_eq!(iter.next(), Some(2));
1752 /// assert_eq!(iter.next(), Some(3));
1753 /// assert_eq!(iter.next(), None);
1754 /// assert_eq!(iter.next(), Some(5));
1755 /// assert_eq!(iter.next(), Some(6));
1756 /// assert_eq!(iter.next(), Some(7));
1757 /// assert_eq!(iter.next(), Some(8));
1758 /// assert_eq!(iter.next(), None);
1759 /// assert_eq!(iter.next(), Some(10));
1760 /// assert_eq!(iter.next(), Some(11));
1761 ///
1762 /// let mut iter = NonFusedIterator::default()
1763 /// .map_windows(|arr: &[_; 2]| *arr);
1764 ///
1765 /// assert_eq!(iter.next(), Some([0, 1]));
1766 /// assert_eq!(iter.next(), Some([1, 2]));
1767 /// assert_eq!(iter.next(), Some([2, 3]));
1768 /// assert_eq!(iter.next(), None);
1769 ///
1770 /// assert_eq!(iter.next(), Some([5, 6]));
1771 /// assert_eq!(iter.next(), Some([6, 7]));
1772 /// assert_eq!(iter.next(), Some([7, 8]));
1773 /// assert_eq!(iter.next(), None);
1774 ///
1775 /// assert_eq!(iter.next(), Some([10, 11]));
1776 /// assert_eq!(iter.next(), Some([11, 12]));
1777 /// assert_eq!(iter.next(), Some([12, 13]));
1778 /// assert_eq!(iter.next(), None);
1779 /// ```
1780 #[inline]
1781 #[unstable(feature = "iter_map_windows", issue = "87155")]
1782 #[rustc_non_const_trait_method]
1783 fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
1784 where
1785 Self: Sized,
1786 F: FnMut(&[Self::Item; N]) -> R,
1787 {
1788 MapWindows::new(self, f)
1789 }
1790
1791 /// Creates an iterator which ends after the first [`None`].
1792 ///
1793 /// After an iterator returns [`None`], future calls may or may not yield
1794 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1795 /// [`None`] is given, it will always return [`None`] forever.
1796 ///
1797 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1798 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1799 /// if the [`FusedIterator`] trait is improperly implemented.
1800 ///
1801 /// [`Some(T)`]: Some
1802 /// [`FusedIterator`]: crate::iter::FusedIterator
1803 ///
1804 /// # Examples
1805 ///
1806 /// ```
1807 /// // an iterator which alternates between Some and None
1808 /// struct Alternate {
1809 /// state: i32,
1810 /// }
1811 ///
1812 /// impl Iterator for Alternate {
1813 /// type Item = i32;
1814 ///
1815 /// fn next(&mut self) -> Option<i32> {
1816 /// let val = self.state;
1817 /// self.state = self.state + 1;
1818 ///
1819 /// // if it's even, Some(i32), else None
1820 /// (val % 2 == 0).then_some(val)
1821 /// }
1822 /// }
1823 ///
1824 /// let mut iter = Alternate { state: 0 };
1825 ///
1826 /// // we can see our iterator going back and forth
1827 /// assert_eq!(iter.next(), Some(0));
1828 /// assert_eq!(iter.next(), None);
1829 /// assert_eq!(iter.next(), Some(2));
1830 /// assert_eq!(iter.next(), None);
1831 ///
1832 /// // however, once we fuse it...
1833 /// let mut iter = iter.fuse();
1834 ///
1835 /// assert_eq!(iter.next(), Some(4));
1836 /// assert_eq!(iter.next(), None);
1837 ///
1838 /// // it will always return `None` after the first time.
1839 /// assert_eq!(iter.next(), None);
1840 /// assert_eq!(iter.next(), None);
1841 /// assert_eq!(iter.next(), None);
1842 /// ```
1843 #[inline]
1844 #[stable(feature = "rust1", since = "1.0.0")]
1845 #[rustc_non_const_trait_method]
1846 fn fuse(self) -> Fuse<Self>
1847 where
1848 Self: Sized,
1849 {
1850 Fuse::new(self)
1851 }
1852
1853 /// Does something with each element of an iterator, passing the value on.
1854 ///
1855 /// When using iterators, you'll often chain several of them together.
1856 /// While working on such code, you might want to check out what's
1857 /// happening at various parts in the pipeline. To do that, insert
1858 /// a call to `inspect()`.
1859 ///
1860 /// It's more common for `inspect()` to be used as a debugging tool than to
1861 /// exist in your final code, but applications may find it useful in certain
1862 /// situations when errors need to be logged before being discarded.
1863 ///
1864 /// # Examples
1865 ///
1866 /// Basic usage:
1867 ///
1868 /// ```
1869 /// let a = [1, 4, 2, 3];
1870 ///
1871 /// // this iterator sequence is complex.
1872 /// let sum = a.iter()
1873 /// .cloned()
1874 /// .filter(|x| x % 2 == 0)
1875 /// .fold(0, |sum, i| sum + i);
1876 ///
1877 /// println!("{sum}");
1878 ///
1879 /// // let's add some inspect() calls to investigate what's happening
1880 /// let sum = a.iter()
1881 /// .cloned()
1882 /// .inspect(|x| println!("about to filter: {x}"))
1883 /// .filter(|x| x % 2 == 0)
1884 /// .inspect(|x| println!("made it through filter: {x}"))
1885 /// .fold(0, |sum, i| sum + i);
1886 ///
1887 /// println!("{sum}");
1888 /// ```
1889 ///
1890 /// This will print:
1891 ///
1892 /// ```text
1893 /// 6
1894 /// about to filter: 1
1895 /// about to filter: 4
1896 /// made it through filter: 4
1897 /// about to filter: 2
1898 /// made it through filter: 2
1899 /// about to filter: 3
1900 /// 6
1901 /// ```
1902 ///
1903 /// Logging errors before discarding them:
1904 ///
1905 /// ```
1906 /// let lines = ["1", "2", "a"];
1907 ///
1908 /// let sum: i32 = lines
1909 /// .iter()
1910 /// .map(|line| line.parse::<i32>())
1911 /// .inspect(|num| {
1912 /// if let Err(ref e) = *num {
1913 /// println!("Parsing error: {e}");
1914 /// }
1915 /// })
1916 /// .filter_map(Result::ok)
1917 /// .sum();
1918 ///
1919 /// println!("Sum: {sum}");
1920 /// ```
1921 ///
1922 /// This will print:
1923 ///
1924 /// ```text
1925 /// Parsing error: invalid digit found in string
1926 /// Sum: 3
1927 /// ```
1928 #[inline]
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 #[rustc_non_const_trait_method]
1931 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1932 where
1933 Self: Sized,
1934 F: FnMut(&Self::Item),
1935 {
1936 Inspect::new(self, f)
1937 }
1938
1939 /// Creates a "by reference" adapter for this instance of `Iterator`.
1940 ///
1941 /// Consuming method calls (direct or indirect calls to `next`)
1942 /// on the "by reference" adapter will consume the original iterator,
1943 /// but ownership-taking methods (those with a `self` parameter)
1944 /// only take ownership of the "by reference" iterator.
1945 ///
1946 /// This is useful for applying ownership-taking methods
1947 /// (such as `take` in the example below)
1948 /// without giving up ownership of the original iterator,
1949 /// so you can use the original iterator afterwards.
1950 ///
1951 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I).
1952 ///
1953 /// # Examples
1954 ///
1955 /// ```
1956 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1957 ///
1958 /// // Take the first two words.
1959 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1960 /// assert_eq!(hello_world, vec!["hello", "world"]);
1961 ///
1962 /// // Collect the rest of the words.
1963 /// // We can only do this because we used `by_ref` earlier.
1964 /// let of_rust: Vec<_> = words.collect();
1965 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1966 /// ```
1967 #[stable(feature = "rust1", since = "1.0.0")]
1968 fn by_ref(&mut self) -> &mut Self
1969 where
1970 Self: Sized,
1971 {
1972 self
1973 }
1974
1975 /// Transforms an iterator into a collection.
1976 ///
1977 /// `collect()` takes ownership of an iterator and produces whichever
1978 /// collection type you request. The iterator itself carries no knowledge of
1979 /// the eventual container; the target collection is chosen entirely by the
1980 /// type you ask `collect()` to return. This makes `collect()` one of the
1981 /// more powerful methods in the standard library, and it shows up in a wide
1982 /// variety of contexts.
1983 ///
1984 /// The most basic pattern in which `collect()` is used is to turn one
1985 /// collection into another. You take a collection, call [`iter`] on it,
1986 /// do a bunch of transformations, and then `collect()` at the end.
1987 ///
1988 /// `collect()` can also create instances of types that are not typical
1989 /// collections. For example, a [`String`] can be built from [`char`]s,
1990 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1991 /// into `Result<Collection<T>, E>`. See the examples below for more.
1992 ///
1993 /// Because `collect()` is so general, it can cause problems with type
1994 /// inference. As such, `collect()` is one of the few times you'll see
1995 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1996 /// helps the inference algorithm understand specifically which collection
1997 /// you're trying to collect into.
1998 ///
1999 /// # Examples
2000 ///
2001 /// Basic usage:
2002 ///
2003 /// ```
2004 /// let a = [1, 2, 3];
2005 ///
2006 /// let doubled: Vec<i32> = a.iter()
2007 /// .map(|x| x * 2)
2008 /// .collect();
2009 ///
2010 /// assert_eq!(vec![2, 4, 6], doubled);
2011 /// ```
2012 ///
2013 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
2014 /// we could collect into, for example, a [`VecDeque<T>`] instead:
2015 ///
2016 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
2017 ///
2018 /// ```
2019 /// use std::collections::VecDeque;
2020 ///
2021 /// let a = [1, 2, 3];
2022 ///
2023 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
2024 ///
2025 /// assert_eq!(2, doubled[0]);
2026 /// assert_eq!(4, doubled[1]);
2027 /// assert_eq!(6, doubled[2]);
2028 /// ```
2029 ///
2030 /// Using the 'turbofish' instead of annotating `doubled`:
2031 ///
2032 /// ```
2033 /// let a = [1, 2, 3];
2034 ///
2035 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
2036 ///
2037 /// assert_eq!(vec![2, 4, 6], doubled);
2038 /// ```
2039 ///
2040 /// Because `collect()` only cares about what you're collecting into, you can
2041 /// still use a partial type hint, `_`, with the turbofish:
2042 ///
2043 /// ```
2044 /// let a = [1, 2, 3];
2045 ///
2046 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2047 ///
2048 /// assert_eq!(vec![2, 4, 6], doubled);
2049 /// ```
2050 ///
2051 /// Using `collect()` to make a [`String`]:
2052 ///
2053 /// ```
2054 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2055 ///
2056 /// let hello: String = chars.into_iter()
2057 /// .map(|x| x as u8)
2058 /// .map(|x| (x + 1) as char)
2059 /// .collect();
2060 ///
2061 /// assert_eq!("hello", hello);
2062 /// ```
2063 ///
2064 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2065 /// see if any of them failed:
2066 ///
2067 /// ```
2068 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2069 ///
2070 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2071 ///
2072 /// // gives us the first error
2073 /// assert_eq!(Err("nope"), result);
2074 ///
2075 /// let results = [Ok(1), Ok(3)];
2076 ///
2077 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2078 ///
2079 /// // gives us the list of answers
2080 /// assert_eq!(Ok(vec![1, 3]), result);
2081 /// ```
2082 ///
2083 /// [`iter`]: Iterator::next
2084 /// [`String`]: ../../std/string/struct.String.html
2085 /// [`char`]: type@char
2086 #[inline]
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2089 #[rustc_diagnostic_item = "iterator_collect_fn"]
2090 #[rustc_non_const_trait_method]
2091 fn collect<B: FromIterator<Self::Item>>(self) -> B
2092 where
2093 Self: Sized,
2094 {
2095 // This is too aggressive to turn on for everything all the time, but PR#137908
2096 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2097 // so this will help catch such things in debug-assertions-std runners,
2098 // even if users won't actually ever see it.
2099 if cfg!(debug_assertions) {
2100 let hint = self.size_hint();
2101 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2102 }
2103
2104 FromIterator::from_iter(self)
2105 }
2106
2107 /// Fallibly transforms an iterator into a collection, short circuiting if
2108 /// a failure is encountered.
2109 ///
2110 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2111 /// conversions during collection. Its main use case is simplifying conversions from
2112 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2113 /// types (e.g. [`Result`]).
2114 ///
2115 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2116 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2117 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2118 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2119 ///
2120 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2121 /// may continue to be used, in which case it will continue iterating starting after the element that
2122 /// triggered the failure. See the last example below for an example of how this works.
2123 ///
2124 /// # Examples
2125 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2126 /// ```
2127 /// #![feature(iterator_try_collect)]
2128 ///
2129 /// let u = vec![Some(1), Some(2), Some(3)];
2130 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2131 /// assert_eq!(v, Some(vec![1, 2, 3]));
2132 /// ```
2133 ///
2134 /// Failing to collect in the same way:
2135 /// ```
2136 /// #![feature(iterator_try_collect)]
2137 ///
2138 /// let u = vec![Some(1), Some(2), None, Some(3)];
2139 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2140 /// assert_eq!(v, None);
2141 /// ```
2142 ///
2143 /// A similar example, but with `Result`:
2144 /// ```
2145 /// #![feature(iterator_try_collect)]
2146 ///
2147 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2148 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2149 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2150 ///
2151 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2152 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2153 /// assert_eq!(v, Err(()));
2154 /// ```
2155 ///
2156 /// Finally, even [`ControlFlow`] works, despite the fact that it
2157 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2158 /// continue to be used, even if a failure is encountered:
2159 ///
2160 /// ```
2161 /// #![feature(iterator_try_collect)]
2162 ///
2163 /// use core::ops::ControlFlow::{Break, Continue};
2164 ///
2165 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2166 /// let mut it = u.into_iter();
2167 ///
2168 /// let v = it.try_collect::<Vec<_>>();
2169 /// assert_eq!(v, Break(3));
2170 ///
2171 /// let v = it.try_collect::<Vec<_>>();
2172 /// assert_eq!(v, Continue(vec![4, 5]));
2173 /// ```
2174 ///
2175 /// [`collect`]: Iterator::collect
2176 #[inline]
2177 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2178 #[rustc_non_const_trait_method]
2179 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2180 where
2181 Self: Sized,
2182 Self::Item: Try<Residual: Residual<B>>,
2183 B: FromIterator<<Self::Item as Try>::Output>,
2184 {
2185 try_process(ByRefSized(self), |i| i.collect())
2186 }
2187
2188 /// Collects all the items from an iterator into a collection.
2189 ///
2190 /// This method consumes the iterator and adds all its items to the
2191 /// passed collection. The collection is then returned, so the call chain
2192 /// can be continued.
2193 ///
2194 /// This is useful when you already have a collection and want to add
2195 /// the iterator items to it.
2196 ///
2197 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2198 /// but instead of being called on a collection, it's called on an iterator.
2199 ///
2200 /// # Examples
2201 ///
2202 /// Basic usage:
2203 ///
2204 /// ```
2205 /// #![feature(iter_collect_into)]
2206 ///
2207 /// let a = [1, 2, 3];
2208 /// let mut vec: Vec::<i32> = vec![0, 1];
2209 ///
2210 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2211 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2212 ///
2213 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2214 /// ```
2215 ///
2216 /// `Vec` can have a manual set capacity to avoid reallocating it:
2217 ///
2218 /// ```
2219 /// #![feature(iter_collect_into)]
2220 ///
2221 /// let a = [1, 2, 3];
2222 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2223 ///
2224 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2225 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2226 ///
2227 /// assert_eq!(6, vec.capacity());
2228 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2229 /// ```
2230 ///
2231 /// The returned mutable reference can be used to continue the call chain:
2232 ///
2233 /// ```
2234 /// #![feature(iter_collect_into)]
2235 ///
2236 /// let a = [1, 2, 3];
2237 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2238 ///
2239 /// let count = a.iter().collect_into(&mut vec).iter().count();
2240 ///
2241 /// assert_eq!(count, vec.len());
2242 /// assert_eq!(vec, vec![1, 2, 3]);
2243 ///
2244 /// let count = a.iter().collect_into(&mut vec).iter().count();
2245 ///
2246 /// assert_eq!(count, vec.len());
2247 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2248 /// ```
2249 #[inline]
2250 #[unstable(feature = "iter_collect_into", issue = "94780")]
2251 #[rustc_non_const_trait_method]
2252 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2253 where
2254 Self: Sized,
2255 {
2256 collection.extend(self);
2257 collection
2258 }
2259
2260 /// Consumes an iterator, creating two collections from it.
2261 ///
2262 /// The predicate passed to `partition()` can return `true`, or `false`.
2263 /// `partition()` returns a pair, all of the elements for which it returned
2264 /// `true`, and all of the elements for which it returned `false`.
2265 ///
2266 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2267 ///
2268 /// [`is_partitioned()`]: Iterator::is_partitioned
2269 /// [`partition_in_place()`]: Iterator::partition_in_place
2270 ///
2271 /// # Examples
2272 ///
2273 /// ```
2274 /// let a = [1, 2, 3];
2275 ///
2276 /// let (even, odd): (Vec<_>, Vec<_>) = a
2277 /// .into_iter()
2278 /// .partition(|n| n % 2 == 0);
2279 ///
2280 /// assert_eq!(even, [2]);
2281 /// assert_eq!(odd, [1, 3]);
2282 /// ```
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 #[rustc_non_const_trait_method]
2285 fn partition<B, F>(self, f: F) -> (B, B)
2286 where
2287 Self: Sized,
2288 B: Default + Extend<Self::Item>,
2289 F: FnMut(&Self::Item) -> bool,
2290 {
2291 #[inline]
2292 fn extend<'a, T, B: Extend<T>>(
2293 mut f: impl FnMut(&T) -> bool + 'a,
2294 left: &'a mut B,
2295 right: &'a mut B,
2296 ) -> impl FnMut((), T) + 'a {
2297 move |(), x| {
2298 if f(&x) {
2299 left.extend_one(x);
2300 } else {
2301 right.extend_one(x);
2302 }
2303 }
2304 }
2305
2306 let mut left: B = Default::default();
2307 let mut right: B = Default::default();
2308
2309 self.fold((), extend(f, &mut left, &mut right));
2310
2311 (left, right)
2312 }
2313
2314 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2315 /// such that all those that return `true` precede all those that return `false`.
2316 /// Returns the number of `true` elements found.
2317 ///
2318 /// The relative order of partitioned items is not maintained.
2319 ///
2320 /// # Current implementation
2321 ///
2322 /// The current algorithm tries to find the first element for which the predicate evaluates
2323 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2324 ///
2325 /// Time complexity: *O*(*n*)
2326 ///
2327 /// See also [`is_partitioned()`] and [`partition()`].
2328 ///
2329 /// [`is_partitioned()`]: Iterator::is_partitioned
2330 /// [`partition()`]: Iterator::partition
2331 ///
2332 /// # Examples
2333 ///
2334 /// ```
2335 /// #![feature(iter_partition_in_place)]
2336 ///
2337 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2338 ///
2339 /// // Partition in-place between evens and odds
2340 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2341 ///
2342 /// assert_eq!(i, 3);
2343 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2344 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2345 /// ```
2346 #[unstable(feature = "iter_partition_in_place", issue = "62543")]
2347 #[rustc_non_const_trait_method]
2348 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2349 where
2350 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2351 P: FnMut(&T) -> bool,
2352 {
2353 // FIXME: should we worry about the count overflowing? The only way to have more than
2354 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2355
2356 // These closure "factory" functions exist to avoid genericity in `Self`.
2357
2358 #[inline]
2359 fn is_false<'a, T>(
2360 predicate: &'a mut impl FnMut(&T) -> bool,
2361 true_count: &'a mut usize,
2362 ) -> impl FnMut(&&mut T) -> bool + 'a {
2363 move |x| {
2364 let p = predicate(&**x);
2365 *true_count += p as usize;
2366 !p
2367 }
2368 }
2369
2370 #[inline]
2371 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2372 move |x| predicate(&**x)
2373 }
2374
2375 // Repeatedly find the first `false` and swap it with the last `true`.
2376 let mut true_count = 0;
2377 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2378 if let Some(tail) = self.rfind(is_true(predicate)) {
2379 crate::mem::swap(head, tail);
2380 true_count += 1;
2381 } else {
2382 break;
2383 }
2384 }
2385 true_count
2386 }
2387
2388 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2389 /// such that all those that return `true` precede all those that return `false`.
2390 ///
2391 /// See also [`partition()`] and [`partition_in_place()`].
2392 ///
2393 /// [`partition()`]: Iterator::partition
2394 /// [`partition_in_place()`]: Iterator::partition_in_place
2395 ///
2396 /// # Examples
2397 ///
2398 /// ```
2399 /// #![feature(iter_is_partitioned)]
2400 ///
2401 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2402 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2403 /// ```
2404 #[unstable(feature = "iter_is_partitioned", issue = "62544")]
2405 #[rustc_non_const_trait_method]
2406 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2407 where
2408 Self: Sized,
2409 P: FnMut(Self::Item) -> bool,
2410 {
2411 // Either all items test `true`, or the first clause stops at `false`
2412 // and we check that there are no more `true` items after that.
2413 self.all(&mut predicate) || !self.any(predicate)
2414 }
2415
2416 /// An iterator method that applies a function as long as it returns
2417 /// successfully, producing a single, final value.
2418 ///
2419 /// `try_fold()` takes two arguments: an initial value, and a closure with
2420 /// two arguments: an 'accumulator', and an element. The closure either
2421 /// returns successfully, with the value that the accumulator should have
2422 /// for the next iteration, or it returns failure, with an error value that
2423 /// is propagated back to the caller immediately (short-circuiting).
2424 ///
2425 /// The initial value is the value the accumulator will have on the first
2426 /// call. If applying the closure succeeded against every element of the
2427 /// iterator, `try_fold()` returns the final accumulator as success.
2428 ///
2429 /// Folding is useful whenever you have a collection of something, and want
2430 /// to produce a single value from it.
2431 ///
2432 /// # Note to Implementors
2433 ///
2434 /// Several of the other (forward) methods have default implementations in
2435 /// terms of this one, so try to implement this explicitly if it can
2436 /// do something better than the default `for` loop implementation.
2437 ///
2438 /// In particular, try to have this call `try_fold()` on the internal parts
2439 /// from which this iterator is composed. If multiple calls are needed,
2440 /// the `?` operator may be convenient for chaining the accumulator value
2441 /// along, but beware any invariants that need to be upheld before those
2442 /// early returns. This is a `&mut self` method, so iteration needs to be
2443 /// resumable after hitting an error here.
2444 ///
2445 /// # Examples
2446 ///
2447 /// Basic usage:
2448 ///
2449 /// ```
2450 /// let a = [1, 2, 3];
2451 ///
2452 /// // the checked sum of all of the elements of the array
2453 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2454 ///
2455 /// assert_eq!(sum, Some(6));
2456 /// ```
2457 ///
2458 /// Short-circuiting:
2459 ///
2460 /// ```
2461 /// let a = [10, 20, 30, 100, 40, 50];
2462 /// let mut iter = a.into_iter();
2463 ///
2464 /// // This sum overflows when adding the 100 element
2465 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2466 /// assert_eq!(sum, None);
2467 ///
2468 /// // Because it short-circuited, the remaining elements are still
2469 /// // available through the iterator.
2470 /// assert_eq!(iter.len(), 2);
2471 /// assert_eq!(iter.next(), Some(40));
2472 /// ```
2473 ///
2474 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2475 /// a similar idea:
2476 ///
2477 /// ```
2478 /// use std::ops::ControlFlow;
2479 ///
2480 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2481 /// if let Some(next) = prev.checked_add(x) {
2482 /// ControlFlow::Continue(next)
2483 /// } else {
2484 /// ControlFlow::Break(prev)
2485 /// }
2486 /// });
2487 /// assert_eq!(triangular, ControlFlow::Break(120));
2488 ///
2489 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2490 /// if let Some(next) = prev.checked_add(x) {
2491 /// ControlFlow::Continue(next)
2492 /// } else {
2493 /// ControlFlow::Break(prev)
2494 /// }
2495 /// });
2496 /// assert_eq!(triangular, ControlFlow::Continue(435));
2497 /// ```
2498 #[inline]
2499 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2500 #[rustc_non_const_trait_method]
2501 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2502 where
2503 Self: Sized,
2504 F: FnMut(B, Self::Item) -> R,
2505 R: Try<Output = B>,
2506 {
2507 let mut accum = init;
2508 while let Some(x) = self.next() {
2509 accum = f(accum, x)?;
2510 }
2511 try { accum }
2512 }
2513
2514 /// An iterator method that applies a fallible function to each item in the
2515 /// iterator, stopping at the first error and returning that error.
2516 ///
2517 /// This can also be thought of as the fallible form of [`for_each()`]
2518 /// or as the stateless version of [`try_fold()`].
2519 ///
2520 /// [`for_each()`]: Iterator::for_each
2521 /// [`try_fold()`]: Iterator::try_fold
2522 ///
2523 /// # Examples
2524 ///
2525 /// ```
2526 /// use std::fs::rename;
2527 /// use std::io::{stdout, Write};
2528 /// use std::path::Path;
2529 ///
2530 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2531 ///
2532 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2533 /// assert!(res.is_ok());
2534 ///
2535 /// let mut it = data.iter().cloned();
2536 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2537 /// assert!(res.is_err());
2538 /// // It short-circuited, so the remaining items are still in the iterator:
2539 /// assert_eq!(it.next(), Some("stale_bread.json"));
2540 /// ```
2541 ///
2542 /// The [`ControlFlow`] type can be used with this method for the situations
2543 /// in which you'd use `break` and `continue` in a normal loop:
2544 ///
2545 /// ```
2546 /// use std::ops::ControlFlow;
2547 ///
2548 /// let r = (2..100).try_for_each(|x| {
2549 /// if 323 % x == 0 {
2550 /// return ControlFlow::Break(x)
2551 /// }
2552 ///
2553 /// ControlFlow::Continue(())
2554 /// });
2555 /// assert_eq!(r, ControlFlow::Break(17));
2556 /// ```
2557 #[inline]
2558 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2559 #[rustc_non_const_trait_method]
2560 fn try_for_each<F, R>(&mut self, f: F) -> R
2561 where
2562 Self: Sized,
2563 F: FnMut(Self::Item) -> R,
2564 R: Try<Output = ()>,
2565 {
2566 #[inline]
2567 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2568 move |(), x| f(x)
2569 }
2570
2571 self.try_fold((), call(f))
2572 }
2573
2574 /// Folds every element into an accumulator by applying an operation,
2575 /// returning the final result.
2576 ///
2577 /// `fold()` takes two arguments: an initial value, and a closure with two
2578 /// arguments: an 'accumulator', and an element. The closure returns the value that
2579 /// the accumulator should have for the next iteration.
2580 ///
2581 /// The initial value is the value the accumulator will have on the first
2582 /// call.
2583 ///
2584 /// After applying this closure to every element of the iterator, `fold()`
2585 /// returns the accumulator.
2586 ///
2587 /// This operation is sometimes called 'reduce' or 'inject'.
2588 ///
2589 /// Folding is useful whenever you have a collection of something, and want
2590 /// to produce a single value from it.
2591 ///
2592 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2593 /// might not terminate for infinite iterators, even on traits for which a
2594 /// result is determinable in finite time.
2595 ///
2596 /// Note: [`reduce()`] can be used to use the first element as the initial
2597 /// value, if the accumulator type and item type is the same.
2598 ///
2599 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2600 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2601 /// operators like `-` the order will affect the final result.
2602 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2603 ///
2604 /// # Note to Implementors
2605 ///
2606 /// Several of the other (forward) methods have default implementations in
2607 /// terms of this one, so try to implement this explicitly if it can
2608 /// do something better than the default `for` loop implementation.
2609 ///
2610 /// In particular, try to have this call `fold()` on the internal parts
2611 /// from which this iterator is composed.
2612 ///
2613 /// # Examples
2614 ///
2615 /// Basic usage:
2616 ///
2617 /// ```
2618 /// let a = [1, 2, 3];
2619 ///
2620 /// // the sum of all of the elements of the array
2621 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2622 ///
2623 /// assert_eq!(sum, 6);
2624 /// ```
2625 ///
2626 /// Let's walk through each step of the iteration here:
2627 ///
2628 /// | element | acc | x | result |
2629 /// |---------|-----|---|--------|
2630 /// | | 0 | | |
2631 /// | 1 | 0 | 1 | 1 |
2632 /// | 2 | 1 | 2 | 3 |
2633 /// | 3 | 3 | 3 | 6 |
2634 ///
2635 /// And so, our final result, `6`.
2636 ///
2637 /// This example demonstrates the left-associative nature of `fold()`:
2638 /// it builds a string, starting with an initial value
2639 /// and continuing with each element from the front until the back:
2640 ///
2641 /// ```
2642 /// let numbers = [1, 2, 3, 4, 5];
2643 ///
2644 /// let zero = "0".to_string();
2645 ///
2646 /// let result = numbers.iter().fold(zero, |acc, &x| {
2647 /// format!("({acc} + {x})")
2648 /// });
2649 ///
2650 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2651 /// ```
2652 /// It's common for people who haven't used iterators a lot to
2653 /// use a `for` loop with a list of things to build up a result. Those
2654 /// can be turned into `fold()`s:
2655 ///
2656 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2657 ///
2658 /// ```
2659 /// let numbers = [1, 2, 3, 4, 5];
2660 ///
2661 /// let mut result = 0;
2662 ///
2663 /// // for loop:
2664 /// for i in &numbers {
2665 /// result = result + i;
2666 /// }
2667 ///
2668 /// // fold:
2669 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2670 ///
2671 /// // they're the same
2672 /// assert_eq!(result, result2);
2673 /// ```
2674 ///
2675 /// [`reduce()`]: Iterator::reduce
2676 #[doc(alias = "inject", alias = "foldl")]
2677 #[inline]
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 #[rustc_non_const_trait_method]
2680 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2681 where
2682 Self: Sized,
2683 F: FnMut(B, Self::Item) -> B,
2684 {
2685 let mut accum = init;
2686 while let Some(x) = self.next() {
2687 accum = f(accum, x);
2688 }
2689 accum
2690 }
2691
2692 /// Reduces the elements to a single one, by repeatedly applying a reducing
2693 /// operation.
2694 ///
2695 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2696 /// result of the reduction.
2697 ///
2698 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2699 /// For iterators with at least one element, this is the same as [`fold()`]
2700 /// with the first element of the iterator as the initial accumulator value, folding
2701 /// every subsequent element into it.
2702 ///
2703 /// [`fold()`]: Iterator::fold
2704 ///
2705 /// # Example
2706 ///
2707 /// ```
2708 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2709 /// assert_eq!(reduced, 45);
2710 ///
2711 /// // Which is equivalent to doing it with `fold`:
2712 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2713 /// assert_eq!(reduced, folded);
2714 /// ```
2715 #[inline]
2716 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2717 #[rustc_non_const_trait_method]
2718 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2719 where
2720 Self: Sized,
2721 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2722 {
2723 let first = self.next()?;
2724 Some(self.fold(first, f))
2725 }
2726
2727 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2728 /// closure returns a failure, the failure is propagated back to the caller immediately.
2729 ///
2730 /// The return type of this method depends on the return type of the closure. If the closure
2731 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2732 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2733 /// `Option<Option<Self::Item>>`.
2734 ///
2735 /// When called on an empty iterator, this function will return either `Some(None)` or
2736 /// `Ok(None)` depending on the type of the provided closure.
2737 ///
2738 /// For iterators with at least one element, this is essentially the same as calling
2739 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2740 ///
2741 /// [`try_fold()`]: Iterator::try_fold
2742 ///
2743 /// # Examples
2744 ///
2745 /// Safely calculate the sum of a series of numbers:
2746 ///
2747 /// ```
2748 /// #![feature(iterator_try_reduce)]
2749 ///
2750 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2751 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2752 /// assert_eq!(sum, Some(Some(58)));
2753 /// ```
2754 ///
2755 /// Determine when a reduction short circuited:
2756 ///
2757 /// ```
2758 /// #![feature(iterator_try_reduce)]
2759 ///
2760 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2761 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2762 /// assert_eq!(sum, None);
2763 /// ```
2764 ///
2765 /// Determine when a reduction was not performed because there are no elements:
2766 ///
2767 /// ```
2768 /// #![feature(iterator_try_reduce)]
2769 ///
2770 /// let numbers: Vec<usize> = Vec::new();
2771 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2772 /// assert_eq!(sum, Some(None));
2773 /// ```
2774 ///
2775 /// Use a [`Result`] instead of an [`Option`]:
2776 ///
2777 /// ```
2778 /// #![feature(iterator_try_reduce)]
2779 ///
2780 /// let numbers = vec!["1", "2", "3", "4", "5"];
2781 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2782 /// numbers.into_iter().try_reduce(|x, y| {
2783 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2784 /// });
2785 /// assert_eq!(max, Ok(Some("5")));
2786 /// ```
2787 #[inline]
2788 #[unstable(feature = "iterator_try_reduce", issue = "87053")]
2789 #[rustc_non_const_trait_method]
2790 fn try_reduce<R>(
2791 &mut self,
2792 f: impl FnMut(Self::Item, Self::Item) -> R,
2793 ) -> ChangeOutputType<R, Option<R::Output>>
2794 where
2795 Self: Sized,
2796 R: Try<Output = Self::Item, Residual: Residual<Option<Self::Item>>>,
2797 {
2798 let first = match self.next() {
2799 Some(i) => i,
2800 None => return Try::from_output(None),
2801 };
2802
2803 match self.try_fold(first, f).branch() {
2804 ControlFlow::Break(r) => FromResidual::from_residual(r),
2805 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2806 }
2807 }
2808
2809 /// Tests if every element of the iterator matches a predicate.
2810 ///
2811 /// `all()` takes a closure that returns `true` or `false`. It applies
2812 /// this closure to each element of the iterator, and if they all return
2813 /// `true`, then so does `all()`. If any of them return `false`, it
2814 /// returns `false`.
2815 ///
2816 /// `all()` is short-circuiting; in other words, it will stop processing
2817 /// as soon as it finds a `false`, given that no matter what else happens,
2818 /// the result will also be `false`.
2819 ///
2820 /// An empty iterator returns `true`.
2821 ///
2822 /// # Examples
2823 ///
2824 /// Basic usage:
2825 ///
2826 /// ```
2827 /// let a = [1, 2, 3];
2828 ///
2829 /// assert!(a.into_iter().all(|x| x > 0));
2830 ///
2831 /// assert!(!a.into_iter().all(|x| x > 2));
2832 /// ```
2833 ///
2834 /// Stopping at the first `false`:
2835 ///
2836 /// ```
2837 /// let a = [1, 2, 3];
2838 ///
2839 /// let mut iter = a.into_iter();
2840 ///
2841 /// assert!(!iter.all(|x| x != 2));
2842 ///
2843 /// // we can still use `iter`, as there are more elements.
2844 /// assert_eq!(iter.next(), Some(3));
2845 /// ```
2846 #[inline]
2847 #[stable(feature = "rust1", since = "1.0.0")]
2848 #[rustc_non_const_trait_method]
2849 fn all<F>(&mut self, f: F) -> bool
2850 where
2851 Self: Sized,
2852 F: FnMut(Self::Item) -> bool,
2853 {
2854 #[inline]
2855 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2856 move |(), x| {
2857 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2858 }
2859 }
2860 self.try_fold((), check(f)) == ControlFlow::Continue(())
2861 }
2862
2863 /// Tests if any element of the iterator matches a predicate.
2864 ///
2865 /// `any()` takes a closure that returns `true` or `false`. It applies
2866 /// this closure to each element of the iterator, and if any of them return
2867 /// `true`, then so does `any()`. If they all return `false`, it
2868 /// returns `false`.
2869 ///
2870 /// `any()` is short-circuiting; in other words, it will stop processing
2871 /// as soon as it finds a `true`, given that no matter what else happens,
2872 /// the result will also be `true`.
2873 ///
2874 /// An empty iterator returns `false`.
2875 ///
2876 /// # Examples
2877 ///
2878 /// Basic usage:
2879 ///
2880 /// ```
2881 /// let a = [1, 2, 3];
2882 ///
2883 /// assert!(a.into_iter().any(|x| x > 0));
2884 ///
2885 /// assert!(!a.into_iter().any(|x| x > 5));
2886 /// ```
2887 ///
2888 /// Stopping at the first `true`:
2889 ///
2890 /// ```
2891 /// let a = [1, 2, 3];
2892 ///
2893 /// let mut iter = a.into_iter();
2894 ///
2895 /// assert!(iter.any(|x| x != 2));
2896 ///
2897 /// // we can still use `iter`, as there are more elements.
2898 /// assert_eq!(iter.next(), Some(2));
2899 /// ```
2900 #[inline]
2901 #[stable(feature = "rust1", since = "1.0.0")]
2902 #[rustc_non_const_trait_method]
2903 fn any<F>(&mut self, f: F) -> bool
2904 where
2905 Self: Sized,
2906 F: FnMut(Self::Item) -> bool,
2907 {
2908 #[inline]
2909 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2910 move |(), x| {
2911 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2912 }
2913 }
2914
2915 self.try_fold((), check(f)) == ControlFlow::Break(())
2916 }
2917
2918 /// Searches for an element of an iterator that satisfies a predicate.
2919 ///
2920 /// `find()` takes a closure that returns `true` or `false`. It applies
2921 /// this closure to each element of the iterator, and if any of them return
2922 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2923 /// `false`, it returns [`None`].
2924 ///
2925 /// `find()` is short-circuiting; in other words, it will stop processing
2926 /// as soon as the closure returns `true`.
2927 ///
2928 /// Because `find()` takes a reference, and many iterators iterate over
2929 /// references, this leads to a possibly confusing situation where the
2930 /// argument is a double reference. You can see this effect in the
2931 /// examples below, with `&&x`.
2932 ///
2933 /// If you need the index of the element, see [`position()`].
2934 ///
2935 /// [`Some(element)`]: Some
2936 /// [`position()`]: Iterator::position
2937 ///
2938 /// # Examples
2939 ///
2940 /// Basic usage:
2941 ///
2942 /// ```
2943 /// let a = [1, 2, 3];
2944 ///
2945 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2946 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2947 /// ```
2948 ///
2949 /// Iterating over references:
2950 ///
2951 /// ```
2952 /// let a = [1, 2, 3];
2953 ///
2954 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2955 /// // reference to each element.
2956 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2957 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2958 /// ```
2959 ///
2960 /// Stopping at the first `true`:
2961 ///
2962 /// ```
2963 /// let a = [1, 2, 3];
2964 ///
2965 /// let mut iter = a.into_iter();
2966 ///
2967 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2968 ///
2969 /// // we can still use `iter`, as there are more elements.
2970 /// assert_eq!(iter.next(), Some(3));
2971 /// ```
2972 ///
2973 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2974 #[inline]
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 #[rustc_non_const_trait_method]
2977 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2978 where
2979 Self: Sized,
2980 P: FnMut(&Self::Item) -> bool,
2981 {
2982 #[inline]
2983 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2984 move |(), x| {
2985 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2986 }
2987 }
2988
2989 self.try_fold((), check(predicate)).break_value()
2990 }
2991
2992 /// Applies function to the elements of iterator and returns
2993 /// the first non-none result.
2994 ///
2995 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2996 ///
2997 /// # Examples
2998 ///
2999 /// ```
3000 /// let a = ["lol", "NaN", "2", "5"];
3001 ///
3002 /// let first_number = a.iter().find_map(|s| s.parse().ok());
3003 ///
3004 /// assert_eq!(first_number, Some(2));
3005 /// ```
3006 #[inline]
3007 #[stable(feature = "iterator_find_map", since = "1.30.0")]
3008 #[rustc_non_const_trait_method]
3009 fn find_map<B, F>(&mut self, f: F) -> Option<B>
3010 where
3011 Self: Sized,
3012 F: FnMut(Self::Item) -> Option<B>,
3013 {
3014 #[inline]
3015 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
3016 move |(), x| match f(x) {
3017 Some(x) => ControlFlow::Break(x),
3018 None => ControlFlow::Continue(()),
3019 }
3020 }
3021
3022 self.try_fold((), check(f)).break_value()
3023 }
3024
3025 /// Applies function to the elements of iterator and returns
3026 /// the first true result or the first error.
3027 ///
3028 /// The return type of this method depends on the return type of the closure.
3029 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
3030 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
3031 ///
3032 /// # Examples
3033 ///
3034 /// ```
3035 /// #![feature(try_find)]
3036 ///
3037 /// let a = ["1", "2", "lol", "NaN", "5"];
3038 ///
3039 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
3040 /// Ok(s.parse::<i32>()? == search)
3041 /// };
3042 ///
3043 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
3044 /// assert_eq!(result, Ok(Some("2")));
3045 ///
3046 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
3047 /// assert!(result.is_err());
3048 /// ```
3049 ///
3050 /// This also supports other types which implement [`Try`], not just [`Result`].
3051 ///
3052 /// ```
3053 /// #![feature(try_find)]
3054 ///
3055 /// use std::num::NonZero;
3056 ///
3057 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
3058 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3059 /// assert_eq!(result, Some(Some(4)));
3060 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3061 /// assert_eq!(result, Some(None));
3062 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3063 /// assert_eq!(result, None);
3064 /// ```
3065 #[inline]
3066 #[unstable(feature = "try_find", issue = "63178")]
3067 #[rustc_non_const_trait_method]
3068 fn try_find<R>(
3069 &mut self,
3070 f: impl FnMut(&Self::Item) -> R,
3071 ) -> ChangeOutputType<R, Option<Self::Item>>
3072 where
3073 Self: Sized,
3074 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3075 {
3076 #[inline]
3077 fn check<I, V, R>(
3078 mut f: impl FnMut(&I) -> V,
3079 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3080 where
3081 V: Try<Output = bool, Residual = R>,
3082 R: Residual<Option<I>>,
3083 {
3084 move |(), x| match f(&x).branch() {
3085 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3086 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3087 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3088 }
3089 }
3090
3091 match self.try_fold((), check(f)) {
3092 ControlFlow::Break(x) => x,
3093 ControlFlow::Continue(()) => Try::from_output(None),
3094 }
3095 }
3096
3097 /// Searches for an element in an iterator, returning its index.
3098 ///
3099 /// `position()` takes a closure that returns `true` or `false`. It applies
3100 /// this closure to each element of the iterator, and if one of them
3101 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3102 /// them return `false`, it returns [`None`].
3103 ///
3104 /// `position()` is short-circuiting; in other words, it will stop
3105 /// processing as soon as it finds a `true`.
3106 ///
3107 /// # Overflow Behavior
3108 ///
3109 /// The method does no guarding against overflows, so if there are more
3110 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3111 /// result or panics. If overflow checks are enabled, a panic is
3112 /// guaranteed.
3113 ///
3114 /// # Panics
3115 ///
3116 /// This function might panic if the iterator has more than `usize::MAX`
3117 /// non-matching elements.
3118 ///
3119 /// [`Some(index)`]: Some
3120 ///
3121 /// # Examples
3122 ///
3123 /// Basic usage:
3124 ///
3125 /// ```
3126 /// let a = [1, 2, 3];
3127 ///
3128 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3129 ///
3130 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3131 /// ```
3132 ///
3133 /// Stopping at the first `true`:
3134 ///
3135 /// ```
3136 /// let a = [1, 2, 3, 4];
3137 ///
3138 /// let mut iter = a.into_iter();
3139 ///
3140 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3141 ///
3142 /// // we can still use `iter`, as there are more elements.
3143 /// assert_eq!(iter.next(), Some(3));
3144 ///
3145 /// // The returned index depends on iterator state
3146 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3147 ///
3148 /// ```
3149 #[inline]
3150 #[stable(feature = "rust1", since = "1.0.0")]
3151 #[rustc_non_const_trait_method]
3152 fn position<P>(&mut self, predicate: P) -> Option<usize>
3153 where
3154 Self: Sized,
3155 P: FnMut(Self::Item) -> bool,
3156 {
3157 #[inline]
3158 fn check<'a, T>(
3159 mut predicate: impl FnMut(T) -> bool + 'a,
3160 acc: &'a mut usize,
3161 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3162 #[rustc_inherit_overflow_checks]
3163 move |_, x| {
3164 if predicate(x) {
3165 ControlFlow::Break(*acc)
3166 } else {
3167 *acc += 1;
3168 ControlFlow::Continue(())
3169 }
3170 }
3171 }
3172
3173 let mut acc = 0;
3174 self.try_fold((), check(predicate, &mut acc)).break_value()
3175 }
3176
3177 /// Searches for an element in an iterator from the right, returning its
3178 /// index.
3179 ///
3180 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3181 /// this closure to each element of the iterator, starting from the end,
3182 /// and if one of them returns `true`, then `rposition()` returns
3183 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3184 ///
3185 /// `rposition()` is short-circuiting; in other words, it will stop
3186 /// processing as soon as it finds a `true`.
3187 ///
3188 /// [`Some(index)`]: Some
3189 ///
3190 /// # Examples
3191 ///
3192 /// Basic usage:
3193 ///
3194 /// ```
3195 /// let a = [1, 2, 3];
3196 ///
3197 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3198 ///
3199 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3200 /// ```
3201 ///
3202 /// Stopping at the first `true`:
3203 ///
3204 /// ```
3205 /// let a = [-1, 2, 3, 4];
3206 ///
3207 /// let mut iter = a.into_iter();
3208 ///
3209 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3210 ///
3211 /// // we can still use `iter`, as there are more elements.
3212 /// assert_eq!(iter.next(), Some(-1));
3213 /// assert_eq!(iter.next_back(), Some(3));
3214 /// ```
3215 #[inline]
3216 #[stable(feature = "rust1", since = "1.0.0")]
3217 #[rustc_non_const_trait_method]
3218 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3219 where
3220 P: FnMut(Self::Item) -> bool,
3221 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3222 {
3223 // No need for an overflow check here, because `ExactSizeIterator`
3224 // implies that the number of elements fits into a `usize`.
3225 #[inline]
3226 fn check<T>(
3227 mut predicate: impl FnMut(T) -> bool,
3228 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3229 move |i, x| {
3230 let i = i - 1;
3231 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3232 }
3233 }
3234
3235 let n = self.len();
3236 self.try_rfold(n, check(predicate)).break_value()
3237 }
3238
3239 /// Returns the maximum element of an iterator.
3240 ///
3241 /// If several elements are equally maximum, the last element is
3242 /// returned. If the iterator is empty, [`None`] is returned.
3243 ///
3244 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3245 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3246 /// ```
3247 /// assert_eq!(
3248 /// [2.4, f32::NAN, 1.3]
3249 /// .into_iter()
3250 /// .reduce(f32::max)
3251 /// .unwrap_or(0.),
3252 /// 2.4
3253 /// );
3254 /// ```
3255 ///
3256 /// # Examples
3257 ///
3258 /// ```
3259 /// let a = [1, 2, 3];
3260 /// let b: [u32; 0] = [];
3261 ///
3262 /// assert_eq!(a.into_iter().max(), Some(3));
3263 /// assert_eq!(b.into_iter().max(), None);
3264 /// ```
3265 #[inline]
3266 #[stable(feature = "rust1", since = "1.0.0")]
3267 #[rustc_non_const_trait_method]
3268 fn max(self) -> Option<Self::Item>
3269 where
3270 Self: Sized,
3271 Self::Item: Ord,
3272 {
3273 self.max_by(Ord::cmp)
3274 }
3275
3276 /// Returns the minimum element of an iterator.
3277 ///
3278 /// If several elements are equally minimum, the first element is returned.
3279 /// If the iterator is empty, [`None`] is returned.
3280 ///
3281 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3282 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3283 /// ```
3284 /// assert_eq!(
3285 /// [2.4, f32::NAN, 1.3]
3286 /// .into_iter()
3287 /// .reduce(f32::min)
3288 /// .unwrap_or(0.),
3289 /// 1.3
3290 /// );
3291 /// ```
3292 ///
3293 /// # Examples
3294 ///
3295 /// ```
3296 /// let a = [1, 2, 3];
3297 /// let b: [u32; 0] = [];
3298 ///
3299 /// assert_eq!(a.into_iter().min(), Some(1));
3300 /// assert_eq!(b.into_iter().min(), None);
3301 /// ```
3302 #[inline]
3303 #[stable(feature = "rust1", since = "1.0.0")]
3304 #[rustc_non_const_trait_method]
3305 fn min(self) -> Option<Self::Item>
3306 where
3307 Self: Sized,
3308 Self::Item: Ord,
3309 {
3310 self.min_by(Ord::cmp)
3311 }
3312
3313 /// Returns the element that gives the maximum value from the
3314 /// specified function.
3315 ///
3316 /// If several elements are equally maximum, the last element is
3317 /// returned. If the iterator is empty, [`None`] is returned.
3318 ///
3319 /// # Examples
3320 ///
3321 /// ```
3322 /// let a = [-3_i32, 0, 1, 5, -10];
3323 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3324 /// ```
3325 #[inline]
3326 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3327 #[rustc_non_const_trait_method]
3328 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3329 where
3330 Self: Sized,
3331 F: FnMut(&Self::Item) -> B,
3332 {
3333 #[inline]
3334 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3335 move |x| (f(&x), x)
3336 }
3337
3338 #[inline]
3339 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3340 x_p.cmp(y_p)
3341 }
3342
3343 let (_, x) = self.map(key(f)).max_by(compare)?;
3344 Some(x)
3345 }
3346
3347 /// Returns the element that gives the maximum value with respect to the
3348 /// specified comparison function.
3349 ///
3350 /// If several elements are equally maximum, the last element is
3351 /// returned. If the iterator is empty, [`None`] is returned.
3352 ///
3353 /// # Examples
3354 ///
3355 /// ```
3356 /// let a = [-3_i32, 0, 1, 5, -10];
3357 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3358 /// ```
3359 #[inline]
3360 #[stable(feature = "iter_max_by", since = "1.15.0")]
3361 #[rustc_non_const_trait_method]
3362 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3363 where
3364 Self: Sized,
3365 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3366 {
3367 #[inline]
3368 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3369 move |x, y| cmp::max_by(x, y, &mut compare)
3370 }
3371
3372 self.reduce(fold(compare))
3373 }
3374
3375 /// Returns the element that gives the minimum value from the
3376 /// specified function.
3377 ///
3378 /// If several elements are equally minimum, the first element is
3379 /// returned. If the iterator is empty, [`None`] is returned.
3380 ///
3381 /// # Examples
3382 ///
3383 /// ```
3384 /// let a = [-3_i32, 0, 1, 5, -10];
3385 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3386 /// ```
3387 #[inline]
3388 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3389 #[rustc_non_const_trait_method]
3390 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3391 where
3392 Self: Sized,
3393 F: FnMut(&Self::Item) -> B,
3394 {
3395 #[inline]
3396 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3397 move |x| (f(&x), x)
3398 }
3399
3400 #[inline]
3401 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3402 x_p.cmp(y_p)
3403 }
3404
3405 let (_, x) = self.map(key(f)).min_by(compare)?;
3406 Some(x)
3407 }
3408
3409 /// Returns the element that gives the minimum value with respect to the
3410 /// specified comparison function.
3411 ///
3412 /// If several elements are equally minimum, the first element is
3413 /// returned. If the iterator is empty, [`None`] is returned.
3414 ///
3415 /// # Examples
3416 ///
3417 /// ```
3418 /// let a = [-3_i32, 0, 1, 5, -10];
3419 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3420 /// ```
3421 #[inline]
3422 #[stable(feature = "iter_min_by", since = "1.15.0")]
3423 #[rustc_non_const_trait_method]
3424 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3425 where
3426 Self: Sized,
3427 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3428 {
3429 #[inline]
3430 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3431 move |x, y| cmp::min_by(x, y, &mut compare)
3432 }
3433
3434 self.reduce(fold(compare))
3435 }
3436
3437 /// Reverses an iterator's direction.
3438 ///
3439 /// Usually, iterators iterate from left to right. After using `rev()`,
3440 /// an iterator will instead iterate from right to left.
3441 ///
3442 /// This is only possible if the iterator has an end, so `rev()` only
3443 /// works on [`DoubleEndedIterator`]s.
3444 ///
3445 /// # Examples
3446 ///
3447 /// ```
3448 /// let a = [1, 2, 3];
3449 ///
3450 /// let mut iter = a.into_iter().rev();
3451 ///
3452 /// assert_eq!(iter.next(), Some(3));
3453 /// assert_eq!(iter.next(), Some(2));
3454 /// assert_eq!(iter.next(), Some(1));
3455 ///
3456 /// assert_eq!(iter.next(), None);
3457 /// ```
3458 #[inline]
3459 #[doc(alias = "reverse")]
3460 #[stable(feature = "rust1", since = "1.0.0")]
3461 #[rustc_non_const_trait_method]
3462 fn rev(self) -> Rev<Self>
3463 where
3464 Self: Sized + DoubleEndedIterator,
3465 {
3466 Rev::new(self)
3467 }
3468
3469 /// Converts an iterator of pairs into a pair of containers.
3470 ///
3471 /// `unzip()` consumes an entire iterator of pairs, producing two
3472 /// collections: one from the left elements of the pairs, and one
3473 /// from the right elements.
3474 ///
3475 /// This function is, in some sense, the opposite of [`zip`].
3476 ///
3477 /// [`zip`]: Iterator::zip
3478 ///
3479 /// # Examples
3480 ///
3481 /// ```
3482 /// let a = [(1, 2), (3, 4), (5, 6)];
3483 ///
3484 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3485 ///
3486 /// assert_eq!(left, [1, 3, 5]);
3487 /// assert_eq!(right, [2, 4, 6]);
3488 ///
3489 /// // you can also unzip multiple nested tuples at once
3490 /// let a = [(1, (2, 3)), (4, (5, 6))];
3491 ///
3492 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3493 /// assert_eq!(x, [1, 4]);
3494 /// assert_eq!(y, [2, 5]);
3495 /// assert_eq!(z, [3, 6]);
3496 /// ```
3497 #[stable(feature = "rust1", since = "1.0.0")]
3498 #[rustc_non_const_trait_method]
3499 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3500 where
3501 FromA: Default + Extend<A>,
3502 FromB: Default + Extend<B>,
3503 Self: Sized + Iterator<Item = (A, B)>,
3504 {
3505 let mut unzipped: (FromA, FromB) = Default::default();
3506 unzipped.extend(self);
3507 unzipped
3508 }
3509
3510 /// Creates an iterator which copies all of its elements.
3511 ///
3512 /// This is useful when you have an iterator over `&T`, but you need an
3513 /// iterator over `T`.
3514 ///
3515 /// # Examples
3516 ///
3517 /// ```
3518 /// let a = [1, 2, 3];
3519 ///
3520 /// let v_copied: Vec<_> = a.iter().copied().collect();
3521 ///
3522 /// // copied is the same as .map(|&x| x)
3523 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3524 ///
3525 /// assert_eq!(v_copied, [1, 2, 3]);
3526 /// assert_eq!(v_map, [1, 2, 3]);
3527 /// ```
3528 #[stable(feature = "iter_copied", since = "1.36.0")]
3529 #[rustc_diagnostic_item = "iter_copied"]
3530 #[rustc_non_const_trait_method]
3531 fn copied<'a, T>(self) -> Copied<Self>
3532 where
3533 T: Copy + 'a,
3534 Self: Sized + Iterator<Item = &'a T>,
3535 {
3536 Copied::new(self)
3537 }
3538
3539 /// Creates an iterator which [`clone`]s all of its elements.
3540 ///
3541 /// This is useful when you have an iterator over `&T`, but you need an
3542 /// iterator over `T`.
3543 ///
3544 /// There is no guarantee whatsoever about the `clone` method actually
3545 /// being called *or* optimized away. So code should not depend on
3546 /// either.
3547 ///
3548 /// [`clone`]: Clone::clone
3549 ///
3550 /// # Examples
3551 ///
3552 /// Basic usage:
3553 ///
3554 /// ```
3555 /// let a = [1, 2, 3];
3556 ///
3557 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3558 ///
3559 /// // cloned is the same as .map(|&x| x), for integers
3560 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3561 ///
3562 /// assert_eq!(v_cloned, [1, 2, 3]);
3563 /// assert_eq!(v_map, [1, 2, 3]);
3564 /// ```
3565 ///
3566 /// To get the best performance, try to clone late:
3567 ///
3568 /// ```
3569 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3570 /// // don't do this:
3571 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3572 /// assert_eq!(&[vec![23]], &slower[..]);
3573 /// // instead call `cloned` late
3574 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3575 /// assert_eq!(&[vec![23]], &faster[..]);
3576 /// ```
3577 #[stable(feature = "rust1", since = "1.0.0")]
3578 #[rustc_diagnostic_item = "iter_cloned"]
3579 #[rustc_non_const_trait_method]
3580 fn cloned<'a, T>(self) -> Cloned<Self>
3581 where
3582 T: Clone + 'a,
3583 Self: Sized + Iterator<Item = &'a T>,
3584 {
3585 Cloned::new(self)
3586 }
3587
3588 /// Repeats an iterator endlessly.
3589 ///
3590 /// Instead of stopping at [`None`], the iterator will instead start again,
3591 /// from the beginning. After iterating again, it will start at the
3592 /// beginning again. And again. And again. Forever. Note that in case the
3593 /// original iterator is empty, the resulting iterator will also be empty.
3594 ///
3595 /// # Examples
3596 ///
3597 /// ```
3598 /// let a = [1, 2, 3];
3599 ///
3600 /// let mut iter = a.into_iter().cycle();
3601 ///
3602 /// loop {
3603 /// assert_eq!(iter.next(), Some(1));
3604 /// assert_eq!(iter.next(), Some(2));
3605 /// assert_eq!(iter.next(), Some(3));
3606 /// # break;
3607 /// }
3608 /// ```
3609 #[stable(feature = "rust1", since = "1.0.0")]
3610 #[inline]
3611 #[rustc_non_const_trait_method]
3612 fn cycle(self) -> Cycle<Self>
3613 where
3614 Self: Sized + Clone,
3615 {
3616 Cycle::new(self)
3617 }
3618
3619 /// Returns an iterator over `N` elements of the iterator at a time.
3620 ///
3621 /// The chunks do not overlap. If `N` does not divide the length of the
3622 /// iterator, then the last up to `N-1` elements will be omitted and can be
3623 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3624 /// function of the iterator.
3625 ///
3626 /// # Panics
3627 ///
3628 /// Panics if `N` is zero.
3629 ///
3630 /// # Examples
3631 ///
3632 /// Basic usage:
3633 ///
3634 /// ```
3635 /// #![feature(iter_array_chunks)]
3636 ///
3637 /// let mut iter = "lorem".chars().array_chunks();
3638 /// assert_eq!(iter.next(), Some(['l', 'o']));
3639 /// assert_eq!(iter.next(), Some(['r', 'e']));
3640 /// assert_eq!(iter.next(), None);
3641 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3642 /// ```
3643 ///
3644 /// ```
3645 /// #![feature(iter_array_chunks)]
3646 ///
3647 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3648 /// // ^-----^ ^------^
3649 /// for [x, y, z] in data.iter().array_chunks() {
3650 /// assert_eq!(x + y + z, 4);
3651 /// }
3652 /// ```
3653 #[track_caller]
3654 #[unstable(feature = "iter_array_chunks", issue = "100450")]
3655 #[rustc_non_const_trait_method]
3656 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3657 where
3658 Self: Sized,
3659 {
3660 ArrayChunks::new(self)
3661 }
3662
3663 /// Sums the elements of an iterator.
3664 ///
3665 /// Takes each element, adds them together, and returns the result.
3666 ///
3667 /// An empty iterator returns the *additive identity* ("zero") of the type,
3668 /// which is `0` for integers and `-0.0` for floats.
3669 ///
3670 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3671 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3672 ///
3673 /// # Panics
3674 ///
3675 /// When calling `sum()` and a primitive integer type is being returned, this
3676 /// method will panic if the computation overflows and overflow checks are
3677 /// enabled.
3678 ///
3679 /// # Examples
3680 ///
3681 /// ```
3682 /// let a = [1, 2, 3];
3683 /// let sum: i32 = a.iter().sum();
3684 ///
3685 /// assert_eq!(sum, 6);
3686 ///
3687 /// let b: Vec<f32> = vec![];
3688 /// let sum: f32 = b.iter().sum();
3689 /// assert_eq!(sum, -0.0_f32);
3690 /// ```
3691 #[stable(feature = "iter_arith", since = "1.11.0")]
3692 #[rustc_non_const_trait_method]
3693 fn sum<S>(self) -> S
3694 where
3695 Self: Sized,
3696 S: Sum<Self::Item>,
3697 {
3698 Sum::sum(self)
3699 }
3700
3701 /// Iterates over the entire iterator, multiplying all the elements
3702 ///
3703 /// An empty iterator returns the one value of the type.
3704 ///
3705 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3706 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3707 ///
3708 /// # Panics
3709 ///
3710 /// When calling `product()` and a primitive integer type is being returned,
3711 /// method will panic if the computation overflows and overflow checks are
3712 /// enabled.
3713 ///
3714 /// # Examples
3715 ///
3716 /// ```
3717 /// fn factorial(n: u32) -> u32 {
3718 /// (1..=n).product()
3719 /// }
3720 /// assert_eq!(factorial(0), 1);
3721 /// assert_eq!(factorial(1), 1);
3722 /// assert_eq!(factorial(5), 120);
3723 /// ```
3724 #[stable(feature = "iter_arith", since = "1.11.0")]
3725 #[rustc_non_const_trait_method]
3726 fn product<P>(self) -> P
3727 where
3728 Self: Sized,
3729 P: Product<Self::Item>,
3730 {
3731 Product::product(self)
3732 }
3733
3734 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3735 /// of another.
3736 ///
3737 /// # Examples
3738 ///
3739 /// ```
3740 /// use std::cmp::Ordering;
3741 ///
3742 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3743 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3744 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3745 /// ```
3746 #[stable(feature = "iter_order", since = "1.5.0")]
3747 #[rustc_non_const_trait_method]
3748 fn cmp<I>(self, other: I) -> Ordering
3749 where
3750 I: IntoIterator<Item = Self::Item>,
3751 Self::Item: Ord,
3752 Self: Sized,
3753 {
3754 self.cmp_by(other, |x, y| x.cmp(&y))
3755 }
3756
3757 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3758 /// of another with respect to the specified comparison function.
3759 ///
3760 /// # Examples
3761 ///
3762 /// ```
3763 /// #![feature(iter_order_by)]
3764 ///
3765 /// use std::cmp::Ordering;
3766 ///
3767 /// let xs = [1, 2, 3, 4];
3768 /// let ys = [1, 4, 9, 16];
3769 ///
3770 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3771 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3772 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3773 /// ```
3774 #[unstable(feature = "iter_order_by", issue = "64295")]
3775 #[rustc_non_const_trait_method]
3776 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3777 where
3778 Self: Sized,
3779 I: IntoIterator,
3780 F: FnMut(Self::Item, I::Item) -> Ordering,
3781 {
3782 #[inline]
3783 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3784 where
3785 F: FnMut(X, Y) -> Ordering,
3786 {
3787 move |x, y| match cmp(x, y) {
3788 Ordering::Equal => ControlFlow::Continue(()),
3789 non_eq => ControlFlow::Break(non_eq),
3790 }
3791 }
3792
3793 match iter_compare(self, other.into_iter(), compare(cmp)) {
3794 ControlFlow::Continue(ord) => ord,
3795 ControlFlow::Break(ord) => ord,
3796 }
3797 }
3798
3799 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3800 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3801 /// evaluation, returning a result without comparing the remaining elements.
3802 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3803 ///
3804 /// # Examples
3805 ///
3806 /// ```
3807 /// use std::cmp::Ordering;
3808 ///
3809 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3810 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3811 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3812 /// ```
3813 ///
3814 /// For floating-point numbers, NaN does not have a total order and will result
3815 /// in `None` when compared:
3816 ///
3817 /// ```
3818 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3819 /// ```
3820 ///
3821 /// The results are determined by the order of evaluation.
3822 ///
3823 /// ```
3824 /// use std::cmp::Ordering;
3825 ///
3826 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3827 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3828 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3829 /// ```
3830 ///
3831 #[stable(feature = "iter_order", since = "1.5.0")]
3832 #[rustc_non_const_trait_method]
3833 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3834 where
3835 I: IntoIterator,
3836 Self::Item: PartialOrd<I::Item>,
3837 Self: Sized,
3838 {
3839 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3840 }
3841
3842 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3843 /// of another with respect to the specified comparison function.
3844 ///
3845 /// # Examples
3846 ///
3847 /// ```
3848 /// #![feature(iter_order_by)]
3849 ///
3850 /// use std::cmp::Ordering;
3851 ///
3852 /// let xs = [1.0, 2.0, 3.0, 4.0];
3853 /// let ys = [1.0, 4.0, 9.0, 16.0];
3854 ///
3855 /// assert_eq!(
3856 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3857 /// Some(Ordering::Less)
3858 /// );
3859 /// assert_eq!(
3860 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3861 /// Some(Ordering::Equal)
3862 /// );
3863 /// assert_eq!(
3864 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3865 /// Some(Ordering::Greater)
3866 /// );
3867 /// ```
3868 #[unstable(feature = "iter_order_by", issue = "64295")]
3869 #[rustc_non_const_trait_method]
3870 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3871 where
3872 Self: Sized,
3873 I: IntoIterator,
3874 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3875 {
3876 #[inline]
3877 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3878 where
3879 F: FnMut(X, Y) -> Option<Ordering>,
3880 {
3881 move |x, y| match partial_cmp(x, y) {
3882 Some(Ordering::Equal) => ControlFlow::Continue(()),
3883 non_eq => ControlFlow::Break(non_eq),
3884 }
3885 }
3886
3887 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3888 ControlFlow::Continue(ord) => Some(ord),
3889 ControlFlow::Break(ord) => ord,
3890 }
3891 }
3892
3893 /// Determines if the elements of this [`Iterator`] are equal to those of
3894 /// another.
3895 ///
3896 /// # Examples
3897 ///
3898 /// ```
3899 /// assert_eq!([1].iter().eq([1].iter()), true);
3900 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3901 /// ```
3902 #[stable(feature = "iter_order", since = "1.5.0")]
3903 #[rustc_non_const_trait_method]
3904 fn eq<I>(self, other: I) -> bool
3905 where
3906 I: IntoIterator,
3907 Self::Item: PartialEq<I::Item>,
3908 Self: Sized,
3909 {
3910 self.eq_by(other, |x, y| x == y)
3911 }
3912
3913 /// Determines if the elements of this [`Iterator`] are equal to those of
3914 /// another with respect to the specified equality function.
3915 ///
3916 /// # Examples
3917 ///
3918 /// ```
3919 /// #![feature(iter_order_by)]
3920 ///
3921 /// let xs = [1, 2, 3, 4];
3922 /// let ys = [1, 4, 9, 16];
3923 ///
3924 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3925 /// ```
3926 #[unstable(feature = "iter_order_by", issue = "64295")]
3927 #[rustc_non_const_trait_method]
3928 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3929 where
3930 Self: Sized,
3931 I: IntoIterator,
3932 F: FnMut(Self::Item, I::Item) -> bool,
3933 {
3934 #[inline]
3935 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3936 where
3937 F: FnMut(X, Y) -> bool,
3938 {
3939 move |x, y| {
3940 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3941 }
3942 }
3943
3944 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3945 }
3946
3947 /// Determines if the elements of this [`Iterator`] are not equal to those of
3948 /// another.
3949 ///
3950 /// # Examples
3951 ///
3952 /// ```
3953 /// assert_eq!([1].iter().ne([1].iter()), false);
3954 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3955 /// ```
3956 #[stable(feature = "iter_order", since = "1.5.0")]
3957 #[rustc_non_const_trait_method]
3958 fn ne<I>(self, other: I) -> bool
3959 where
3960 I: IntoIterator,
3961 Self::Item: PartialEq<I::Item>,
3962 Self: Sized,
3963 {
3964 !self.eq(other)
3965 }
3966
3967 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3968 /// less than those of another.
3969 ///
3970 /// # Examples
3971 ///
3972 /// ```
3973 /// assert_eq!([1].iter().lt([1].iter()), false);
3974 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3975 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3976 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3977 /// ```
3978 #[stable(feature = "iter_order", since = "1.5.0")]
3979 #[rustc_non_const_trait_method]
3980 fn lt<I>(self, other: I) -> bool
3981 where
3982 I: IntoIterator,
3983 Self::Item: PartialOrd<I::Item>,
3984 Self: Sized,
3985 {
3986 self.partial_cmp(other) == Some(Ordering::Less)
3987 }
3988
3989 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3990 /// less or equal to those of another.
3991 ///
3992 /// # Examples
3993 ///
3994 /// ```
3995 /// assert_eq!([1].iter().le([1].iter()), true);
3996 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3997 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3998 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3999 /// ```
4000 #[stable(feature = "iter_order", since = "1.5.0")]
4001 #[rustc_non_const_trait_method]
4002 fn le<I>(self, other: I) -> bool
4003 where
4004 I: IntoIterator,
4005 Self::Item: PartialOrd<I::Item>,
4006 Self: Sized,
4007 {
4008 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
4009 }
4010
4011 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4012 /// greater than those of another.
4013 ///
4014 /// # Examples
4015 ///
4016 /// ```
4017 /// assert_eq!([1].iter().gt([1].iter()), false);
4018 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
4019 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
4020 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
4021 /// ```
4022 #[stable(feature = "iter_order", since = "1.5.0")]
4023 #[rustc_non_const_trait_method]
4024 fn gt<I>(self, other: I) -> bool
4025 where
4026 I: IntoIterator,
4027 Self::Item: PartialOrd<I::Item>,
4028 Self: Sized,
4029 {
4030 self.partial_cmp(other) == Some(Ordering::Greater)
4031 }
4032
4033 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4034 /// greater than or equal to those of another.
4035 ///
4036 /// # Examples
4037 ///
4038 /// ```
4039 /// assert_eq!([1].iter().ge([1].iter()), true);
4040 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
4041 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
4042 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
4043 /// ```
4044 #[stable(feature = "iter_order", since = "1.5.0")]
4045 #[rustc_non_const_trait_method]
4046 fn ge<I>(self, other: I) -> bool
4047 where
4048 I: IntoIterator,
4049 Self::Item: PartialOrd<I::Item>,
4050 Self: Sized,
4051 {
4052 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
4053 }
4054
4055 /// Checks if the elements of this iterator are sorted.
4056 ///
4057 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4058 /// iterator yields exactly zero or one element, `true` is returned.
4059 ///
4060 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4061 /// implies that this function returns `false` if any two consecutive items are not
4062 /// comparable.
4063 ///
4064 /// # Examples
4065 ///
4066 /// ```
4067 /// assert!([1, 2, 2, 9].iter().is_sorted());
4068 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4069 /// assert!([0].iter().is_sorted());
4070 /// assert!(std::iter::empty::<i32>().is_sorted());
4071 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4072 /// ```
4073 #[inline]
4074 #[stable(feature = "is_sorted", since = "1.82.0")]
4075 #[rustc_non_const_trait_method]
4076 fn is_sorted(self) -> bool
4077 where
4078 Self: Sized,
4079 Self::Item: PartialOrd,
4080 {
4081 self.is_sorted_by(|a, b| a <= b)
4082 }
4083
4084 /// Checks if the elements of this iterator are sorted using the given comparator function.
4085 ///
4086 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4087 /// function to determine whether two elements are to be considered in sorted order.
4088 ///
4089 /// # Examples
4090 ///
4091 /// ```
4092 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4093 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4094 ///
4095 /// assert!([0].iter().is_sorted_by(|a, b| true));
4096 /// assert!([0].iter().is_sorted_by(|a, b| false));
4097 ///
4098 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4099 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4100 /// ```
4101 #[stable(feature = "is_sorted", since = "1.82.0")]
4102 #[rustc_non_const_trait_method]
4103 fn is_sorted_by<F>(mut self, compare: F) -> bool
4104 where
4105 Self: Sized,
4106 F: FnMut(&Self::Item, &Self::Item) -> bool,
4107 {
4108 #[inline]
4109 fn check<'a, T>(
4110 last: &'a mut T,
4111 mut compare: impl FnMut(&T, &T) -> bool + 'a,
4112 ) -> impl FnMut(T) -> bool + 'a {
4113 move |curr| {
4114 if !compare(&last, &curr) {
4115 return false;
4116 }
4117 *last = curr;
4118 true
4119 }
4120 }
4121
4122 let mut last = match self.next() {
4123 Some(e) => e,
4124 None => return true,
4125 };
4126
4127 self.all(check(&mut last, compare))
4128 }
4129
4130 /// Checks if the elements of this iterator are sorted using the given key extraction
4131 /// function.
4132 ///
4133 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4134 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4135 /// its documentation for more information.
4136 ///
4137 /// [`is_sorted`]: Iterator::is_sorted
4138 ///
4139 /// # Examples
4140 ///
4141 /// ```
4142 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4143 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4144 /// ```
4145 #[inline]
4146 #[stable(feature = "is_sorted", since = "1.82.0")]
4147 #[rustc_non_const_trait_method]
4148 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4149 where
4150 Self: Sized,
4151 F: FnMut(Self::Item) -> K,
4152 K: PartialOrd,
4153 {
4154 self.map(f).is_sorted()
4155 }
4156
4157 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4158 // The unusual name is to avoid name collisions in method resolution
4159 // see #76479.
4160 #[inline]
4161 #[doc(hidden)]
4162 #[unstable(feature = "trusted_random_access", issue = "none")]
4163 #[rustc_non_const_trait_method]
4164 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4165 where
4166 Self: TrustedRandomAccessNoCoerce,
4167 {
4168 unreachable!("Always specialized");
4169 }
4170}
4171
4172trait SpecIterEq<B: Iterator>: Iterator {
4173 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4174 where
4175 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4176}
4177
4178impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4179 #[inline]
4180 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4181 where
4182 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4183 {
4184 iter_eq(self, b, f)
4185 }
4186}
4187
4188impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4189 #[inline]
4190 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4191 where
4192 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4193 {
4194 // we *can't* short-circuit if:
4195 match (self.size_hint(), b.size_hint()) {
4196 // ... both iterators have the same length
4197 ((_, Some(a)), (_, Some(b))) if a == b => {}
4198 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4199 ((_, None), (_, None)) => {}
4200 // otherwise, we can ascertain that they are unequal without actually comparing items
4201 _ => return false,
4202 }
4203
4204 iter_eq(self, b, f)
4205 }
4206}
4207
4208/// Compares two iterators element-wise using the given function.
4209///
4210/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4211/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4212/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4213/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4214/// the iterators.
4215///
4216/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4217/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4218#[inline]
4219fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4220where
4221 A: Iterator,
4222 B: Iterator,
4223 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4224{
4225 #[inline]
4226 fn compare<'a, B, X, T>(
4227 b: &'a mut B,
4228 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4229 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4230 where
4231 B: Iterator,
4232 {
4233 move |x| match b.next() {
4234 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4235 Some(y) => f(x, y).map_break(ControlFlow::Break),
4236 }
4237 }
4238
4239 match a.try_for_each(compare(&mut b, f)) {
4240 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4241 None => Ordering::Equal,
4242 Some(_) => Ordering::Less,
4243 }),
4244 ControlFlow::Break(x) => x,
4245 }
4246}
4247
4248#[inline]
4249fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4250where
4251 A: Iterator,
4252 B: Iterator,
4253 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4254{
4255 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4256}
4257
4258/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4259///
4260/// This implementation passes all method calls on to the original iterator.
4261#[stable(feature = "rust1", since = "1.0.0")]
4262impl<I: Iterator + ?Sized> Iterator for &mut I {
4263 type Item = I::Item;
4264 #[inline]
4265 fn next(&mut self) -> Option<I::Item> {
4266 (**self).next()
4267 }
4268 fn size_hint(&self) -> (usize, Option<usize>) {
4269 (**self).size_hint()
4270 }
4271 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4272 (**self).advance_by(n)
4273 }
4274 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4275 (**self).nth(n)
4276 }
4277 fn fold<B, F>(self, init: B, f: F) -> B
4278 where
4279 F: FnMut(B, Self::Item) -> B,
4280 {
4281 self.spec_fold(init, f)
4282 }
4283 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4284 where
4285 F: FnMut(B, Self::Item) -> R,
4286 R: Try<Output = B>,
4287 {
4288 self.spec_try_fold(init, f)
4289 }
4290}
4291
4292/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4293trait IteratorRefSpec: Iterator {
4294 fn spec_fold<B, F>(self, init: B, f: F) -> B
4295 where
4296 F: FnMut(B, Self::Item) -> B;
4297
4298 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4299 where
4300 F: FnMut(B, Self::Item) -> R,
4301 R: Try<Output = B>;
4302}
4303
4304impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4305 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4306 where
4307 F: FnMut(B, Self::Item) -> B,
4308 {
4309 let mut accum = init;
4310 while let Some(x) = self.next() {
4311 accum = f(accum, x);
4312 }
4313 accum
4314 }
4315
4316 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4317 where
4318 F: FnMut(B, Self::Item) -> R,
4319 R: Try<Output = B>,
4320 {
4321 let mut accum = init;
4322 while let Some(x) = self.next() {
4323 accum = f(accum, x)?;
4324 }
4325 try { accum }
4326 }
4327}
4328
4329impl<I: Iterator> IteratorRefSpec for &mut I {
4330 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4331
4332 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4333 where
4334 F: FnMut(B, Self::Item) -> R,
4335 R: Try<Output = B>,
4336 {
4337 (**self).try_fold(init, f)
4338 }
4339}