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