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