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