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