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