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