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