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