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