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