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, Map, Rev, Skip, StepBy, Sum,
22 Take, 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", reason = "recently added", 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", reason = "recently added", 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", reason = "recently added", 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", reason = "recently added", 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 #[cfg(not(feature = "ferrocene_subset"))]
1225 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1226 where
1227 Self: Sized,
1228 P: FnMut(&Self::Item) -> bool,
1229 {
1230 TakeWhile::new(self, predicate)
1231 }
1232
1233 /// Creates an iterator that both yields elements based on a predicate and maps.
1234 ///
1235 /// `map_while()` takes a closure as an argument. It will call this
1236 /// closure on each element of the iterator, and yield elements
1237 /// while it returns [`Some(_)`][`Some`].
1238 ///
1239 /// # Examples
1240 ///
1241 /// Basic usage:
1242 ///
1243 /// ```
1244 /// let a = [-1i32, 4, 0, 1];
1245 ///
1246 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1247 ///
1248 /// assert_eq!(iter.next(), Some(-16));
1249 /// assert_eq!(iter.next(), Some(4));
1250 /// assert_eq!(iter.next(), None);
1251 /// ```
1252 ///
1253 /// Here's the same example, but with [`take_while`] and [`map`]:
1254 ///
1255 /// [`take_while`]: Iterator::take_while
1256 /// [`map`]: Iterator::map
1257 ///
1258 /// ```
1259 /// let a = [-1i32, 4, 0, 1];
1260 ///
1261 /// let mut iter = a.into_iter()
1262 /// .map(|x| 16i32.checked_div(x))
1263 /// .take_while(|x| x.is_some())
1264 /// .map(|x| x.unwrap());
1265 ///
1266 /// assert_eq!(iter.next(), Some(-16));
1267 /// assert_eq!(iter.next(), Some(4));
1268 /// assert_eq!(iter.next(), None);
1269 /// ```
1270 ///
1271 /// Stopping after an initial [`None`]:
1272 ///
1273 /// ```
1274 /// let a = [0, 1, 2, -3, 4, 5, -6];
1275 ///
1276 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1277 /// let vec: Vec<_> = iter.collect();
1278 ///
1279 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1280 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1281 /// assert_eq!(vec, [0, 1, 2]);
1282 /// ```
1283 ///
1284 /// Because `map_while()` needs to look at the value in order to see if it
1285 /// should be included or not, consuming iterators will see that it is
1286 /// removed:
1287 ///
1288 /// ```
1289 /// let a = [1, 2, -3, 4];
1290 /// let mut iter = a.into_iter();
1291 ///
1292 /// let result: Vec<u32> = iter.by_ref()
1293 /// .map_while(|n| u32::try_from(n).ok())
1294 /// .collect();
1295 ///
1296 /// assert_eq!(result, [1, 2]);
1297 ///
1298 /// let result: Vec<i32> = iter.collect();
1299 ///
1300 /// assert_eq!(result, [4]);
1301 /// ```
1302 ///
1303 /// The `-3` is no longer there, because it was consumed in order to see if
1304 /// the iteration should stop, but wasn't placed back into the iterator.
1305 ///
1306 /// Note that unlike [`take_while`] this iterator is **not** fused.
1307 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1308 /// If you need a fused iterator, use [`fuse`].
1309 ///
1310 /// [`fuse`]: Iterator::fuse
1311 #[inline]
1312 #[stable(feature = "iter_map_while", since = "1.57.0")]
1313 #[cfg(not(feature = "ferrocene_subset"))]
1314 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1315 where
1316 Self: Sized,
1317 P: FnMut(Self::Item) -> Option<B>,
1318 {
1319 MapWhile::new(self, predicate)
1320 }
1321
1322 /// Creates an iterator that skips the first `n` elements.
1323 ///
1324 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1325 /// iterator is reached (whichever happens first). After that, all the remaining
1326 /// elements are yielded. In particular, if the original iterator is too short,
1327 /// then the returned iterator is empty.
1328 ///
1329 /// Rather than overriding this method directly, instead override the `nth` method.
1330 ///
1331 /// # Examples
1332 ///
1333 /// ```
1334 /// let a = [1, 2, 3];
1335 ///
1336 /// let mut iter = a.into_iter().skip(2);
1337 ///
1338 /// assert_eq!(iter.next(), Some(3));
1339 /// assert_eq!(iter.next(), None);
1340 /// ```
1341 #[inline]
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 fn skip(self, n: usize) -> Skip<Self>
1344 where
1345 Self: Sized,
1346 {
1347 Skip::new(self, n)
1348 }
1349
1350 /// Creates an iterator that yields the first `n` elements, or fewer
1351 /// if the underlying iterator ends sooner.
1352 ///
1353 /// `take(n)` yields elements until `n` elements are yielded or the end of
1354 /// the iterator is reached (whichever happens first).
1355 /// The returned iterator is a prefix of length `n` if the original iterator
1356 /// contains at least `n` elements, otherwise it contains all of the
1357 /// (fewer than `n`) elements of the original iterator.
1358 ///
1359 /// # Examples
1360 ///
1361 /// Basic usage:
1362 ///
1363 /// ```
1364 /// let a = [1, 2, 3];
1365 ///
1366 /// let mut iter = a.into_iter().take(2);
1367 ///
1368 /// assert_eq!(iter.next(), Some(1));
1369 /// assert_eq!(iter.next(), Some(2));
1370 /// assert_eq!(iter.next(), None);
1371 /// ```
1372 ///
1373 /// `take()` is often used with an infinite iterator, to make it finite:
1374 ///
1375 /// ```
1376 /// let mut iter = (0..).take(3);
1377 ///
1378 /// assert_eq!(iter.next(), Some(0));
1379 /// assert_eq!(iter.next(), Some(1));
1380 /// assert_eq!(iter.next(), Some(2));
1381 /// assert_eq!(iter.next(), None);
1382 /// ```
1383 ///
1384 /// If less than `n` elements are available,
1385 /// `take` will limit itself to the size of the underlying iterator:
1386 ///
1387 /// ```
1388 /// let v = [1, 2];
1389 /// let mut iter = v.into_iter().take(5);
1390 /// assert_eq!(iter.next(), Some(1));
1391 /// assert_eq!(iter.next(), Some(2));
1392 /// assert_eq!(iter.next(), None);
1393 /// ```
1394 ///
1395 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1396 /// continue using the original iterator:
1397 ///
1398 /// ```
1399 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1400 ///
1401 /// // Take the first two words.
1402 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1403 /// assert_eq!(hello_world, vec!["hello", "world"]);
1404 ///
1405 /// // Collect the rest of the words.
1406 /// // We can only do this because we used `by_ref` earlier.
1407 /// let of_rust: Vec<_> = words.collect();
1408 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1409 /// ```
1410 ///
1411 /// [`by_ref`]: Iterator::by_ref
1412 #[doc(alias = "limit")]
1413 #[inline]
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 fn take(self, n: usize) -> Take<Self>
1416 where
1417 Self: Sized,
1418 {
1419 Take::new(self, n)
1420 }
1421
1422 /// An iterator adapter which, like [`fold`], holds internal state, but
1423 /// unlike [`fold`], produces a new iterator.
1424 ///
1425 /// [`fold`]: Iterator::fold
1426 ///
1427 /// `scan()` takes two arguments: an initial value which seeds the internal
1428 /// state, and a closure with two arguments, the first being a mutable
1429 /// reference to the internal state and the second an iterator element.
1430 /// The closure can assign to the internal state to share state between
1431 /// iterations.
1432 ///
1433 /// On iteration, the closure will be applied to each element of the
1434 /// iterator and the return value from the closure, an [`Option`], is
1435 /// returned by the `next` method. Thus the closure can return
1436 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1437 ///
1438 /// # Examples
1439 ///
1440 /// ```
1441 /// let a = [1, 2, 3, 4];
1442 ///
1443 /// let mut iter = a.into_iter().scan(1, |state, x| {
1444 /// // each iteration, we'll multiply the state by the element ...
1445 /// *state = *state * x;
1446 ///
1447 /// // ... and terminate if the state exceeds 6
1448 /// if *state > 6 {
1449 /// return None;
1450 /// }
1451 /// // ... else yield the negation of the state
1452 /// Some(-*state)
1453 /// });
1454 ///
1455 /// assert_eq!(iter.next(), Some(-1));
1456 /// assert_eq!(iter.next(), Some(-2));
1457 /// assert_eq!(iter.next(), Some(-6));
1458 /// assert_eq!(iter.next(), None);
1459 /// ```
1460 #[inline]
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 #[cfg(not(feature = "ferrocene_subset"))]
1463 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1464 where
1465 Self: Sized,
1466 F: FnMut(&mut St, Self::Item) -> Option<B>,
1467 {
1468 Scan::new(self, initial_state, f)
1469 }
1470
1471 /// Creates an iterator that works like map, but flattens nested structure.
1472 ///
1473 /// The [`map`] adapter is very useful, but only when the closure
1474 /// argument produces values. If it produces an iterator instead, there's
1475 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1476 /// on its own.
1477 ///
1478 /// You can think of `flat_map(f)` as the semantic equivalent
1479 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1480 ///
1481 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1482 /// one item for each element, and `flat_map()`'s closure returns an
1483 /// iterator for each element.
1484 ///
1485 /// [`map`]: Iterator::map
1486 /// [`flatten`]: Iterator::flatten
1487 ///
1488 /// # Examples
1489 ///
1490 /// ```
1491 /// let words = ["alpha", "beta", "gamma"];
1492 ///
1493 /// // chars() returns an iterator
1494 /// let merged: String = words.iter()
1495 /// .flat_map(|s| s.chars())
1496 /// .collect();
1497 /// assert_eq!(merged, "alphabetagamma");
1498 /// ```
1499 #[inline]
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 #[cfg(not(feature = "ferrocene_subset"))]
1502 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1503 where
1504 Self: Sized,
1505 U: IntoIterator,
1506 F: FnMut(Self::Item) -> U,
1507 {
1508 FlatMap::new(self, f)
1509 }
1510
1511 /// Creates an iterator that flattens nested structure.
1512 ///
1513 /// This is useful when you have an iterator of iterators or an iterator of
1514 /// things that can be turned into iterators and you want to remove one
1515 /// level of indirection.
1516 ///
1517 /// # Examples
1518 ///
1519 /// Basic usage:
1520 ///
1521 /// ```
1522 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1523 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1524 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1525 /// ```
1526 ///
1527 /// Mapping and then flattening:
1528 ///
1529 /// ```
1530 /// let words = ["alpha", "beta", "gamma"];
1531 ///
1532 /// // chars() returns an iterator
1533 /// let merged: String = words.iter()
1534 /// .map(|s| s.chars())
1535 /// .flatten()
1536 /// .collect();
1537 /// assert_eq!(merged, "alphabetagamma");
1538 /// ```
1539 ///
1540 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1541 /// in this case since it conveys intent more clearly:
1542 ///
1543 /// ```
1544 /// let words = ["alpha", "beta", "gamma"];
1545 ///
1546 /// // chars() returns an iterator
1547 /// let merged: String = words.iter()
1548 /// .flat_map(|s| s.chars())
1549 /// .collect();
1550 /// assert_eq!(merged, "alphabetagamma");
1551 /// ```
1552 ///
1553 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1554 ///
1555 /// ```
1556 /// let options = vec![Some(123), Some(321), None, Some(231)];
1557 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1558 /// assert_eq!(flattened_options, [123, 321, 231]);
1559 ///
1560 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1561 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1562 /// assert_eq!(flattened_results, [123, 321, 231]);
1563 /// ```
1564 ///
1565 /// Flattening only removes one level of nesting at a time:
1566 ///
1567 /// ```
1568 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1569 ///
1570 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1571 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1572 ///
1573 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1574 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1575 /// ```
1576 ///
1577 /// Here we see that `flatten()` does not perform a "deep" flatten.
1578 /// Instead, only one level of nesting is removed. That is, if you
1579 /// `flatten()` a three-dimensional array, the result will be
1580 /// two-dimensional and not one-dimensional. To get a one-dimensional
1581 /// structure, you have to `flatten()` again.
1582 ///
1583 /// [`flat_map()`]: Iterator::flat_map
1584 #[inline]
1585 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1586 #[cfg(not(feature = "ferrocene_subset"))]
1587 fn flatten(self) -> Flatten<Self>
1588 where
1589 Self: Sized,
1590 Self::Item: IntoIterator,
1591 {
1592 Flatten::new(self)
1593 }
1594
1595 /// Calls the given function `f` for each contiguous window of size `N` over
1596 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1597 /// the windows during mapping overlap as well.
1598 ///
1599 /// In the following example, the closure is called three times with the
1600 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1601 ///
1602 /// ```
1603 /// #![feature(iter_map_windows)]
1604 ///
1605 /// let strings = "abcd".chars()
1606 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1607 /// .collect::<Vec<String>>();
1608 ///
1609 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1610 /// ```
1611 ///
1612 /// Note that the const parameter `N` is usually inferred by the
1613 /// destructured argument in the closure.
1614 ///
1615 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1616 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1617 /// empty iterator.
1618 ///
1619 /// The returned iterator implements [`FusedIterator`], because once `self`
1620 /// returns `None`, even if it returns a `Some(T)` again in the next iterations,
1621 /// we cannot put it into a contiguous array buffer, and thus the returned iterator
1622 /// should be fused.
1623 ///
1624 /// [`slice::windows()`]: slice::windows
1625 /// [`FusedIterator`]: crate::iter::FusedIterator
1626 ///
1627 /// # Panics
1628 ///
1629 /// Panics if `N` is zero. This check will most probably get changed to a
1630 /// compile time error before this method gets stabilized.
1631 ///
1632 /// ```should_panic
1633 /// #![feature(iter_map_windows)]
1634 ///
1635 /// let iter = std::iter::repeat(0).map_windows(|&[]| ());
1636 /// ```
1637 ///
1638 /// # Examples
1639 ///
1640 /// Building the sums of neighboring numbers.
1641 ///
1642 /// ```
1643 /// #![feature(iter_map_windows)]
1644 ///
1645 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1646 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1647 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1648 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1649 /// assert_eq!(it.next(), None);
1650 /// ```
1651 ///
1652 /// Since the elements in the following example implement `Copy`, we can
1653 /// just copy the array and get an iterator over the windows.
1654 ///
1655 /// ```
1656 /// #![feature(iter_map_windows)]
1657 ///
1658 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1659 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1660 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1661 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1662 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1663 /// assert_eq!(it.next(), None);
1664 /// ```
1665 ///
1666 /// You can also use this function to check the sortedness of an iterator.
1667 /// For the simple case, rather use [`Iterator::is_sorted`].
1668 ///
1669 /// ```
1670 /// #![feature(iter_map_windows)]
1671 ///
1672 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1673 /// .map_windows(|[a, b]| a <= b);
1674 ///
1675 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1676 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1677 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1678 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1679 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1680 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1681 /// assert_eq!(it.next(), None);
1682 /// ```
1683 ///
1684 /// For non-fused iterators, they are fused after `map_windows`.
1685 ///
1686 /// ```
1687 /// #![feature(iter_map_windows)]
1688 ///
1689 /// #[derive(Default)]
1690 /// struct NonFusedIterator {
1691 /// state: i32,
1692 /// }
1693 ///
1694 /// impl Iterator for NonFusedIterator {
1695 /// type Item = i32;
1696 ///
1697 /// fn next(&mut self) -> Option<i32> {
1698 /// let val = self.state;
1699 /// self.state = self.state + 1;
1700 ///
1701 /// // yields `0..5` first, then only even numbers since `6..`.
1702 /// if val < 5 || val % 2 == 0 {
1703 /// Some(val)
1704 /// } else {
1705 /// None
1706 /// }
1707 /// }
1708 /// }
1709 ///
1710 ///
1711 /// let mut iter = NonFusedIterator::default();
1712 ///
1713 /// // yields 0..5 first.
1714 /// assert_eq!(iter.next(), Some(0));
1715 /// assert_eq!(iter.next(), Some(1));
1716 /// assert_eq!(iter.next(), Some(2));
1717 /// assert_eq!(iter.next(), Some(3));
1718 /// assert_eq!(iter.next(), Some(4));
1719 /// // then we can see our iterator going back and forth
1720 /// assert_eq!(iter.next(), None);
1721 /// assert_eq!(iter.next(), Some(6));
1722 /// assert_eq!(iter.next(), None);
1723 /// assert_eq!(iter.next(), Some(8));
1724 /// assert_eq!(iter.next(), None);
1725 ///
1726 /// // however, with `.map_windows()`, it is fused.
1727 /// let mut iter = NonFusedIterator::default()
1728 /// .map_windows(|arr: &[_; 2]| *arr);
1729 ///
1730 /// assert_eq!(iter.next(), Some([0, 1]));
1731 /// assert_eq!(iter.next(), Some([1, 2]));
1732 /// assert_eq!(iter.next(), Some([2, 3]));
1733 /// assert_eq!(iter.next(), Some([3, 4]));
1734 /// assert_eq!(iter.next(), None);
1735 ///
1736 /// // it will always return `None` after the first time.
1737 /// assert_eq!(iter.next(), None);
1738 /// assert_eq!(iter.next(), None);
1739 /// assert_eq!(iter.next(), None);
1740 /// ```
1741 #[inline]
1742 #[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")]
1743 #[cfg(not(feature = "ferrocene_subset"))]
1744 fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
1745 where
1746 Self: Sized,
1747 F: FnMut(&[Self::Item; N]) -> R,
1748 {
1749 MapWindows::new(self, f)
1750 }
1751
1752 /// Creates an iterator which ends after the first [`None`].
1753 ///
1754 /// After an iterator returns [`None`], future calls may or may not yield
1755 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1756 /// [`None`] is given, it will always return [`None`] forever.
1757 ///
1758 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1759 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1760 /// if the [`FusedIterator`] trait is improperly implemented.
1761 ///
1762 /// [`Some(T)`]: Some
1763 /// [`FusedIterator`]: crate::iter::FusedIterator
1764 ///
1765 /// # Examples
1766 ///
1767 /// ```
1768 /// // an iterator which alternates between Some and None
1769 /// struct Alternate {
1770 /// state: i32,
1771 /// }
1772 ///
1773 /// impl Iterator for Alternate {
1774 /// type Item = i32;
1775 ///
1776 /// fn next(&mut self) -> Option<i32> {
1777 /// let val = self.state;
1778 /// self.state = self.state + 1;
1779 ///
1780 /// // if it's even, Some(i32), else None
1781 /// (val % 2 == 0).then_some(val)
1782 /// }
1783 /// }
1784 ///
1785 /// let mut iter = Alternate { state: 0 };
1786 ///
1787 /// // we can see our iterator going back and forth
1788 /// assert_eq!(iter.next(), Some(0));
1789 /// assert_eq!(iter.next(), None);
1790 /// assert_eq!(iter.next(), Some(2));
1791 /// assert_eq!(iter.next(), None);
1792 ///
1793 /// // however, once we fuse it...
1794 /// let mut iter = iter.fuse();
1795 ///
1796 /// assert_eq!(iter.next(), Some(4));
1797 /// assert_eq!(iter.next(), None);
1798 ///
1799 /// // it will always return `None` after the first time.
1800 /// assert_eq!(iter.next(), None);
1801 /// assert_eq!(iter.next(), None);
1802 /// assert_eq!(iter.next(), None);
1803 /// ```
1804 #[inline]
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 #[cfg(not(feature = "ferrocene_subset"))]
1807 fn fuse(self) -> Fuse<Self>
1808 where
1809 Self: Sized,
1810 {
1811 Fuse::new(self)
1812 }
1813
1814 /// Does something with each element of an iterator, passing the value on.
1815 ///
1816 /// When using iterators, you'll often chain several of them together.
1817 /// While working on such code, you might want to check out what's
1818 /// happening at various parts in the pipeline. To do that, insert
1819 /// a call to `inspect()`.
1820 ///
1821 /// It's more common for `inspect()` to be used as a debugging tool than to
1822 /// exist in your final code, but applications may find it useful in certain
1823 /// situations when errors need to be logged before being discarded.
1824 ///
1825 /// # Examples
1826 ///
1827 /// Basic usage:
1828 ///
1829 /// ```
1830 /// let a = [1, 4, 2, 3];
1831 ///
1832 /// // this iterator sequence is complex.
1833 /// let sum = a.iter()
1834 /// .cloned()
1835 /// .filter(|x| x % 2 == 0)
1836 /// .fold(0, |sum, i| sum + i);
1837 ///
1838 /// println!("{sum}");
1839 ///
1840 /// // let's add some inspect() calls to investigate what's happening
1841 /// let sum = a.iter()
1842 /// .cloned()
1843 /// .inspect(|x| println!("about to filter: {x}"))
1844 /// .filter(|x| x % 2 == 0)
1845 /// .inspect(|x| println!("made it through filter: {x}"))
1846 /// .fold(0, |sum, i| sum + i);
1847 ///
1848 /// println!("{sum}");
1849 /// ```
1850 ///
1851 /// This will print:
1852 ///
1853 /// ```text
1854 /// 6
1855 /// about to filter: 1
1856 /// about to filter: 4
1857 /// made it through filter: 4
1858 /// about to filter: 2
1859 /// made it through filter: 2
1860 /// about to filter: 3
1861 /// 6
1862 /// ```
1863 ///
1864 /// Logging errors before discarding them:
1865 ///
1866 /// ```
1867 /// let lines = ["1", "2", "a"];
1868 ///
1869 /// let sum: i32 = lines
1870 /// .iter()
1871 /// .map(|line| line.parse::<i32>())
1872 /// .inspect(|num| {
1873 /// if let Err(ref e) = *num {
1874 /// println!("Parsing error: {e}");
1875 /// }
1876 /// })
1877 /// .filter_map(Result::ok)
1878 /// .sum();
1879 ///
1880 /// println!("Sum: {sum}");
1881 /// ```
1882 ///
1883 /// This will print:
1884 ///
1885 /// ```text
1886 /// Parsing error: invalid digit found in string
1887 /// Sum: 3
1888 /// ```
1889 #[inline]
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 #[cfg(not(feature = "ferrocene_subset"))]
1892 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1893 where
1894 Self: Sized,
1895 F: FnMut(&Self::Item),
1896 {
1897 Inspect::new(self, f)
1898 }
1899
1900 /// Creates a "by reference" adapter for this instance of `Iterator`.
1901 ///
1902 /// Consuming method calls (direct or indirect calls to `next`)
1903 /// on the "by reference" adapter will consume the original iterator,
1904 /// but ownership-taking methods (those with a `self` parameter)
1905 /// only take ownership of the "by reference" iterator.
1906 ///
1907 /// This is useful for applying ownership-taking methods
1908 /// (such as `take` in the example below)
1909 /// without giving up ownership of the original iterator,
1910 /// so you can use the original iterator afterwards.
1911 ///
1912 /// 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).
1913 ///
1914 /// # Examples
1915 ///
1916 /// ```
1917 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1918 ///
1919 /// // Take the first two words.
1920 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1921 /// assert_eq!(hello_world, vec!["hello", "world"]);
1922 ///
1923 /// // Collect the rest of the words.
1924 /// // We can only do this because we used `by_ref` earlier.
1925 /// let of_rust: Vec<_> = words.collect();
1926 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1927 /// ```
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 fn by_ref(&mut self) -> &mut Self
1930 where
1931 Self: Sized,
1932 {
1933 self
1934 }
1935
1936 /// Transforms an iterator into a collection.
1937 ///
1938 /// `collect()` can take anything iterable, and turn it into a relevant
1939 /// collection. This is one of the more powerful methods in the standard
1940 /// library, used in a variety of contexts.
1941 ///
1942 /// The most basic pattern in which `collect()` is used is to turn one
1943 /// collection into another. You take a collection, call [`iter`] on it,
1944 /// do a bunch of transformations, and then `collect()` at the end.
1945 ///
1946 /// `collect()` can also create instances of types that are not typical
1947 /// collections. For example, a [`String`] can be built from [`char`]s,
1948 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1949 /// into `Result<Collection<T>, E>`. See the examples below for more.
1950 ///
1951 /// Because `collect()` is so general, it can cause problems with type
1952 /// inference. As such, `collect()` is one of the few times you'll see
1953 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1954 /// helps the inference algorithm understand specifically which collection
1955 /// you're trying to collect into.
1956 ///
1957 /// # Examples
1958 ///
1959 /// Basic usage:
1960 ///
1961 /// ```
1962 /// let a = [1, 2, 3];
1963 ///
1964 /// let doubled: Vec<i32> = a.iter()
1965 /// .map(|x| x * 2)
1966 /// .collect();
1967 ///
1968 /// assert_eq!(vec![2, 4, 6], doubled);
1969 /// ```
1970 ///
1971 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1972 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1973 ///
1974 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1975 ///
1976 /// ```
1977 /// use std::collections::VecDeque;
1978 ///
1979 /// let a = [1, 2, 3];
1980 ///
1981 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
1982 ///
1983 /// assert_eq!(2, doubled[0]);
1984 /// assert_eq!(4, doubled[1]);
1985 /// assert_eq!(6, doubled[2]);
1986 /// ```
1987 ///
1988 /// Using the 'turbofish' instead of annotating `doubled`:
1989 ///
1990 /// ```
1991 /// let a = [1, 2, 3];
1992 ///
1993 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1994 ///
1995 /// assert_eq!(vec![2, 4, 6], doubled);
1996 /// ```
1997 ///
1998 /// Because `collect()` only cares about what you're collecting into, you can
1999 /// still use a partial type hint, `_`, with the turbofish:
2000 ///
2001 /// ```
2002 /// let a = [1, 2, 3];
2003 ///
2004 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2005 ///
2006 /// assert_eq!(vec![2, 4, 6], doubled);
2007 /// ```
2008 ///
2009 /// Using `collect()` to make a [`String`]:
2010 ///
2011 /// ```
2012 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2013 ///
2014 /// let hello: String = chars.into_iter()
2015 /// .map(|x| x as u8)
2016 /// .map(|x| (x + 1) as char)
2017 /// .collect();
2018 ///
2019 /// assert_eq!("hello", hello);
2020 /// ```
2021 ///
2022 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2023 /// see if any of them failed:
2024 ///
2025 /// ```
2026 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2027 ///
2028 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2029 ///
2030 /// // gives us the first error
2031 /// assert_eq!(Err("nope"), result);
2032 ///
2033 /// let results = [Ok(1), Ok(3)];
2034 ///
2035 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2036 ///
2037 /// // gives us the list of answers
2038 /// assert_eq!(Ok(vec![1, 3]), result);
2039 /// ```
2040 ///
2041 /// [`iter`]: Iterator::next
2042 /// [`String`]: ../../std/string/struct.String.html
2043 /// [`char`]: type@char
2044 #[inline]
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2047 #[rustc_diagnostic_item = "iterator_collect_fn"]
2048 fn collect<B: FromIterator<Self::Item>>(self) -> B
2049 where
2050 Self: Sized,
2051 {
2052 // This is too aggressive to turn on for everything all the time, but PR#137908
2053 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2054 // so this will help catch such things in debug-assertions-std runners,
2055 // even if users won't actually ever see it.
2056 #[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", reason = "new API", 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", reason = "new API", 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", reason = "new API", 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", reason = "new API", 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 /// Stopping at the first `true`:
2902 ///
2903 /// ```
2904 /// let a = [1, 2, 3];
2905 ///
2906 /// let mut iter = a.into_iter();
2907 ///
2908 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2909 ///
2910 /// // we can still use `iter`, as there are more elements.
2911 /// assert_eq!(iter.next(), Some(3));
2912 /// ```
2913 ///
2914 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2915 #[inline]
2916 #[stable(feature = "rust1", since = "1.0.0")]
2917 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2918 where
2919 Self: Sized,
2920 P: FnMut(&Self::Item) -> bool,
2921 {
2922 #[inline]
2923 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2924 move |(), x| {
2925 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2926 }
2927 }
2928
2929 self.try_fold((), check(predicate)).break_value()
2930 }
2931
2932 /// Applies function to the elements of iterator and returns
2933 /// the first non-none result.
2934 ///
2935 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2936 ///
2937 /// # Examples
2938 ///
2939 /// ```
2940 /// let a = ["lol", "NaN", "2", "5"];
2941 ///
2942 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2943 ///
2944 /// assert_eq!(first_number, Some(2));
2945 /// ```
2946 #[inline]
2947 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2948 #[cfg(not(feature = "ferrocene_subset"))]
2949 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2950 where
2951 Self: Sized,
2952 F: FnMut(Self::Item) -> Option<B>,
2953 {
2954 #[inline]
2955 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2956 move |(), x| match f(x) {
2957 Some(x) => ControlFlow::Break(x),
2958 None => ControlFlow::Continue(()),
2959 }
2960 }
2961
2962 self.try_fold((), check(f)).break_value()
2963 }
2964
2965 /// Applies function to the elements of iterator and returns
2966 /// the first true result or the first error.
2967 ///
2968 /// The return type of this method depends on the return type of the closure.
2969 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
2970 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
2971 ///
2972 /// # Examples
2973 ///
2974 /// ```
2975 /// #![feature(try_find)]
2976 ///
2977 /// let a = ["1", "2", "lol", "NaN", "5"];
2978 ///
2979 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2980 /// Ok(s.parse::<i32>()? == search)
2981 /// };
2982 ///
2983 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
2984 /// assert_eq!(result, Ok(Some("2")));
2985 ///
2986 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
2987 /// assert!(result.is_err());
2988 /// ```
2989 ///
2990 /// This also supports other types which implement [`Try`], not just [`Result`].
2991 ///
2992 /// ```
2993 /// #![feature(try_find)]
2994 ///
2995 /// use std::num::NonZero;
2996 ///
2997 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
2998 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
2999 /// assert_eq!(result, Some(Some(4)));
3000 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3001 /// assert_eq!(result, Some(None));
3002 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3003 /// assert_eq!(result, None);
3004 /// ```
3005 #[inline]
3006 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
3007 #[cfg(not(feature = "ferrocene_subset"))]
3008 fn try_find<R>(
3009 &mut self,
3010 f: impl FnMut(&Self::Item) -> R,
3011 ) -> ChangeOutputType<R, Option<Self::Item>>
3012 where
3013 Self: Sized,
3014 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3015 {
3016 #[inline]
3017 fn check<I, V, R>(
3018 mut f: impl FnMut(&I) -> V,
3019 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3020 where
3021 V: Try<Output = bool, Residual = R>,
3022 R: Residual<Option<I>>,
3023 {
3024 move |(), x| match f(&x).branch() {
3025 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3026 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3027 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3028 }
3029 }
3030
3031 match self.try_fold((), check(f)) {
3032 ControlFlow::Break(x) => x,
3033 ControlFlow::Continue(()) => Try::from_output(None),
3034 }
3035 }
3036
3037 /// Searches for an element in an iterator, returning its index.
3038 ///
3039 /// `position()` takes a closure that returns `true` or `false`. It applies
3040 /// this closure to each element of the iterator, and if one of them
3041 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3042 /// them return `false`, it returns [`None`].
3043 ///
3044 /// `position()` is short-circuiting; in other words, it will stop
3045 /// processing as soon as it finds a `true`.
3046 ///
3047 /// # Overflow Behavior
3048 ///
3049 /// The method does no guarding against overflows, so if there are more
3050 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3051 /// result or panics. If overflow checks are enabled, a panic is
3052 /// guaranteed.
3053 ///
3054 /// # Panics
3055 ///
3056 /// This function might panic if the iterator has more than `usize::MAX`
3057 /// non-matching elements.
3058 ///
3059 /// [`Some(index)`]: Some
3060 ///
3061 /// # Examples
3062 ///
3063 /// Basic usage:
3064 ///
3065 /// ```
3066 /// let a = [1, 2, 3];
3067 ///
3068 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3069 ///
3070 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3071 /// ```
3072 ///
3073 /// Stopping at the first `true`:
3074 ///
3075 /// ```
3076 /// let a = [1, 2, 3, 4];
3077 ///
3078 /// let mut iter = a.into_iter();
3079 ///
3080 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3081 ///
3082 /// // we can still use `iter`, as there are more elements.
3083 /// assert_eq!(iter.next(), Some(3));
3084 ///
3085 /// // The returned index depends on iterator state
3086 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3087 ///
3088 /// ```
3089 #[inline]
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 fn position<P>(&mut self, predicate: P) -> Option<usize>
3092 where
3093 Self: Sized,
3094 P: FnMut(Self::Item) -> bool,
3095 {
3096 #[inline]
3097 fn check<'a, T>(
3098 mut predicate: impl FnMut(T) -> bool + 'a,
3099 acc: &'a mut usize,
3100 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3101 #[rustc_inherit_overflow_checks]
3102 move |_, x| {
3103 if predicate(x) {
3104 ControlFlow::Break(*acc)
3105 } else {
3106 *acc += 1;
3107 ControlFlow::Continue(())
3108 }
3109 }
3110 }
3111
3112 let mut acc = 0;
3113 self.try_fold((), check(predicate, &mut acc)).break_value()
3114 }
3115
3116 /// Searches for an element in an iterator from the right, returning its
3117 /// index.
3118 ///
3119 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3120 /// this closure to each element of the iterator, starting from the end,
3121 /// and if one of them returns `true`, then `rposition()` returns
3122 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3123 ///
3124 /// `rposition()` is short-circuiting; in other words, it will stop
3125 /// processing as soon as it finds a `true`.
3126 ///
3127 /// [`Some(index)`]: Some
3128 ///
3129 /// # Examples
3130 ///
3131 /// Basic usage:
3132 ///
3133 /// ```
3134 /// let a = [1, 2, 3];
3135 ///
3136 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3137 ///
3138 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3139 /// ```
3140 ///
3141 /// Stopping at the first `true`:
3142 ///
3143 /// ```
3144 /// let a = [-1, 2, 3, 4];
3145 ///
3146 /// let mut iter = a.into_iter();
3147 ///
3148 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3149 ///
3150 /// // we can still use `iter`, as there are more elements.
3151 /// assert_eq!(iter.next(), Some(-1));
3152 /// assert_eq!(iter.next_back(), Some(3));
3153 /// ```
3154 #[inline]
3155 #[stable(feature = "rust1", since = "1.0.0")]
3156 #[cfg(not(feature = "ferrocene_subset"))]
3157 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3158 where
3159 P: FnMut(Self::Item) -> bool,
3160 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3161 {
3162 // No need for an overflow check here, because `ExactSizeIterator`
3163 // implies that the number of elements fits into a `usize`.
3164 #[inline]
3165 fn check<T>(
3166 mut predicate: impl FnMut(T) -> bool,
3167 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3168 move |i, x| {
3169 let i = i - 1;
3170 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3171 }
3172 }
3173
3174 let n = self.len();
3175 self.try_rfold(n, check(predicate)).break_value()
3176 }
3177
3178 /// Returns the maximum element of an iterator.
3179 ///
3180 /// If several elements are equally maximum, the last element is
3181 /// returned. If the iterator is empty, [`None`] is returned.
3182 ///
3183 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3184 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3185 /// ```
3186 /// assert_eq!(
3187 /// [2.4, f32::NAN, 1.3]
3188 /// .into_iter()
3189 /// .reduce(f32::max)
3190 /// .unwrap_or(0.),
3191 /// 2.4
3192 /// );
3193 /// ```
3194 ///
3195 /// # Examples
3196 ///
3197 /// ```
3198 /// let a = [1, 2, 3];
3199 /// let b: [u32; 0] = [];
3200 ///
3201 /// assert_eq!(a.into_iter().max(), Some(3));
3202 /// assert_eq!(b.into_iter().max(), None);
3203 /// ```
3204 #[inline]
3205 #[stable(feature = "rust1", since = "1.0.0")]
3206 #[cfg(not(feature = "ferrocene_subset"))]
3207 fn max(self) -> Option<Self::Item>
3208 where
3209 Self: Sized,
3210 Self::Item: Ord,
3211 {
3212 self.max_by(Ord::cmp)
3213 }
3214
3215 /// Returns the minimum element of an iterator.
3216 ///
3217 /// If several elements are equally minimum, the first element is returned.
3218 /// If the iterator is empty, [`None`] is returned.
3219 ///
3220 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3221 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3222 /// ```
3223 /// assert_eq!(
3224 /// [2.4, f32::NAN, 1.3]
3225 /// .into_iter()
3226 /// .reduce(f32::min)
3227 /// .unwrap_or(0.),
3228 /// 1.3
3229 /// );
3230 /// ```
3231 ///
3232 /// # Examples
3233 ///
3234 /// ```
3235 /// let a = [1, 2, 3];
3236 /// let b: [u32; 0] = [];
3237 ///
3238 /// assert_eq!(a.into_iter().min(), Some(1));
3239 /// assert_eq!(b.into_iter().min(), None);
3240 /// ```
3241 #[inline]
3242 #[stable(feature = "rust1", since = "1.0.0")]
3243 #[cfg(not(feature = "ferrocene_subset"))]
3244 fn min(self) -> Option<Self::Item>
3245 where
3246 Self: Sized,
3247 Self::Item: Ord,
3248 {
3249 self.min_by(Ord::cmp)
3250 }
3251
3252 /// Returns the element that gives the maximum value from the
3253 /// specified function.
3254 ///
3255 /// If several elements are equally maximum, the last element is
3256 /// returned. If the iterator is empty, [`None`] is returned.
3257 ///
3258 /// # Examples
3259 ///
3260 /// ```
3261 /// let a = [-3_i32, 0, 1, 5, -10];
3262 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3263 /// ```
3264 #[inline]
3265 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3266 #[cfg(not(feature = "ferrocene_subset"))]
3267 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3268 where
3269 Self: Sized,
3270 F: FnMut(&Self::Item) -> B,
3271 {
3272 #[inline]
3273 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3274 move |x| (f(&x), x)
3275 }
3276
3277 #[inline]
3278 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3279 x_p.cmp(y_p)
3280 }
3281
3282 let (_, x) = self.map(key(f)).max_by(compare)?;
3283 Some(x)
3284 }
3285
3286 /// Returns the element that gives the maximum value with respect to the
3287 /// specified comparison function.
3288 ///
3289 /// If several elements are equally maximum, the last element is
3290 /// returned. If the iterator is empty, [`None`] is returned.
3291 ///
3292 /// # Examples
3293 ///
3294 /// ```
3295 /// let a = [-3_i32, 0, 1, 5, -10];
3296 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3297 /// ```
3298 #[inline]
3299 #[stable(feature = "iter_max_by", since = "1.15.0")]
3300 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3301 where
3302 Self: Sized,
3303 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3304 {
3305 #[inline]
3306 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3307 move |x, y| cmp::max_by(x, y, &mut compare)
3308 }
3309
3310 self.reduce(fold(compare))
3311 }
3312
3313 /// Returns the element that gives the minimum value from the
3314 /// specified function.
3315 ///
3316 /// If several elements are equally minimum, the first element is
3317 /// returned. If the iterator is empty, [`None`] is returned.
3318 ///
3319 /// # Examples
3320 ///
3321 /// ```
3322 /// let a = [-3_i32, 0, 1, 5, -10];
3323 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3324 /// ```
3325 #[inline]
3326 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3327 #[cfg(not(feature = "ferrocene_subset"))]
3328 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3329 where
3330 Self: Sized,
3331 F: FnMut(&Self::Item) -> B,
3332 {
3333 #[inline]
3334 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3335 move |x| (f(&x), x)
3336 }
3337
3338 #[inline]
3339 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3340 x_p.cmp(y_p)
3341 }
3342
3343 let (_, x) = self.map(key(f)).min_by(compare)?;
3344 Some(x)
3345 }
3346
3347 /// Returns the element that gives the minimum value with respect to the
3348 /// specified comparison function.
3349 ///
3350 /// If several elements are equally minimum, the first element is
3351 /// returned. If the iterator is empty, [`None`] is returned.
3352 ///
3353 /// # Examples
3354 ///
3355 /// ```
3356 /// let a = [-3_i32, 0, 1, 5, -10];
3357 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3358 /// ```
3359 #[inline]
3360 #[stable(feature = "iter_min_by", since = "1.15.0")]
3361 #[cfg(not(feature = "ferrocene_subset"))]
3362 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3363 where
3364 Self: Sized,
3365 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3366 {
3367 #[inline]
3368 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3369 move |x, y| cmp::min_by(x, y, &mut compare)
3370 }
3371
3372 self.reduce(fold(compare))
3373 }
3374
3375 /// Reverses an iterator's direction.
3376 ///
3377 /// Usually, iterators iterate from left to right. After using `rev()`,
3378 /// an iterator will instead iterate from right to left.
3379 ///
3380 /// This is only possible if the iterator has an end, so `rev()` only
3381 /// works on [`DoubleEndedIterator`]s.
3382 ///
3383 /// # Examples
3384 ///
3385 /// ```
3386 /// let a = [1, 2, 3];
3387 ///
3388 /// let mut iter = a.into_iter().rev();
3389 ///
3390 /// assert_eq!(iter.next(), Some(3));
3391 /// assert_eq!(iter.next(), Some(2));
3392 /// assert_eq!(iter.next(), Some(1));
3393 ///
3394 /// assert_eq!(iter.next(), None);
3395 /// ```
3396 #[inline]
3397 #[doc(alias = "reverse")]
3398 #[stable(feature = "rust1", since = "1.0.0")]
3399 fn rev(self) -> Rev<Self>
3400 where
3401 Self: Sized + DoubleEndedIterator,
3402 {
3403 Rev::new(self)
3404 }
3405
3406 /// Converts an iterator of pairs into a pair of containers.
3407 ///
3408 /// `unzip()` consumes an entire iterator of pairs, producing two
3409 /// collections: one from the left elements of the pairs, and one
3410 /// from the right elements.
3411 ///
3412 /// This function is, in some sense, the opposite of [`zip`].
3413 ///
3414 /// [`zip`]: Iterator::zip
3415 ///
3416 /// # Examples
3417 ///
3418 /// ```
3419 /// let a = [(1, 2), (3, 4), (5, 6)];
3420 ///
3421 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3422 ///
3423 /// assert_eq!(left, [1, 3, 5]);
3424 /// assert_eq!(right, [2, 4, 6]);
3425 ///
3426 /// // you can also unzip multiple nested tuples at once
3427 /// let a = [(1, (2, 3)), (4, (5, 6))];
3428 ///
3429 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3430 /// assert_eq!(x, [1, 4]);
3431 /// assert_eq!(y, [2, 5]);
3432 /// assert_eq!(z, [3, 6]);
3433 /// ```
3434 #[stable(feature = "rust1", since = "1.0.0")]
3435 #[cfg(not(feature = "ferrocene_subset"))]
3436 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3437 where
3438 FromA: Default + Extend<A>,
3439 FromB: Default + Extend<B>,
3440 Self: Sized + Iterator<Item = (A, B)>,
3441 {
3442 let mut unzipped: (FromA, FromB) = Default::default();
3443 unzipped.extend(self);
3444 unzipped
3445 }
3446
3447 /// Creates an iterator which copies all of its elements.
3448 ///
3449 /// This is useful when you have an iterator over `&T`, but you need an
3450 /// iterator over `T`.
3451 ///
3452 /// # Examples
3453 ///
3454 /// ```
3455 /// let a = [1, 2, 3];
3456 ///
3457 /// let v_copied: Vec<_> = a.iter().copied().collect();
3458 ///
3459 /// // copied is the same as .map(|&x| x)
3460 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3461 ///
3462 /// assert_eq!(v_copied, [1, 2, 3]);
3463 /// assert_eq!(v_map, [1, 2, 3]);
3464 /// ```
3465 #[stable(feature = "iter_copied", since = "1.36.0")]
3466 #[rustc_diagnostic_item = "iter_copied"]
3467 fn copied<'a, T>(self) -> Copied<Self>
3468 where
3469 T: Copy + 'a,
3470 Self: Sized + Iterator<Item = &'a T>,
3471 {
3472 Copied::new(self)
3473 }
3474
3475 /// Creates an iterator which [`clone`]s all of its elements.
3476 ///
3477 /// This is useful when you have an iterator over `&T`, but you need an
3478 /// iterator over `T`.
3479 ///
3480 /// There is no guarantee whatsoever about the `clone` method actually
3481 /// being called *or* optimized away. So code should not depend on
3482 /// either.
3483 ///
3484 /// [`clone`]: Clone::clone
3485 ///
3486 /// # Examples
3487 ///
3488 /// Basic usage:
3489 ///
3490 /// ```
3491 /// let a = [1, 2, 3];
3492 ///
3493 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3494 ///
3495 /// // cloned is the same as .map(|&x| x), for integers
3496 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3497 ///
3498 /// assert_eq!(v_cloned, [1, 2, 3]);
3499 /// assert_eq!(v_map, [1, 2, 3]);
3500 /// ```
3501 ///
3502 /// To get the best performance, try to clone late:
3503 ///
3504 /// ```
3505 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3506 /// // don't do this:
3507 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3508 /// assert_eq!(&[vec![23]], &slower[..]);
3509 /// // instead call `cloned` late
3510 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3511 /// assert_eq!(&[vec![23]], &faster[..]);
3512 /// ```
3513 #[stable(feature = "rust1", since = "1.0.0")]
3514 #[rustc_diagnostic_item = "iter_cloned"]
3515 fn cloned<'a, T>(self) -> Cloned<Self>
3516 where
3517 T: Clone + 'a,
3518 Self: Sized + Iterator<Item = &'a T>,
3519 {
3520 Cloned::new(self)
3521 }
3522
3523 /// Repeats an iterator endlessly.
3524 ///
3525 /// Instead of stopping at [`None`], the iterator will instead start again,
3526 /// from the beginning. After iterating again, it will start at the
3527 /// beginning again. And again. And again. Forever. Note that in case the
3528 /// original iterator is empty, the resulting iterator will also be empty.
3529 ///
3530 /// # Examples
3531 ///
3532 /// ```
3533 /// let a = [1, 2, 3];
3534 ///
3535 /// let mut iter = a.into_iter().cycle();
3536 ///
3537 /// loop {
3538 /// assert_eq!(iter.next(), Some(1));
3539 /// assert_eq!(iter.next(), Some(2));
3540 /// assert_eq!(iter.next(), Some(3));
3541 /// # break;
3542 /// }
3543 /// ```
3544 #[stable(feature = "rust1", since = "1.0.0")]
3545 #[inline]
3546 #[cfg(not(feature = "ferrocene_subset"))]
3547 fn cycle(self) -> Cycle<Self>
3548 where
3549 Self: Sized + Clone,
3550 {
3551 Cycle::new(self)
3552 }
3553
3554 /// Returns an iterator over `N` elements of the iterator at a time.
3555 ///
3556 /// The chunks do not overlap. If `N` does not divide the length of the
3557 /// iterator, then the last up to `N-1` elements will be omitted and can be
3558 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3559 /// function of the iterator.
3560 ///
3561 /// # Panics
3562 ///
3563 /// Panics if `N` is zero.
3564 ///
3565 /// # Examples
3566 ///
3567 /// Basic usage:
3568 ///
3569 /// ```
3570 /// #![feature(iter_array_chunks)]
3571 ///
3572 /// let mut iter = "lorem".chars().array_chunks();
3573 /// assert_eq!(iter.next(), Some(['l', 'o']));
3574 /// assert_eq!(iter.next(), Some(['r', 'e']));
3575 /// assert_eq!(iter.next(), None);
3576 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3577 /// ```
3578 ///
3579 /// ```
3580 /// #![feature(iter_array_chunks)]
3581 ///
3582 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3583 /// // ^-----^ ^------^
3584 /// for [x, y, z] in data.iter().array_chunks() {
3585 /// assert_eq!(x + y + z, 4);
3586 /// }
3587 /// ```
3588 #[track_caller]
3589 #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
3590 #[cfg(not(feature = "ferrocene_subset"))]
3591 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3592 where
3593 Self: Sized,
3594 {
3595 ArrayChunks::new(self)
3596 }
3597
3598 /// Sums the elements of an iterator.
3599 ///
3600 /// Takes each element, adds them together, and returns the result.
3601 ///
3602 /// An empty iterator returns the *additive identity* ("zero") of the type,
3603 /// which is `0` for integers and `-0.0` for floats.
3604 ///
3605 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3606 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3607 ///
3608 /// # Panics
3609 ///
3610 /// When calling `sum()` and a primitive integer type is being returned, this
3611 /// method will panic if the computation overflows and overflow checks are
3612 /// enabled.
3613 ///
3614 /// # Examples
3615 ///
3616 /// ```
3617 /// let a = [1, 2, 3];
3618 /// let sum: i32 = a.iter().sum();
3619 ///
3620 /// assert_eq!(sum, 6);
3621 ///
3622 /// let b: Vec<f32> = vec![];
3623 /// let sum: f32 = b.iter().sum();
3624 /// assert_eq!(sum, -0.0_f32);
3625 /// ```
3626 #[stable(feature = "iter_arith", since = "1.11.0")]
3627 fn sum<S>(self) -> S
3628 where
3629 Self: Sized,
3630 S: Sum<Self::Item>,
3631 {
3632 Sum::sum(self)
3633 }
3634
3635 /// Iterates over the entire iterator, multiplying all the elements
3636 ///
3637 /// An empty iterator returns the one value of the type.
3638 ///
3639 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3640 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3641 ///
3642 /// # Panics
3643 ///
3644 /// When calling `product()` and a primitive integer type is being returned,
3645 /// method will panic if the computation overflows and overflow checks are
3646 /// enabled.
3647 ///
3648 /// # Examples
3649 ///
3650 /// ```
3651 /// fn factorial(n: u32) -> u32 {
3652 /// (1..=n).product()
3653 /// }
3654 /// assert_eq!(factorial(0), 1);
3655 /// assert_eq!(factorial(1), 1);
3656 /// assert_eq!(factorial(5), 120);
3657 /// ```
3658 #[stable(feature = "iter_arith", since = "1.11.0")]
3659 #[cfg(not(feature = "ferrocene_subset"))]
3660 fn product<P>(self) -> P
3661 where
3662 Self: Sized,
3663 P: Product<Self::Item>,
3664 {
3665 Product::product(self)
3666 }
3667
3668 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3669 /// of another.
3670 ///
3671 /// # Examples
3672 ///
3673 /// ```
3674 /// use std::cmp::Ordering;
3675 ///
3676 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3677 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3678 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3679 /// ```
3680 #[stable(feature = "iter_order", since = "1.5.0")]
3681 #[cfg(not(feature = "ferrocene_subset"))]
3682 fn cmp<I>(self, other: I) -> Ordering
3683 where
3684 I: IntoIterator<Item = Self::Item>,
3685 Self::Item: Ord,
3686 Self: Sized,
3687 {
3688 self.cmp_by(other, |x, y| x.cmp(&y))
3689 }
3690
3691 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3692 /// of another with respect to the specified comparison function.
3693 ///
3694 /// # Examples
3695 ///
3696 /// ```
3697 /// #![feature(iter_order_by)]
3698 ///
3699 /// use std::cmp::Ordering;
3700 ///
3701 /// let xs = [1, 2, 3, 4];
3702 /// let ys = [1, 4, 9, 16];
3703 ///
3704 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3705 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3706 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3707 /// ```
3708 #[unstable(feature = "iter_order_by", issue = "64295")]
3709 #[cfg(not(feature = "ferrocene_subset"))]
3710 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3711 where
3712 Self: Sized,
3713 I: IntoIterator,
3714 F: FnMut(Self::Item, I::Item) -> Ordering,
3715 {
3716 #[inline]
3717 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3718 where
3719 F: FnMut(X, Y) -> Ordering,
3720 {
3721 move |x, y| match cmp(x, y) {
3722 Ordering::Equal => ControlFlow::Continue(()),
3723 non_eq => ControlFlow::Break(non_eq),
3724 }
3725 }
3726
3727 match iter_compare(self, other.into_iter(), compare(cmp)) {
3728 ControlFlow::Continue(ord) => ord,
3729 ControlFlow::Break(ord) => ord,
3730 }
3731 }
3732
3733 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3734 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3735 /// evaluation, returning a result without comparing the remaining elements.
3736 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3737 ///
3738 /// # Examples
3739 ///
3740 /// ```
3741 /// use std::cmp::Ordering;
3742 ///
3743 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3744 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3745 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3746 /// ```
3747 ///
3748 /// For floating-point numbers, NaN does not have a total order and will result
3749 /// in `None` when compared:
3750 ///
3751 /// ```
3752 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3753 /// ```
3754 ///
3755 /// The results are determined by the order of evaluation.
3756 ///
3757 /// ```
3758 /// use std::cmp::Ordering;
3759 ///
3760 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3761 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3762 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3763 /// ```
3764 ///
3765 #[stable(feature = "iter_order", since = "1.5.0")]
3766 #[cfg(not(feature = "ferrocene_subset"))]
3767 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3768 where
3769 I: IntoIterator,
3770 Self::Item: PartialOrd<I::Item>,
3771 Self: Sized,
3772 {
3773 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3774 }
3775
3776 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3777 /// of another with respect to the specified comparison function.
3778 ///
3779 /// # Examples
3780 ///
3781 /// ```
3782 /// #![feature(iter_order_by)]
3783 ///
3784 /// use std::cmp::Ordering;
3785 ///
3786 /// let xs = [1.0, 2.0, 3.0, 4.0];
3787 /// let ys = [1.0, 4.0, 9.0, 16.0];
3788 ///
3789 /// assert_eq!(
3790 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3791 /// Some(Ordering::Less)
3792 /// );
3793 /// assert_eq!(
3794 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3795 /// Some(Ordering::Equal)
3796 /// );
3797 /// assert_eq!(
3798 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3799 /// Some(Ordering::Greater)
3800 /// );
3801 /// ```
3802 #[unstable(feature = "iter_order_by", issue = "64295")]
3803 #[cfg(not(feature = "ferrocene_subset"))]
3804 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3805 where
3806 Self: Sized,
3807 I: IntoIterator,
3808 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3809 {
3810 #[inline]
3811 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3812 where
3813 F: FnMut(X, Y) -> Option<Ordering>,
3814 {
3815 move |x, y| match partial_cmp(x, y) {
3816 Some(Ordering::Equal) => ControlFlow::Continue(()),
3817 non_eq => ControlFlow::Break(non_eq),
3818 }
3819 }
3820
3821 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3822 ControlFlow::Continue(ord) => Some(ord),
3823 ControlFlow::Break(ord) => ord,
3824 }
3825 }
3826
3827 /// Determines if the elements of this [`Iterator`] are equal to those of
3828 /// another.
3829 ///
3830 /// # Examples
3831 ///
3832 /// ```
3833 /// assert_eq!([1].iter().eq([1].iter()), true);
3834 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3835 /// ```
3836 #[stable(feature = "iter_order", since = "1.5.0")]
3837 fn eq<I>(self, other: I) -> bool
3838 where
3839 I: IntoIterator,
3840 Self::Item: PartialEq<I::Item>,
3841 Self: Sized,
3842 {
3843 self.eq_by(other, |x, y| x == y)
3844 }
3845
3846 /// Determines if the elements of this [`Iterator`] are equal to those of
3847 /// another with respect to the specified equality function.
3848 ///
3849 /// # Examples
3850 ///
3851 /// ```
3852 /// #![feature(iter_order_by)]
3853 ///
3854 /// let xs = [1, 2, 3, 4];
3855 /// let ys = [1, 4, 9, 16];
3856 ///
3857 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3858 /// ```
3859 #[unstable(feature = "iter_order_by", issue = "64295")]
3860 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3861 where
3862 Self: Sized,
3863 I: IntoIterator,
3864 F: FnMut(Self::Item, I::Item) -> bool,
3865 {
3866 #[inline]
3867 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3868 where
3869 F: FnMut(X, Y) -> bool,
3870 {
3871 move |x, y| {
3872 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3873 }
3874 }
3875
3876 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3877 }
3878
3879 /// Determines if the elements of this [`Iterator`] are not equal to those of
3880 /// another.
3881 ///
3882 /// # Examples
3883 ///
3884 /// ```
3885 /// assert_eq!([1].iter().ne([1].iter()), false);
3886 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3887 /// ```
3888 #[stable(feature = "iter_order", since = "1.5.0")]
3889 #[cfg(not(feature = "ferrocene_subset"))]
3890 fn ne<I>(self, other: I) -> bool
3891 where
3892 I: IntoIterator,
3893 Self::Item: PartialEq<I::Item>,
3894 Self: Sized,
3895 {
3896 !self.eq(other)
3897 }
3898
3899 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3900 /// less than those of another.
3901 ///
3902 /// # Examples
3903 ///
3904 /// ```
3905 /// assert_eq!([1].iter().lt([1].iter()), false);
3906 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3907 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3908 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3909 /// ```
3910 #[stable(feature = "iter_order", since = "1.5.0")]
3911 #[cfg(not(feature = "ferrocene_subset"))]
3912 fn lt<I>(self, other: I) -> bool
3913 where
3914 I: IntoIterator,
3915 Self::Item: PartialOrd<I::Item>,
3916 Self: Sized,
3917 {
3918 self.partial_cmp(other) == Some(Ordering::Less)
3919 }
3920
3921 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3922 /// less or equal to those of another.
3923 ///
3924 /// # Examples
3925 ///
3926 /// ```
3927 /// assert_eq!([1].iter().le([1].iter()), true);
3928 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3929 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3930 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3931 /// ```
3932 #[stable(feature = "iter_order", since = "1.5.0")]
3933 #[cfg(not(feature = "ferrocene_subset"))]
3934 fn le<I>(self, other: I) -> bool
3935 where
3936 I: IntoIterator,
3937 Self::Item: PartialOrd<I::Item>,
3938 Self: Sized,
3939 {
3940 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3941 }
3942
3943 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3944 /// greater than those of another.
3945 ///
3946 /// # Examples
3947 ///
3948 /// ```
3949 /// assert_eq!([1].iter().gt([1].iter()), false);
3950 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3951 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3952 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3953 /// ```
3954 #[stable(feature = "iter_order", since = "1.5.0")]
3955 #[cfg(not(feature = "ferrocene_subset"))]
3956 fn gt<I>(self, other: I) -> bool
3957 where
3958 I: IntoIterator,
3959 Self::Item: PartialOrd<I::Item>,
3960 Self: Sized,
3961 {
3962 self.partial_cmp(other) == Some(Ordering::Greater)
3963 }
3964
3965 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3966 /// greater than or equal to those of another.
3967 ///
3968 /// # Examples
3969 ///
3970 /// ```
3971 /// assert_eq!([1].iter().ge([1].iter()), true);
3972 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3973 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3974 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3975 /// ```
3976 #[stable(feature = "iter_order", since = "1.5.0")]
3977 #[cfg(not(feature = "ferrocene_subset"))]
3978 fn ge<I>(self, other: I) -> bool
3979 where
3980 I: IntoIterator,
3981 Self::Item: PartialOrd<I::Item>,
3982 Self: Sized,
3983 {
3984 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3985 }
3986
3987 /// Checks if the elements of this iterator are sorted.
3988 ///
3989 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3990 /// iterator yields exactly zero or one element, `true` is returned.
3991 ///
3992 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3993 /// implies that this function returns `false` if any two consecutive items are not
3994 /// comparable.
3995 ///
3996 /// # Examples
3997 ///
3998 /// ```
3999 /// assert!([1, 2, 2, 9].iter().is_sorted());
4000 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4001 /// assert!([0].iter().is_sorted());
4002 /// assert!(std::iter::empty::<i32>().is_sorted());
4003 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4004 /// ```
4005 #[inline]
4006 #[stable(feature = "is_sorted", since = "1.82.0")]
4007 #[cfg(not(feature = "ferrocene_subset"))]
4008 fn is_sorted(self) -> bool
4009 where
4010 Self: Sized,
4011 Self::Item: PartialOrd,
4012 {
4013 self.is_sorted_by(|a, b| a <= b)
4014 }
4015
4016 /// Checks if the elements of this iterator are sorted using the given comparator function.
4017 ///
4018 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4019 /// function to determine whether two elements are to be considered in sorted order.
4020 ///
4021 /// # Examples
4022 ///
4023 /// ```
4024 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4025 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4026 ///
4027 /// assert!([0].iter().is_sorted_by(|a, b| true));
4028 /// assert!([0].iter().is_sorted_by(|a, b| false));
4029 ///
4030 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4031 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4032 /// ```
4033 #[stable(feature = "is_sorted", since = "1.82.0")]
4034 #[cfg(not(feature = "ferrocene_subset"))]
4035 fn is_sorted_by<F>(mut self, compare: F) -> bool
4036 where
4037 Self: Sized,
4038 F: FnMut(&Self::Item, &Self::Item) -> bool,
4039 {
4040 #[inline]
4041 fn check<'a, T>(
4042 last: &'a mut T,
4043 mut compare: impl FnMut(&T, &T) -> bool + 'a,
4044 ) -> impl FnMut(T) -> bool + 'a {
4045 move |curr| {
4046 if !compare(&last, &curr) {
4047 return false;
4048 }
4049 *last = curr;
4050 true
4051 }
4052 }
4053
4054 let mut last = match self.next() {
4055 Some(e) => e,
4056 None => return true,
4057 };
4058
4059 self.all(check(&mut last, compare))
4060 }
4061
4062 /// Checks if the elements of this iterator are sorted using the given key extraction
4063 /// function.
4064 ///
4065 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4066 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4067 /// its documentation for more information.
4068 ///
4069 /// [`is_sorted`]: Iterator::is_sorted
4070 ///
4071 /// # Examples
4072 ///
4073 /// ```
4074 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4075 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4076 /// ```
4077 #[inline]
4078 #[stable(feature = "is_sorted", since = "1.82.0")]
4079 #[cfg(not(feature = "ferrocene_subset"))]
4080 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4081 where
4082 Self: Sized,
4083 F: FnMut(Self::Item) -> K,
4084 K: PartialOrd,
4085 {
4086 self.map(f).is_sorted()
4087 }
4088
4089 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4090 // The unusual name is to avoid name collisions in method resolution
4091 // see #76479.
4092 #[inline]
4093 #[doc(hidden)]
4094 #[unstable(feature = "trusted_random_access", issue = "none")]
4095 #[cfg(not(feature = "ferrocene_subset"))]
4096 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4097 where
4098 Self: TrustedRandomAccessNoCoerce,
4099 {
4100 unreachable!("Always specialized");
4101 }
4102}
4103
4104trait SpecIterEq<B: Iterator>: Iterator {
4105 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4106 where
4107 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4108}
4109
4110impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4111 #[inline]
4112 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4113 where
4114 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4115 {
4116 iter_eq(self, b, f)
4117 }
4118}
4119
4120impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4121 #[inline]
4122 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4123 where
4124 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4125 {
4126 // we *can't* short-circuit if:
4127 match (self.size_hint(), b.size_hint()) {
4128 // ... both iterators have the same length
4129 ((_, Some(a)), (_, Some(b))) if a == b => {}
4130 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4131 ((_, None), (_, None)) => {}
4132 // otherwise, we can ascertain that they are unequal without actually comparing items
4133 _ => return false,
4134 }
4135
4136 iter_eq(self, b, f)
4137 }
4138}
4139
4140/// Compares two iterators element-wise using the given function.
4141///
4142/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4143/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4144/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4145/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4146/// the iterators.
4147///
4148/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4149/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4150#[inline]
4151fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4152where
4153 A: Iterator,
4154 B: Iterator,
4155 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4156{
4157 #[inline]
4158 fn compare<'a, B, X, T>(
4159 b: &'a mut B,
4160 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4161 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4162 where
4163 B: Iterator,
4164 {
4165 move |x| match b.next() {
4166 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4167 Some(y) => f(x, y).map_break(ControlFlow::Break),
4168 }
4169 }
4170
4171 match a.try_for_each(compare(&mut b, f)) {
4172 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4173 None => Ordering::Equal,
4174 Some(_) => Ordering::Less,
4175 }),
4176 ControlFlow::Break(x) => x,
4177 }
4178}
4179
4180#[inline]
4181fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4182where
4183 A: Iterator,
4184 B: Iterator,
4185 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4186{
4187 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4188}
4189
4190/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4191///
4192/// This implementation passes all method calls on to the original iterator.
4193#[stable(feature = "rust1", since = "1.0.0")]
4194impl<I: Iterator + ?Sized> Iterator for &mut I {
4195 type Item = I::Item;
4196 #[inline]
4197 fn next(&mut self) -> Option<I::Item> {
4198 (**self).next()
4199 }
4200 fn size_hint(&self) -> (usize, Option<usize>) {
4201 (**self).size_hint()
4202 }
4203 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4204 (**self).advance_by(n)
4205 }
4206 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4207 (**self).nth(n)
4208 }
4209 #[cfg(not(feature = "ferrocene_subset"))]
4210 fn fold<B, F>(self, init: B, f: F) -> B
4211 where
4212 F: FnMut(B, Self::Item) -> B,
4213 {
4214 self.spec_fold(init, f)
4215 }
4216 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4217 where
4218 F: FnMut(B, Self::Item) -> R,
4219 R: Try<Output = B>,
4220 {
4221 self.spec_try_fold(init, f)
4222 }
4223}
4224
4225/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4226trait IteratorRefSpec: Iterator {
4227 #[cfg(not(feature = "ferrocene_subset"))]
4228 fn spec_fold<B, F>(self, init: B, f: F) -> B
4229 where
4230 F: FnMut(B, Self::Item) -> B;
4231
4232 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4233 where
4234 F: FnMut(B, Self::Item) -> R,
4235 R: Try<Output = B>;
4236}
4237
4238impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4239 #[cfg(not(feature = "ferrocene_subset"))]
4240 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4241 where
4242 F: FnMut(B, Self::Item) -> B,
4243 {
4244 let mut accum = init;
4245 while let Some(x) = self.next() {
4246 accum = f(accum, x);
4247 }
4248 accum
4249 }
4250
4251 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4252 where
4253 F: FnMut(B, Self::Item) -> R,
4254 R: Try<Output = B>,
4255 {
4256 let mut accum = init;
4257 while let Some(x) = self.next() {
4258 accum = f(accum, x)?;
4259 }
4260 try { accum }
4261 }
4262}
4263
4264#[cfg(not(feature = "ferrocene_subset"))]
4265impl<I: Iterator> IteratorRefSpec for &mut I {
4266 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4267
4268 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4269 where
4270 F: FnMut(B, Self::Item) -> R,
4271 R: Try<Output = B>,
4272 {
4273 (**self).try_fold(init, f)
4274 }
4275}