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