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