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