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