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