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