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