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