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