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