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