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