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