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