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