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