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