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