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