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