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