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