]> git.proxmox.com Git - rustc.git/blob - library/core/src/iter/adapters/mod.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / library / core / src / iter / adapters / mod.rs
1 use crate::cmp;
2 use crate::fmt;
3 use crate::intrinsics;
4 use crate::ops::{Add, AddAssign, ControlFlow, Try};
5
6 use super::from_fn;
7 use super::{
8 DoubleEndedIterator, ExactSizeIterator, FusedIterator, InPlaceIterable, Iterator, TrustedLen,
9 };
10
11 mod chain;
12 mod flatten;
13 mod fuse;
14 mod zip;
15
16 pub use self::chain::Chain;
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub use self::flatten::{FlatMap, Flatten};
19 pub use self::fuse::Fuse;
20 use self::zip::try_get_unchecked;
21 #[unstable(feature = "trusted_random_access", issue = "none")]
22 pub use self::zip::TrustedRandomAccess;
23 pub use self::zip::Zip;
24
25 /// This trait provides transitive access to source-stage in an interator-adapter pipeline
26 /// under the conditions that
27 /// * the iterator source `S` itself implements `SourceIter<Source = S>`
28 /// * there is a delegating implementation of this trait for each adapter in the pipeline between
29 /// the source and the pipeline consumer.
30 ///
31 /// When the source is an owning iterator struct (commonly called `IntoIter`) then
32 /// this can be useful for specializing [`FromIterator`] implementations or recovering the
33 /// remaining elements after an iterator has been partially exhausted.
34 ///
35 /// Note that implementations do not necessarily have to provide access to the inner-most
36 /// source of a pipeline. A stateful intermediate adapter might eagerly evaluate a part
37 /// of the pipeline and expose its internal storage as source.
38 ///
39 /// The trait is unsafe because implementers must uphold additional safety properties.
40 /// See [`as_inner`] for details.
41 ///
42 /// # Examples
43 ///
44 /// Retrieving a partially consumed source:
45 ///
46 /// ```
47 /// # #![feature(inplace_iteration)]
48 /// # use std::iter::SourceIter;
49 ///
50 /// let mut iter = vec![9, 9, 9].into_iter().map(|i| i * i);
51 /// let _ = iter.next();
52 /// let mut remainder = std::mem::replace(unsafe { iter.as_inner() }, Vec::new().into_iter());
53 /// println!("n = {} elements remaining", remainder.len());
54 /// ```
55 ///
56 /// [`FromIterator`]: crate::iter::FromIterator
57 /// [`as_inner`]: SourceIter::as_inner
58 #[unstable(issue = "none", feature = "inplace_iteration")]
59 pub unsafe trait SourceIter {
60 /// A source stage in an iterator pipeline.
61 type Source: Iterator;
62
63 /// Retrieve the source of an iterator pipeline.
64 ///
65 /// # Safety
66 ///
67 /// Implementations of must return the same mutable reference for their lifetime, unless
68 /// replaced by a caller.
69 /// Callers may only replace the reference when they stopped iteration and drop the
70 /// iterator pipeline after extracting the source.
71 ///
72 /// This means iterator adapters can rely on the source not changing during
73 /// iteration but they cannot rely on it in their Drop implementations.
74 ///
75 /// Implementing this method means adapters relinquish private-only access to their
76 /// source and can only rely on guarantees made based on method receiver types.
77 /// The lack of restricted access also requires that adapters must uphold the source's
78 /// public API even when they have access to its internals.
79 ///
80 /// Callers in turn must expect the source to be in any state that is consistent with
81 /// its public API since adapters sitting between it and the source have the same
82 /// access. In particular an adapter may have consumed more elements than strictly necessary.
83 ///
84 /// The overall goal of these requirements is to let the consumer of a pipeline use
85 /// * whatever remains in the source after iteration has stopped
86 /// * the memory that has become unused by advancing a consuming iterator
87 ///
88 /// [`next()`]: trait.Iterator.html#method.next
89 unsafe fn as_inner(&mut self) -> &mut Self::Source;
90 }
91
92 /// A double-ended iterator with the direction inverted.
93 ///
94 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
95 /// documentation for more.
96 ///
97 /// [`rev`]: trait.Iterator.html#method.rev
98 /// [`Iterator`]: trait.Iterator.html
99 #[derive(Clone, Debug)]
100 #[must_use = "iterators are lazy and do nothing unless consumed"]
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub struct Rev<T> {
103 iter: T,
104 }
105 impl<T> Rev<T> {
106 pub(super) fn new(iter: T) -> Rev<T> {
107 Rev { iter }
108 }
109 }
110
111 #[stable(feature = "rust1", since = "1.0.0")]
112 impl<I> Iterator for Rev<I>
113 where
114 I: DoubleEndedIterator,
115 {
116 type Item = <I as Iterator>::Item;
117
118 #[inline]
119 fn next(&mut self) -> Option<<I as Iterator>::Item> {
120 self.iter.next_back()
121 }
122 #[inline]
123 fn size_hint(&self) -> (usize, Option<usize>) {
124 self.iter.size_hint()
125 }
126
127 #[inline]
128 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
129 self.iter.advance_back_by(n)
130 }
131
132 #[inline]
133 fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
134 self.iter.nth_back(n)
135 }
136
137 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
138 where
139 Self: Sized,
140 F: FnMut(B, Self::Item) -> R,
141 R: Try<Ok = B>,
142 {
143 self.iter.try_rfold(init, f)
144 }
145
146 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
147 where
148 F: FnMut(Acc, Self::Item) -> Acc,
149 {
150 self.iter.rfold(init, f)
151 }
152
153 #[inline]
154 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
155 where
156 P: FnMut(&Self::Item) -> bool,
157 {
158 self.iter.rfind(predicate)
159 }
160 }
161
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl<I> DoubleEndedIterator for Rev<I>
164 where
165 I: DoubleEndedIterator,
166 {
167 #[inline]
168 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
169 self.iter.next()
170 }
171
172 #[inline]
173 fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
174 self.iter.advance_by(n)
175 }
176
177 #[inline]
178 fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
179 self.iter.nth(n)
180 }
181
182 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
183 where
184 Self: Sized,
185 F: FnMut(B, Self::Item) -> R,
186 R: Try<Ok = B>,
187 {
188 self.iter.try_fold(init, f)
189 }
190
191 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
192 where
193 F: FnMut(Acc, Self::Item) -> Acc,
194 {
195 self.iter.fold(init, f)
196 }
197
198 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
199 where
200 P: FnMut(&Self::Item) -> bool,
201 {
202 self.iter.find(predicate)
203 }
204 }
205
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<I> ExactSizeIterator for Rev<I>
208 where
209 I: ExactSizeIterator + DoubleEndedIterator,
210 {
211 fn len(&self) -> usize {
212 self.iter.len()
213 }
214
215 fn is_empty(&self) -> bool {
216 self.iter.is_empty()
217 }
218 }
219
220 #[stable(feature = "fused", since = "1.26.0")]
221 impl<I> FusedIterator for Rev<I> where I: FusedIterator + DoubleEndedIterator {}
222
223 #[unstable(feature = "trusted_len", issue = "37572")]
224 unsafe impl<I> TrustedLen for Rev<I> where I: TrustedLen + DoubleEndedIterator {}
225
226 /// An iterator that copies the elements of an underlying iterator.
227 ///
228 /// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
229 /// documentation for more.
230 ///
231 /// [`copied`]: trait.Iterator.html#method.copied
232 /// [`Iterator`]: trait.Iterator.html
233 #[stable(feature = "iter_copied", since = "1.36.0")]
234 #[must_use = "iterators are lazy and do nothing unless consumed"]
235 #[derive(Clone, Debug)]
236 pub struct Copied<I> {
237 it: I,
238 }
239
240 impl<I> Copied<I> {
241 pub(super) fn new(it: I) -> Copied<I> {
242 Copied { it }
243 }
244 }
245
246 fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
247 move |acc, &elt| f(acc, elt)
248 }
249
250 fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
251 move |acc, &elt| f(acc, elt)
252 }
253
254 #[stable(feature = "iter_copied", since = "1.36.0")]
255 impl<'a, I, T: 'a> Iterator for Copied<I>
256 where
257 I: Iterator<Item = &'a T>,
258 T: Copy,
259 {
260 type Item = T;
261
262 fn next(&mut self) -> Option<T> {
263 self.it.next().copied()
264 }
265
266 fn size_hint(&self) -> (usize, Option<usize>) {
267 self.it.size_hint()
268 }
269
270 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
271 where
272 Self: Sized,
273 F: FnMut(B, Self::Item) -> R,
274 R: Try<Ok = B>,
275 {
276 self.it.try_fold(init, copy_try_fold(f))
277 }
278
279 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
280 where
281 F: FnMut(Acc, Self::Item) -> Acc,
282 {
283 self.it.fold(init, copy_fold(f))
284 }
285
286 fn nth(&mut self, n: usize) -> Option<T> {
287 self.it.nth(n).copied()
288 }
289
290 fn last(self) -> Option<T> {
291 self.it.last().copied()
292 }
293
294 fn count(self) -> usize {
295 self.it.count()
296 }
297
298 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
299 where
300 Self: TrustedRandomAccess,
301 {
302 // SAFETY: the caller must uphold the contract for
303 // `Iterator::__iterator_get_unchecked`.
304 *unsafe { try_get_unchecked(&mut self.it, idx) }
305 }
306 }
307
308 #[stable(feature = "iter_copied", since = "1.36.0")]
309 impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
310 where
311 I: DoubleEndedIterator<Item = &'a T>,
312 T: Copy,
313 {
314 fn next_back(&mut self) -> Option<T> {
315 self.it.next_back().copied()
316 }
317
318 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
319 where
320 Self: Sized,
321 F: FnMut(B, Self::Item) -> R,
322 R: Try<Ok = B>,
323 {
324 self.it.try_rfold(init, copy_try_fold(f))
325 }
326
327 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
328 where
329 F: FnMut(Acc, Self::Item) -> Acc,
330 {
331 self.it.rfold(init, copy_fold(f))
332 }
333 }
334
335 #[stable(feature = "iter_copied", since = "1.36.0")]
336 impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
337 where
338 I: ExactSizeIterator<Item = &'a T>,
339 T: Copy,
340 {
341 fn len(&self) -> usize {
342 self.it.len()
343 }
344
345 fn is_empty(&self) -> bool {
346 self.it.is_empty()
347 }
348 }
349
350 #[stable(feature = "iter_copied", since = "1.36.0")]
351 impl<'a, I, T: 'a> FusedIterator for Copied<I>
352 where
353 I: FusedIterator<Item = &'a T>,
354 T: Copy,
355 {
356 }
357
358 #[doc(hidden)]
359 #[unstable(feature = "trusted_random_access", issue = "none")]
360 unsafe impl<I> TrustedRandomAccess for Copied<I>
361 where
362 I: TrustedRandomAccess,
363 {
364 #[inline]
365 fn may_have_side_effect() -> bool {
366 I::may_have_side_effect()
367 }
368 }
369
370 #[stable(feature = "iter_copied", since = "1.36.0")]
371 unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
372 where
373 I: TrustedLen<Item = &'a T>,
374 T: Copy,
375 {
376 }
377
378 /// An iterator that clones the elements of an underlying iterator.
379 ///
380 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
381 /// documentation for more.
382 ///
383 /// [`cloned`]: trait.Iterator.html#method.cloned
384 /// [`Iterator`]: trait.Iterator.html
385 #[stable(feature = "iter_cloned", since = "1.1.0")]
386 #[must_use = "iterators are lazy and do nothing unless consumed"]
387 #[derive(Clone, Debug)]
388 pub struct Cloned<I> {
389 it: I,
390 }
391 impl<I> Cloned<I> {
392 pub(super) fn new(it: I) -> Cloned<I> {
393 Cloned { it }
394 }
395 }
396
397 fn clone_try_fold<T: Clone, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
398 move |acc, elt| f(acc, elt.clone())
399 }
400
401 #[stable(feature = "iter_cloned", since = "1.1.0")]
402 impl<'a, I, T: 'a> Iterator for Cloned<I>
403 where
404 I: Iterator<Item = &'a T>,
405 T: Clone,
406 {
407 type Item = T;
408
409 fn next(&mut self) -> Option<T> {
410 self.it.next().cloned()
411 }
412
413 fn size_hint(&self) -> (usize, Option<usize>) {
414 self.it.size_hint()
415 }
416
417 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
418 where
419 Self: Sized,
420 F: FnMut(B, Self::Item) -> R,
421 R: Try<Ok = B>,
422 {
423 self.it.try_fold(init, clone_try_fold(f))
424 }
425
426 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
427 where
428 F: FnMut(Acc, Self::Item) -> Acc,
429 {
430 self.it.map(T::clone).fold(init, f)
431 }
432
433 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> T
434 where
435 Self: TrustedRandomAccess,
436 {
437 // SAFETY: the caller must uphold the contract for
438 // `Iterator::__iterator_get_unchecked`.
439 unsafe { try_get_unchecked(&mut self.it, idx).clone() }
440 }
441 }
442
443 #[stable(feature = "iter_cloned", since = "1.1.0")]
444 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
445 where
446 I: DoubleEndedIterator<Item = &'a T>,
447 T: Clone,
448 {
449 fn next_back(&mut self) -> Option<T> {
450 self.it.next_back().cloned()
451 }
452
453 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
454 where
455 Self: Sized,
456 F: FnMut(B, Self::Item) -> R,
457 R: Try<Ok = B>,
458 {
459 self.it.try_rfold(init, clone_try_fold(f))
460 }
461
462 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
463 where
464 F: FnMut(Acc, Self::Item) -> Acc,
465 {
466 self.it.map(T::clone).rfold(init, f)
467 }
468 }
469
470 #[stable(feature = "iter_cloned", since = "1.1.0")]
471 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
472 where
473 I: ExactSizeIterator<Item = &'a T>,
474 T: Clone,
475 {
476 fn len(&self) -> usize {
477 self.it.len()
478 }
479
480 fn is_empty(&self) -> bool {
481 self.it.is_empty()
482 }
483 }
484
485 #[stable(feature = "fused", since = "1.26.0")]
486 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
487 where
488 I: FusedIterator<Item = &'a T>,
489 T: Clone,
490 {
491 }
492
493 #[doc(hidden)]
494 #[unstable(feature = "trusted_random_access", issue = "none")]
495 unsafe impl<I> TrustedRandomAccess for Cloned<I>
496 where
497 I: TrustedRandomAccess,
498 {
499 #[inline]
500 fn may_have_side_effect() -> bool {
501 true
502 }
503 }
504
505 #[unstable(feature = "trusted_len", issue = "37572")]
506 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
507 where
508 I: TrustedLen<Item = &'a T>,
509 T: Clone,
510 {
511 }
512
513 /// An iterator that repeats endlessly.
514 ///
515 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
516 /// documentation for more.
517 ///
518 /// [`cycle`]: trait.Iterator.html#method.cycle
519 /// [`Iterator`]: trait.Iterator.html
520 #[derive(Clone, Debug)]
521 #[must_use = "iterators are lazy and do nothing unless consumed"]
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub struct Cycle<I> {
524 orig: I,
525 iter: I,
526 }
527 impl<I: Clone> Cycle<I> {
528 pub(super) fn new(iter: I) -> Cycle<I> {
529 Cycle { orig: iter.clone(), iter }
530 }
531 }
532
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<I> Iterator for Cycle<I>
535 where
536 I: Clone + Iterator,
537 {
538 type Item = <I as Iterator>::Item;
539
540 #[inline]
541 fn next(&mut self) -> Option<<I as Iterator>::Item> {
542 match self.iter.next() {
543 None => {
544 self.iter = self.orig.clone();
545 self.iter.next()
546 }
547 y => y,
548 }
549 }
550
551 #[inline]
552 fn size_hint(&self) -> (usize, Option<usize>) {
553 // the cycle iterator is either empty or infinite
554 match self.orig.size_hint() {
555 sz @ (0, Some(0)) => sz,
556 (0, _) => (0, None),
557 _ => (usize::MAX, None),
558 }
559 }
560
561 #[inline]
562 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
563 where
564 F: FnMut(Acc, Self::Item) -> R,
565 R: Try<Ok = Acc>,
566 {
567 // fully iterate the current iterator. this is necessary because
568 // `self.iter` may be empty even when `self.orig` isn't
569 acc = self.iter.try_fold(acc, &mut f)?;
570 self.iter = self.orig.clone();
571
572 // complete a full cycle, keeping track of whether the cycled
573 // iterator is empty or not. we need to return early in case
574 // of an empty iterator to prevent an infinite loop
575 let mut is_empty = true;
576 acc = self.iter.try_fold(acc, |acc, x| {
577 is_empty = false;
578 f(acc, x)
579 })?;
580
581 if is_empty {
582 return Try::from_ok(acc);
583 }
584
585 loop {
586 self.iter = self.orig.clone();
587 acc = self.iter.try_fold(acc, &mut f)?;
588 }
589 }
590
591 // No `fold` override, because `fold` doesn't make much sense for `Cycle`,
592 // and we can't do anything better than the default.
593 }
594
595 #[stable(feature = "fused", since = "1.26.0")]
596 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
597
598 /// An iterator for stepping iterators by a custom amount.
599 ///
600 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
601 /// its documentation for more.
602 ///
603 /// [`step_by`]: trait.Iterator.html#method.step_by
604 /// [`Iterator`]: trait.Iterator.html
605 #[must_use = "iterators are lazy and do nothing unless consumed"]
606 #[stable(feature = "iterator_step_by", since = "1.28.0")]
607 #[derive(Clone, Debug)]
608 pub struct StepBy<I> {
609 iter: I,
610 step: usize,
611 first_take: bool,
612 }
613 impl<I> StepBy<I> {
614 pub(super) fn new(iter: I, step: usize) -> StepBy<I> {
615 assert!(step != 0);
616 StepBy { iter, step: step - 1, first_take: true }
617 }
618 }
619
620 #[stable(feature = "iterator_step_by", since = "1.28.0")]
621 impl<I> Iterator for StepBy<I>
622 where
623 I: Iterator,
624 {
625 type Item = I::Item;
626
627 #[inline]
628 fn next(&mut self) -> Option<Self::Item> {
629 if self.first_take {
630 self.first_take = false;
631 self.iter.next()
632 } else {
633 self.iter.nth(self.step)
634 }
635 }
636
637 #[inline]
638 fn size_hint(&self) -> (usize, Option<usize>) {
639 #[inline]
640 fn first_size(step: usize) -> impl Fn(usize) -> usize {
641 move |n| if n == 0 { 0 } else { 1 + (n - 1) / (step + 1) }
642 }
643
644 #[inline]
645 fn other_size(step: usize) -> impl Fn(usize) -> usize {
646 move |n| n / (step + 1)
647 }
648
649 let (low, high) = self.iter.size_hint();
650
651 if self.first_take {
652 let f = first_size(self.step);
653 (f(low), high.map(f))
654 } else {
655 let f = other_size(self.step);
656 (f(low), high.map(f))
657 }
658 }
659
660 #[inline]
661 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
662 if self.first_take {
663 self.first_take = false;
664 let first = self.iter.next();
665 if n == 0 {
666 return first;
667 }
668 n -= 1;
669 }
670 // n and self.step are indices, we need to add 1 to get the amount of elements
671 // When calling `.nth`, we need to subtract 1 again to convert back to an index
672 // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
673 let mut step = self.step + 1;
674 // n + 1 could overflow
675 // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
676 if n == usize::MAX {
677 self.iter.nth(step - 1);
678 } else {
679 n += 1;
680 }
681
682 // overflow handling
683 loop {
684 let mul = n.checked_mul(step);
685 {
686 if intrinsics::likely(mul.is_some()) {
687 return self.iter.nth(mul.unwrap() - 1);
688 }
689 }
690 let div_n = usize::MAX / n;
691 let div_step = usize::MAX / step;
692 let nth_n = div_n * n;
693 let nth_step = div_step * step;
694 let nth = if nth_n > nth_step {
695 step -= div_n;
696 nth_n
697 } else {
698 n -= div_step;
699 nth_step
700 };
701 self.iter.nth(nth - 1);
702 }
703 }
704
705 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
706 where
707 F: FnMut(Acc, Self::Item) -> R,
708 R: Try<Ok = Acc>,
709 {
710 #[inline]
711 fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
712 move || iter.nth(step)
713 }
714
715 if self.first_take {
716 self.first_take = false;
717 match self.iter.next() {
718 None => return Try::from_ok(acc),
719 Some(x) => acc = f(acc, x)?,
720 }
721 }
722 from_fn(nth(&mut self.iter, self.step)).try_fold(acc, f)
723 }
724
725 fn fold<Acc, F>(mut self, mut acc: Acc, mut f: F) -> Acc
726 where
727 F: FnMut(Acc, Self::Item) -> Acc,
728 {
729 #[inline]
730 fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
731 move || iter.nth(step)
732 }
733
734 if self.first_take {
735 self.first_take = false;
736 match self.iter.next() {
737 None => return acc,
738 Some(x) => acc = f(acc, x),
739 }
740 }
741 from_fn(nth(&mut self.iter, self.step)).fold(acc, f)
742 }
743 }
744
745 impl<I> StepBy<I>
746 where
747 I: ExactSizeIterator,
748 {
749 // The zero-based index starting from the end of the iterator of the
750 // last element. Used in the `DoubleEndedIterator` implementation.
751 fn next_back_index(&self) -> usize {
752 let rem = self.iter.len() % (self.step + 1);
753 if self.first_take {
754 if rem == 0 { self.step } else { rem - 1 }
755 } else {
756 rem
757 }
758 }
759 }
760
761 #[stable(feature = "double_ended_step_by_iterator", since = "1.38.0")]
762 impl<I> DoubleEndedIterator for StepBy<I>
763 where
764 I: DoubleEndedIterator + ExactSizeIterator,
765 {
766 #[inline]
767 fn next_back(&mut self) -> Option<Self::Item> {
768 self.iter.nth_back(self.next_back_index())
769 }
770
771 #[inline]
772 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
773 // `self.iter.nth_back(usize::MAX)` does the right thing here when `n`
774 // is out of bounds because the length of `self.iter` does not exceed
775 // `usize::MAX` (because `I: ExactSizeIterator`) and `nth_back` is
776 // zero-indexed
777 let n = n.saturating_mul(self.step + 1).saturating_add(self.next_back_index());
778 self.iter.nth_back(n)
779 }
780
781 fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R
782 where
783 F: FnMut(Acc, Self::Item) -> R,
784 R: Try<Ok = Acc>,
785 {
786 #[inline]
787 fn nth_back<I: DoubleEndedIterator>(
788 iter: &mut I,
789 step: usize,
790 ) -> impl FnMut() -> Option<I::Item> + '_ {
791 move || iter.nth_back(step)
792 }
793
794 match self.next_back() {
795 None => Try::from_ok(init),
796 Some(x) => {
797 let acc = f(init, x)?;
798 from_fn(nth_back(&mut self.iter, self.step)).try_fold(acc, f)
799 }
800 }
801 }
802
803 #[inline]
804 fn rfold<Acc, F>(mut self, init: Acc, mut f: F) -> Acc
805 where
806 Self: Sized,
807 F: FnMut(Acc, Self::Item) -> Acc,
808 {
809 #[inline]
810 fn nth_back<I: DoubleEndedIterator>(
811 iter: &mut I,
812 step: usize,
813 ) -> impl FnMut() -> Option<I::Item> + '_ {
814 move || iter.nth_back(step)
815 }
816
817 match self.next_back() {
818 None => init,
819 Some(x) => {
820 let acc = f(init, x);
821 from_fn(nth_back(&mut self.iter, self.step)).fold(acc, f)
822 }
823 }
824 }
825 }
826
827 // StepBy can only make the iterator shorter, so the len will still fit.
828 #[stable(feature = "iterator_step_by", since = "1.28.0")]
829 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
830
831 /// An iterator that maps the values of `iter` with `f`.
832 ///
833 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
834 /// documentation for more.
835 ///
836 /// [`map`]: trait.Iterator.html#method.map
837 /// [`Iterator`]: trait.Iterator.html
838 ///
839 /// # Notes about side effects
840 ///
841 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
842 /// you can also [`map`] backwards:
843 ///
844 /// ```rust
845 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
846 ///
847 /// assert_eq!(v, [4, 3, 2]);
848 /// ```
849 ///
850 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
851 ///
852 /// But if your closure has state, iterating backwards may act in a way you do
853 /// not expect. Let's go through an example. First, in the forward direction:
854 ///
855 /// ```rust
856 /// let mut c = 0;
857 ///
858 /// for pair in vec!['a', 'b', 'c'].into_iter()
859 /// .map(|letter| { c += 1; (letter, c) }) {
860 /// println!("{:?}", pair);
861 /// }
862 /// ```
863 ///
864 /// This will print "('a', 1), ('b', 2), ('c', 3)".
865 ///
866 /// Now consider this twist where we add a call to `rev`. This version will
867 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
868 /// but the values of the counter still go in order. This is because `map()` is
869 /// still being called lazily on each item, but we are popping items off the
870 /// back of the vector now, instead of shifting them from the front.
871 ///
872 /// ```rust
873 /// let mut c = 0;
874 ///
875 /// for pair in vec!['a', 'b', 'c'].into_iter()
876 /// .map(|letter| { c += 1; (letter, c) })
877 /// .rev() {
878 /// println!("{:?}", pair);
879 /// }
880 /// ```
881 #[must_use = "iterators are lazy and do nothing unless consumed"]
882 #[stable(feature = "rust1", since = "1.0.0")]
883 #[derive(Clone)]
884 pub struct Map<I, F> {
885 iter: I,
886 f: F,
887 }
888 impl<I, F> Map<I, F> {
889 pub(super) fn new(iter: I, f: F) -> Map<I, F> {
890 Map { iter, f }
891 }
892 }
893
894 #[stable(feature = "core_impl_debug", since = "1.9.0")]
895 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897 f.debug_struct("Map").field("iter", &self.iter).finish()
898 }
899 }
900
901 fn map_fold<T, B, Acc>(
902 mut f: impl FnMut(T) -> B,
903 mut g: impl FnMut(Acc, B) -> Acc,
904 ) -> impl FnMut(Acc, T) -> Acc {
905 move |acc, elt| g(acc, f(elt))
906 }
907
908 fn map_try_fold<'a, T, B, Acc, R>(
909 f: &'a mut impl FnMut(T) -> B,
910 mut g: impl FnMut(Acc, B) -> R + 'a,
911 ) -> impl FnMut(Acc, T) -> R + 'a {
912 move |acc, elt| g(acc, f(elt))
913 }
914
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl<B, I: Iterator, F> Iterator for Map<I, F>
917 where
918 F: FnMut(I::Item) -> B,
919 {
920 type Item = B;
921
922 #[inline]
923 fn next(&mut self) -> Option<B> {
924 self.iter.next().map(&mut self.f)
925 }
926
927 #[inline]
928 fn size_hint(&self) -> (usize, Option<usize>) {
929 self.iter.size_hint()
930 }
931
932 fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
933 where
934 Self: Sized,
935 G: FnMut(Acc, Self::Item) -> R,
936 R: Try<Ok = Acc>,
937 {
938 self.iter.try_fold(init, map_try_fold(&mut self.f, g))
939 }
940
941 fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
942 where
943 G: FnMut(Acc, Self::Item) -> Acc,
944 {
945 self.iter.fold(init, map_fold(self.f, g))
946 }
947
948 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B
949 where
950 Self: TrustedRandomAccess,
951 {
952 // SAFETY: the caller must uphold the contract for
953 // `Iterator::__iterator_get_unchecked`.
954 unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
955 }
956 }
957
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
960 where
961 F: FnMut(I::Item) -> B,
962 {
963 #[inline]
964 fn next_back(&mut self) -> Option<B> {
965 self.iter.next_back().map(&mut self.f)
966 }
967
968 fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
969 where
970 Self: Sized,
971 G: FnMut(Acc, Self::Item) -> R,
972 R: Try<Ok = Acc>,
973 {
974 self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
975 }
976
977 fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
978 where
979 G: FnMut(Acc, Self::Item) -> Acc,
980 {
981 self.iter.rfold(init, map_fold(self.f, g))
982 }
983 }
984
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
987 where
988 F: FnMut(I::Item) -> B,
989 {
990 fn len(&self) -> usize {
991 self.iter.len()
992 }
993
994 fn is_empty(&self) -> bool {
995 self.iter.is_empty()
996 }
997 }
998
999 #[stable(feature = "fused", since = "1.26.0")]
1000 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
1001
1002 #[unstable(feature = "trusted_len", issue = "37572")]
1003 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1004 where
1005 I: TrustedLen,
1006 F: FnMut(I::Item) -> B,
1007 {
1008 }
1009
1010 #[doc(hidden)]
1011 #[unstable(feature = "trusted_random_access", issue = "none")]
1012 unsafe impl<I, F> TrustedRandomAccess for Map<I, F>
1013 where
1014 I: TrustedRandomAccess,
1015 {
1016 #[inline]
1017 fn may_have_side_effect() -> bool {
1018 true
1019 }
1020 }
1021
1022 #[unstable(issue = "none", feature = "inplace_iteration")]
1023 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for Map<I, F>
1024 where
1025 F: FnMut(I::Item) -> B,
1026 I: SourceIter<Source = S>,
1027 {
1028 type Source = S;
1029
1030 #[inline]
1031 unsafe fn as_inner(&mut self) -> &mut S {
1032 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1033 unsafe { SourceIter::as_inner(&mut self.iter) }
1034 }
1035 }
1036
1037 #[unstable(issue = "none", feature = "inplace_iteration")]
1038 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for Map<I, F> where F: FnMut(I::Item) -> B {}
1039
1040 /// An iterator that filters the elements of `iter` with `predicate`.
1041 ///
1042 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1043 /// documentation for more.
1044 ///
1045 /// [`filter`]: trait.Iterator.html#method.filter
1046 /// [`Iterator`]: trait.Iterator.html
1047 #[must_use = "iterators are lazy and do nothing unless consumed"]
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 #[derive(Clone)]
1050 pub struct Filter<I, P> {
1051 iter: I,
1052 predicate: P,
1053 }
1054 impl<I, P> Filter<I, P> {
1055 pub(super) fn new(iter: I, predicate: P) -> Filter<I, P> {
1056 Filter { iter, predicate }
1057 }
1058 }
1059
1060 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1061 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 f.debug_struct("Filter").field("iter", &self.iter).finish()
1064 }
1065 }
1066
1067 fn filter_fold<T, Acc>(
1068 mut predicate: impl FnMut(&T) -> bool,
1069 mut fold: impl FnMut(Acc, T) -> Acc,
1070 ) -> impl FnMut(Acc, T) -> Acc {
1071 move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
1072 }
1073
1074 fn filter_try_fold<'a, T, Acc, R: Try<Ok = Acc>>(
1075 predicate: &'a mut impl FnMut(&T) -> bool,
1076 mut fold: impl FnMut(Acc, T) -> R + 'a,
1077 ) -> impl FnMut(Acc, T) -> R + 'a {
1078 move |acc, item| if predicate(&item) { fold(acc, item) } else { R::from_ok(acc) }
1079 }
1080
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<I: Iterator, P> Iterator for Filter<I, P>
1083 where
1084 P: FnMut(&I::Item) -> bool,
1085 {
1086 type Item = I::Item;
1087
1088 #[inline]
1089 fn next(&mut self) -> Option<I::Item> {
1090 self.iter.find(&mut self.predicate)
1091 }
1092
1093 #[inline]
1094 fn size_hint(&self) -> (usize, Option<usize>) {
1095 let (_, upper) = self.iter.size_hint();
1096 (0, upper) // can't know a lower bound, due to the predicate
1097 }
1098
1099 // this special case allows the compiler to make `.filter(_).count()`
1100 // branchless. Barring perfect branch prediction (which is unattainable in
1101 // the general case), this will be much faster in >90% of cases (containing
1102 // virtually all real workloads) and only a tiny bit slower in the rest.
1103 //
1104 // Having this specialization thus allows us to write `.filter(p).count()`
1105 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1106 // less readable and also less backwards-compatible to Rust before 1.10.
1107 //
1108 // Using the branchless version will also simplify the LLVM byte code, thus
1109 // leaving more budget for LLVM optimizations.
1110 #[inline]
1111 fn count(self) -> usize {
1112 #[inline]
1113 fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
1114 move |x| predicate(&x) as usize
1115 }
1116
1117 self.iter.map(to_usize(self.predicate)).sum()
1118 }
1119
1120 #[inline]
1121 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1122 where
1123 Self: Sized,
1124 Fold: FnMut(Acc, Self::Item) -> R,
1125 R: Try<Ok = Acc>,
1126 {
1127 self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
1128 }
1129
1130 #[inline]
1131 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1132 where
1133 Fold: FnMut(Acc, Self::Item) -> Acc,
1134 {
1135 self.iter.fold(init, filter_fold(self.predicate, fold))
1136 }
1137 }
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1141 where
1142 P: FnMut(&I::Item) -> bool,
1143 {
1144 #[inline]
1145 fn next_back(&mut self) -> Option<I::Item> {
1146 self.iter.rfind(&mut self.predicate)
1147 }
1148
1149 #[inline]
1150 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1151 where
1152 Self: Sized,
1153 Fold: FnMut(Acc, Self::Item) -> R,
1154 R: Try<Ok = Acc>,
1155 {
1156 self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
1157 }
1158
1159 #[inline]
1160 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1161 where
1162 Fold: FnMut(Acc, Self::Item) -> Acc,
1163 {
1164 self.iter.rfold(init, filter_fold(self.predicate, fold))
1165 }
1166 }
1167
1168 #[stable(feature = "fused", since = "1.26.0")]
1169 impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1170
1171 #[unstable(issue = "none", feature = "inplace_iteration")]
1172 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P>
1173 where
1174 P: FnMut(&I::Item) -> bool,
1175 I: SourceIter<Source = S>,
1176 {
1177 type Source = S;
1178
1179 #[inline]
1180 unsafe fn as_inner(&mut self) -> &mut S {
1181 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1182 unsafe { SourceIter::as_inner(&mut self.iter) }
1183 }
1184 }
1185
1186 #[unstable(issue = "none", feature = "inplace_iteration")]
1187 unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1188
1189 /// An iterator that uses `f` to both filter and map elements from `iter`.
1190 ///
1191 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1192 /// documentation for more.
1193 ///
1194 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1195 /// [`Iterator`]: trait.Iterator.html
1196 #[must_use = "iterators are lazy and do nothing unless consumed"]
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 #[derive(Clone)]
1199 pub struct FilterMap<I, F> {
1200 iter: I,
1201 f: F,
1202 }
1203 impl<I, F> FilterMap<I, F> {
1204 pub(super) fn new(iter: I, f: F) -> FilterMap<I, F> {
1205 FilterMap { iter, f }
1206 }
1207 }
1208
1209 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1210 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1212 f.debug_struct("FilterMap").field("iter", &self.iter).finish()
1213 }
1214 }
1215
1216 fn filter_map_fold<T, B, Acc>(
1217 mut f: impl FnMut(T) -> Option<B>,
1218 mut fold: impl FnMut(Acc, B) -> Acc,
1219 ) -> impl FnMut(Acc, T) -> Acc {
1220 move |acc, item| match f(item) {
1221 Some(x) => fold(acc, x),
1222 None => acc,
1223 }
1224 }
1225
1226 fn filter_map_try_fold<'a, T, B, Acc, R: Try<Ok = Acc>>(
1227 f: &'a mut impl FnMut(T) -> Option<B>,
1228 mut fold: impl FnMut(Acc, B) -> R + 'a,
1229 ) -> impl FnMut(Acc, T) -> R + 'a {
1230 move |acc, item| match f(item) {
1231 Some(x) => fold(acc, x),
1232 None => R::from_ok(acc),
1233 }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1238 where
1239 F: FnMut(I::Item) -> Option<B>,
1240 {
1241 type Item = B;
1242
1243 #[inline]
1244 fn next(&mut self) -> Option<B> {
1245 self.iter.find_map(&mut self.f)
1246 }
1247
1248 #[inline]
1249 fn size_hint(&self) -> (usize, Option<usize>) {
1250 let (_, upper) = self.iter.size_hint();
1251 (0, upper) // can't know a lower bound, due to the predicate
1252 }
1253
1254 #[inline]
1255 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1256 where
1257 Self: Sized,
1258 Fold: FnMut(Acc, Self::Item) -> R,
1259 R: Try<Ok = Acc>,
1260 {
1261 self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold))
1262 }
1263
1264 #[inline]
1265 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1266 where
1267 Fold: FnMut(Acc, Self::Item) -> Acc,
1268 {
1269 self.iter.fold(init, filter_map_fold(self.f, fold))
1270 }
1271 }
1272
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1275 where
1276 F: FnMut(I::Item) -> Option<B>,
1277 {
1278 #[inline]
1279 fn next_back(&mut self) -> Option<B> {
1280 #[inline]
1281 fn find<T, B>(
1282 f: &mut impl FnMut(T) -> Option<B>,
1283 ) -> impl FnMut((), T) -> ControlFlow<(), B> + '_ {
1284 move |(), x| match f(x) {
1285 Some(x) => ControlFlow::Break(x),
1286 None => ControlFlow::CONTINUE,
1287 }
1288 }
1289
1290 self.iter.try_rfold((), find(&mut self.f)).break_value()
1291 }
1292
1293 #[inline]
1294 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1295 where
1296 Self: Sized,
1297 Fold: FnMut(Acc, Self::Item) -> R,
1298 R: Try<Ok = Acc>,
1299 {
1300 self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold))
1301 }
1302
1303 #[inline]
1304 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1305 where
1306 Fold: FnMut(Acc, Self::Item) -> Acc,
1307 {
1308 self.iter.rfold(init, filter_map_fold(self.f, fold))
1309 }
1310 }
1311
1312 #[stable(feature = "fused", since = "1.26.0")]
1313 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F> where F: FnMut(I::Item) -> Option<B> {}
1314
1315 #[unstable(issue = "none", feature = "inplace_iteration")]
1316 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for FilterMap<I, F>
1317 where
1318 F: FnMut(I::Item) -> Option<B>,
1319 I: SourceIter<Source = S>,
1320 {
1321 type Source = S;
1322
1323 #[inline]
1324 unsafe fn as_inner(&mut self) -> &mut S {
1325 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1326 unsafe { SourceIter::as_inner(&mut self.iter) }
1327 }
1328 }
1329
1330 #[unstable(issue = "none", feature = "inplace_iteration")]
1331 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for FilterMap<I, F> where
1332 F: FnMut(I::Item) -> Option<B>
1333 {
1334 }
1335
1336 /// An iterator that yields the current count and the element during iteration.
1337 ///
1338 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1339 /// documentation for more.
1340 ///
1341 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1342 /// [`Iterator`]: trait.Iterator.html
1343 #[derive(Clone, Debug)]
1344 #[must_use = "iterators are lazy and do nothing unless consumed"]
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 pub struct Enumerate<I> {
1347 iter: I,
1348 count: usize,
1349 }
1350 impl<I> Enumerate<I> {
1351 pub(super) fn new(iter: I) -> Enumerate<I> {
1352 Enumerate { iter, count: 0 }
1353 }
1354 }
1355
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<I> Iterator for Enumerate<I>
1358 where
1359 I: Iterator,
1360 {
1361 type Item = (usize, <I as Iterator>::Item);
1362
1363 /// # Overflow Behavior
1364 ///
1365 /// The method does no guarding against overflows, so enumerating more than
1366 /// `usize::MAX` elements either produces the wrong result or panics. If
1367 /// debug assertions are enabled, a panic is guaranteed.
1368 ///
1369 /// # Panics
1370 ///
1371 /// Might panic if the index of the element overflows a `usize`.
1372 #[inline]
1373 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1374 let a = self.iter.next()?;
1375 let i = self.count;
1376 // Possible undefined overflow.
1377 AddAssign::add_assign(&mut self.count, 1);
1378 Some((i, a))
1379 }
1380
1381 #[inline]
1382 fn size_hint(&self) -> (usize, Option<usize>) {
1383 self.iter.size_hint()
1384 }
1385
1386 #[inline]
1387 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1388 let a = self.iter.nth(n)?;
1389 // Possible undefined overflow.
1390 let i = Add::add(self.count, n);
1391 self.count = Add::add(i, 1);
1392 Some((i, a))
1393 }
1394
1395 #[inline]
1396 fn count(self) -> usize {
1397 self.iter.count()
1398 }
1399
1400 #[inline]
1401 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1402 where
1403 Self: Sized,
1404 Fold: FnMut(Acc, Self::Item) -> R,
1405 R: Try<Ok = Acc>,
1406 {
1407 #[inline]
1408 fn enumerate<'a, T, Acc, R>(
1409 count: &'a mut usize,
1410 mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a,
1411 ) -> impl FnMut(Acc, T) -> R + 'a {
1412 move |acc, item| {
1413 let acc = fold(acc, (*count, item));
1414 // Possible undefined overflow.
1415 AddAssign::add_assign(count, 1);
1416 acc
1417 }
1418 }
1419
1420 self.iter.try_fold(init, enumerate(&mut self.count, fold))
1421 }
1422
1423 #[inline]
1424 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1425 where
1426 Fold: FnMut(Acc, Self::Item) -> Acc,
1427 {
1428 #[inline]
1429 fn enumerate<T, Acc>(
1430 mut count: usize,
1431 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1432 ) -> impl FnMut(Acc, T) -> Acc {
1433 move |acc, item| {
1434 let acc = fold(acc, (count, item));
1435 // Possible undefined overflow.
1436 AddAssign::add_assign(&mut count, 1);
1437 acc
1438 }
1439 }
1440
1441 self.iter.fold(init, enumerate(self.count, fold))
1442 }
1443
1444 unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item
1445 where
1446 Self: TrustedRandomAccess,
1447 {
1448 // SAFETY: the caller must uphold the contract for
1449 // `Iterator::__iterator_get_unchecked`.
1450 let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
1451 (Add::add(self.count, idx), value)
1452 }
1453 }
1454
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<I> DoubleEndedIterator for Enumerate<I>
1457 where
1458 I: ExactSizeIterator + DoubleEndedIterator,
1459 {
1460 #[inline]
1461 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1462 let a = self.iter.next_back()?;
1463 let len = self.iter.len();
1464 // Can safely add, `ExactSizeIterator` promises that the number of
1465 // elements fits into a `usize`.
1466 Some((self.count + len, a))
1467 }
1468
1469 #[inline]
1470 fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
1471 let a = self.iter.nth_back(n)?;
1472 let len = self.iter.len();
1473 // Can safely add, `ExactSizeIterator` promises that the number of
1474 // elements fits into a `usize`.
1475 Some((self.count + len, a))
1476 }
1477
1478 #[inline]
1479 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1480 where
1481 Self: Sized,
1482 Fold: FnMut(Acc, Self::Item) -> R,
1483 R: Try<Ok = Acc>,
1484 {
1485 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1486 // that the number of elements fits into a `usize`.
1487 fn enumerate<T, Acc, R>(
1488 mut count: usize,
1489 mut fold: impl FnMut(Acc, (usize, T)) -> R,
1490 ) -> impl FnMut(Acc, T) -> R {
1491 move |acc, item| {
1492 count -= 1;
1493 fold(acc, (count, item))
1494 }
1495 }
1496
1497 let count = self.count + self.iter.len();
1498 self.iter.try_rfold(init, enumerate(count, fold))
1499 }
1500
1501 #[inline]
1502 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1503 where
1504 Fold: FnMut(Acc, Self::Item) -> Acc,
1505 {
1506 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1507 // that the number of elements fits into a `usize`.
1508 fn enumerate<T, Acc>(
1509 mut count: usize,
1510 mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1511 ) -> impl FnMut(Acc, T) -> Acc {
1512 move |acc, item| {
1513 count -= 1;
1514 fold(acc, (count, item))
1515 }
1516 }
1517
1518 let count = self.count + self.iter.len();
1519 self.iter.rfold(init, enumerate(count, fold))
1520 }
1521 }
1522
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl<I> ExactSizeIterator for Enumerate<I>
1525 where
1526 I: ExactSizeIterator,
1527 {
1528 fn len(&self) -> usize {
1529 self.iter.len()
1530 }
1531
1532 fn is_empty(&self) -> bool {
1533 self.iter.is_empty()
1534 }
1535 }
1536
1537 #[doc(hidden)]
1538 #[unstable(feature = "trusted_random_access", issue = "none")]
1539 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1540 where
1541 I: TrustedRandomAccess,
1542 {
1543 fn may_have_side_effect() -> bool {
1544 I::may_have_side_effect()
1545 }
1546 }
1547
1548 #[stable(feature = "fused", since = "1.26.0")]
1549 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1550
1551 #[unstable(feature = "trusted_len", issue = "37572")]
1552 unsafe impl<I> TrustedLen for Enumerate<I> where I: TrustedLen {}
1553
1554 #[unstable(issue = "none", feature = "inplace_iteration")]
1555 unsafe impl<S: Iterator, I: Iterator> SourceIter for Enumerate<I>
1556 where
1557 I: SourceIter<Source = S>,
1558 {
1559 type Source = S;
1560
1561 #[inline]
1562 unsafe fn as_inner(&mut self) -> &mut S {
1563 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1564 unsafe { SourceIter::as_inner(&mut self.iter) }
1565 }
1566 }
1567
1568 #[unstable(issue = "none", feature = "inplace_iteration")]
1569 unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> {}
1570
1571 /// An iterator with a `peek()` that returns an optional reference to the next
1572 /// element.
1573 ///
1574 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1575 /// documentation for more.
1576 ///
1577 /// [`peekable`]: trait.Iterator.html#method.peekable
1578 /// [`Iterator`]: trait.Iterator.html
1579 #[derive(Clone, Debug)]
1580 #[must_use = "iterators are lazy and do nothing unless consumed"]
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 pub struct Peekable<I: Iterator> {
1583 iter: I,
1584 /// Remember a peeked value, even if it was None.
1585 peeked: Option<Option<I::Item>>,
1586 }
1587 impl<I: Iterator> Peekable<I> {
1588 pub(super) fn new(iter: I) -> Peekable<I> {
1589 Peekable { iter, peeked: None }
1590 }
1591 }
1592
1593 // Peekable must remember if a None has been seen in the `.peek()` method.
1594 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1595 // underlying iterator at most once. This does not by itself make the iterator
1596 // fused.
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<I: Iterator> Iterator for Peekable<I> {
1599 type Item = I::Item;
1600
1601 #[inline]
1602 fn next(&mut self) -> Option<I::Item> {
1603 match self.peeked.take() {
1604 Some(v) => v,
1605 None => self.iter.next(),
1606 }
1607 }
1608
1609 #[inline]
1610 #[rustc_inherit_overflow_checks]
1611 fn count(mut self) -> usize {
1612 match self.peeked.take() {
1613 Some(None) => 0,
1614 Some(Some(_)) => 1 + self.iter.count(),
1615 None => self.iter.count(),
1616 }
1617 }
1618
1619 #[inline]
1620 fn nth(&mut self, n: usize) -> Option<I::Item> {
1621 match self.peeked.take() {
1622 Some(None) => None,
1623 Some(v @ Some(_)) if n == 0 => v,
1624 Some(Some(_)) => self.iter.nth(n - 1),
1625 None => self.iter.nth(n),
1626 }
1627 }
1628
1629 #[inline]
1630 fn last(mut self) -> Option<I::Item> {
1631 let peek_opt = match self.peeked.take() {
1632 Some(None) => return None,
1633 Some(v) => v,
1634 None => None,
1635 };
1636 self.iter.last().or(peek_opt)
1637 }
1638
1639 #[inline]
1640 fn size_hint(&self) -> (usize, Option<usize>) {
1641 let peek_len = match self.peeked {
1642 Some(None) => return (0, Some(0)),
1643 Some(Some(_)) => 1,
1644 None => 0,
1645 };
1646 let (lo, hi) = self.iter.size_hint();
1647 let lo = lo.saturating_add(peek_len);
1648 let hi = match hi {
1649 Some(x) => x.checked_add(peek_len),
1650 None => None,
1651 };
1652 (lo, hi)
1653 }
1654
1655 #[inline]
1656 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1657 where
1658 Self: Sized,
1659 F: FnMut(B, Self::Item) -> R,
1660 R: Try<Ok = B>,
1661 {
1662 let acc = match self.peeked.take() {
1663 Some(None) => return Try::from_ok(init),
1664 Some(Some(v)) => f(init, v)?,
1665 None => init,
1666 };
1667 self.iter.try_fold(acc, f)
1668 }
1669
1670 #[inline]
1671 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1672 where
1673 Fold: FnMut(Acc, Self::Item) -> Acc,
1674 {
1675 let acc = match self.peeked {
1676 Some(None) => return init,
1677 Some(Some(v)) => fold(init, v),
1678 None => init,
1679 };
1680 self.iter.fold(acc, fold)
1681 }
1682 }
1683
1684 #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
1685 impl<I> DoubleEndedIterator for Peekable<I>
1686 where
1687 I: DoubleEndedIterator,
1688 {
1689 #[inline]
1690 fn next_back(&mut self) -> Option<Self::Item> {
1691 match self.peeked.as_mut() {
1692 Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
1693 Some(None) => None,
1694 None => self.iter.next_back(),
1695 }
1696 }
1697
1698 #[inline]
1699 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
1700 where
1701 Self: Sized,
1702 F: FnMut(B, Self::Item) -> R,
1703 R: Try<Ok = B>,
1704 {
1705 match self.peeked.take() {
1706 Some(None) => Try::from_ok(init),
1707 Some(Some(v)) => match self.iter.try_rfold(init, &mut f).into_result() {
1708 Ok(acc) => f(acc, v),
1709 Err(e) => {
1710 self.peeked = Some(Some(v));
1711 Try::from_error(e)
1712 }
1713 },
1714 None => self.iter.try_rfold(init, f),
1715 }
1716 }
1717
1718 #[inline]
1719 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1720 where
1721 Fold: FnMut(Acc, Self::Item) -> Acc,
1722 {
1723 match self.peeked {
1724 Some(None) => init,
1725 Some(Some(v)) => {
1726 let acc = self.iter.rfold(init, &mut fold);
1727 fold(acc, v)
1728 }
1729 None => self.iter.rfold(init, fold),
1730 }
1731 }
1732 }
1733
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1736
1737 #[stable(feature = "fused", since = "1.26.0")]
1738 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1739
1740 impl<I: Iterator> Peekable<I> {
1741 /// Returns a reference to the next() value without advancing the iterator.
1742 ///
1743 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1744 /// But if the iteration is over, `None` is returned.
1745 ///
1746 /// [`next`]: trait.Iterator.html#tymethod.next
1747 ///
1748 /// Because `peek()` returns a reference, and many iterators iterate over
1749 /// references, there can be a possibly confusing situation where the
1750 /// return value is a double reference. You can see this effect in the
1751 /// examples below.
1752 ///
1753 /// # Examples
1754 ///
1755 /// Basic usage:
1756 ///
1757 /// ```
1758 /// let xs = [1, 2, 3];
1759 ///
1760 /// let mut iter = xs.iter().peekable();
1761 ///
1762 /// // peek() lets us see into the future
1763 /// assert_eq!(iter.peek(), Some(&&1));
1764 /// assert_eq!(iter.next(), Some(&1));
1765 ///
1766 /// assert_eq!(iter.next(), Some(&2));
1767 ///
1768 /// // The iterator does not advance even if we `peek` multiple times
1769 /// assert_eq!(iter.peek(), Some(&&3));
1770 /// assert_eq!(iter.peek(), Some(&&3));
1771 ///
1772 /// assert_eq!(iter.next(), Some(&3));
1773 ///
1774 /// // After the iterator is finished, so is `peek()`
1775 /// assert_eq!(iter.peek(), None);
1776 /// assert_eq!(iter.next(), None);
1777 /// ```
1778 #[inline]
1779 #[stable(feature = "rust1", since = "1.0.0")]
1780 pub fn peek(&mut self) -> Option<&I::Item> {
1781 let iter = &mut self.iter;
1782 self.peeked.get_or_insert_with(|| iter.next()).as_ref()
1783 }
1784
1785 /// Consume and return the next value of this iterator if a condition is true.
1786 ///
1787 /// If `func` returns `true` for the next value of this iterator, consume and return it.
1788 /// Otherwise, return `None`.
1789 ///
1790 /// # Examples
1791 /// Consume a number if it's equal to 0.
1792 /// ```
1793 /// #![feature(peekable_next_if)]
1794 /// let mut iter = (0..5).peekable();
1795 /// // The first item of the iterator is 0; consume it.
1796 /// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
1797 /// // The next item returned is now 1, so `consume` will return `false`.
1798 /// assert_eq!(iter.next_if(|&x| x == 0), None);
1799 /// // `next_if` saves the value of the next item if it was not equal to `expected`.
1800 /// assert_eq!(iter.next(), Some(1));
1801 /// ```
1802 ///
1803 /// Consume any number less than 10.
1804 /// ```
1805 /// #![feature(peekable_next_if)]
1806 /// let mut iter = (1..20).peekable();
1807 /// // Consume all numbers less than 10
1808 /// while iter.next_if(|&x| x < 10).is_some() {}
1809 /// // The next value returned will be 10
1810 /// assert_eq!(iter.next(), Some(10));
1811 /// ```
1812 #[unstable(feature = "peekable_next_if", issue = "72480")]
1813 pub fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item> {
1814 match self.next() {
1815 Some(matched) if func(&matched) => Some(matched),
1816 other => {
1817 // Since we called `self.next()`, we consumed `self.peeked`.
1818 assert!(self.peeked.is_none());
1819 self.peeked = Some(other);
1820 None
1821 }
1822 }
1823 }
1824
1825 /// Consume and return the next item if it is equal to `expected`.
1826 ///
1827 /// # Example
1828 /// Consume a number if it's equal to 0.
1829 /// ```
1830 /// #![feature(peekable_next_if)]
1831 /// let mut iter = (0..5).peekable();
1832 /// // The first item of the iterator is 0; consume it.
1833 /// assert_eq!(iter.next_if_eq(&0), Some(0));
1834 /// // The next item returned is now 1, so `consume` will return `false`.
1835 /// assert_eq!(iter.next_if_eq(&0), None);
1836 /// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
1837 /// assert_eq!(iter.next(), Some(1));
1838 /// ```
1839 #[unstable(feature = "peekable_next_if", issue = "72480")]
1840 pub fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item>
1841 where
1842 T: ?Sized,
1843 I::Item: PartialEq<T>,
1844 {
1845 self.next_if(|next| next == expected)
1846 }
1847 }
1848
1849 #[unstable(feature = "trusted_len", issue = "37572")]
1850 unsafe impl<I> TrustedLen for Peekable<I> where I: TrustedLen {}
1851
1852 #[unstable(issue = "none", feature = "inplace_iteration")]
1853 unsafe impl<S: Iterator, I: Iterator> SourceIter for Peekable<I>
1854 where
1855 I: SourceIter<Source = S>,
1856 {
1857 type Source = S;
1858
1859 #[inline]
1860 unsafe fn as_inner(&mut self) -> &mut S {
1861 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1862 unsafe { SourceIter::as_inner(&mut self.iter) }
1863 }
1864 }
1865
1866 #[unstable(issue = "none", feature = "inplace_iteration")]
1867 unsafe impl<I: InPlaceIterable> InPlaceIterable for Peekable<I> {}
1868
1869 /// An iterator that rejects elements while `predicate` returns `true`.
1870 ///
1871 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1872 /// documentation for more.
1873 ///
1874 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1875 /// [`Iterator`]: trait.Iterator.html
1876 #[must_use = "iterators are lazy and do nothing unless consumed"]
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 #[derive(Clone)]
1879 pub struct SkipWhile<I, P> {
1880 iter: I,
1881 flag: bool,
1882 predicate: P,
1883 }
1884 impl<I, P> SkipWhile<I, P> {
1885 pub(super) fn new(iter: I, predicate: P) -> SkipWhile<I, P> {
1886 SkipWhile { iter, flag: false, predicate }
1887 }
1888 }
1889
1890 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1891 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1893 f.debug_struct("SkipWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
1894 }
1895 }
1896
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1899 where
1900 P: FnMut(&I::Item) -> bool,
1901 {
1902 type Item = I::Item;
1903
1904 #[inline]
1905 fn next(&mut self) -> Option<I::Item> {
1906 fn check<'a, T>(
1907 flag: &'a mut bool,
1908 pred: &'a mut impl FnMut(&T) -> bool,
1909 ) -> impl FnMut(&T) -> bool + 'a {
1910 move |x| {
1911 if *flag || !pred(x) {
1912 *flag = true;
1913 true
1914 } else {
1915 false
1916 }
1917 }
1918 }
1919
1920 let flag = &mut self.flag;
1921 let pred = &mut self.predicate;
1922 self.iter.find(check(flag, pred))
1923 }
1924
1925 #[inline]
1926 fn size_hint(&self) -> (usize, Option<usize>) {
1927 let (_, upper) = self.iter.size_hint();
1928 (0, upper) // can't know a lower bound, due to the predicate
1929 }
1930
1931 #[inline]
1932 fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R
1933 where
1934 Self: Sized,
1935 Fold: FnMut(Acc, Self::Item) -> R,
1936 R: Try<Ok = Acc>,
1937 {
1938 if !self.flag {
1939 match self.next() {
1940 Some(v) => init = fold(init, v)?,
1941 None => return Try::from_ok(init),
1942 }
1943 }
1944 self.iter.try_fold(init, fold)
1945 }
1946
1947 #[inline]
1948 fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
1949 where
1950 Fold: FnMut(Acc, Self::Item) -> Acc,
1951 {
1952 if !self.flag {
1953 match self.next() {
1954 Some(v) => init = fold(init, v),
1955 None => return init,
1956 }
1957 }
1958 self.iter.fold(init, fold)
1959 }
1960 }
1961
1962 #[stable(feature = "fused", since = "1.26.0")]
1963 impl<I, P> FusedIterator for SkipWhile<I, P>
1964 where
1965 I: FusedIterator,
1966 P: FnMut(&I::Item) -> bool,
1967 {
1968 }
1969
1970 #[unstable(issue = "none", feature = "inplace_iteration")]
1971 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for SkipWhile<I, P>
1972 where
1973 P: FnMut(&I::Item) -> bool,
1974 I: SourceIter<Source = S>,
1975 {
1976 type Source = S;
1977
1978 #[inline]
1979 unsafe fn as_inner(&mut self) -> &mut S {
1980 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
1981 unsafe { SourceIter::as_inner(&mut self.iter) }
1982 }
1983 }
1984
1985 #[unstable(issue = "none", feature = "inplace_iteration")]
1986 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for SkipWhile<I, F> where
1987 F: FnMut(&I::Item) -> bool
1988 {
1989 }
1990
1991 /// An iterator that only accepts elements while `predicate` returns `true`.
1992 ///
1993 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1994 /// documentation for more.
1995 ///
1996 /// [`take_while`]: trait.Iterator.html#method.take_while
1997 /// [`Iterator`]: trait.Iterator.html
1998 #[must_use = "iterators are lazy and do nothing unless consumed"]
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 #[derive(Clone)]
2001 pub struct TakeWhile<I, P> {
2002 iter: I,
2003 flag: bool,
2004 predicate: P,
2005 }
2006 impl<I, P> TakeWhile<I, P> {
2007 pub(super) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
2008 TakeWhile { iter, flag: false, predicate }
2009 }
2010 }
2011
2012 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2013 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
2014 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2015 f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
2016 }
2017 }
2018
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2021 where
2022 P: FnMut(&I::Item) -> bool,
2023 {
2024 type Item = I::Item;
2025
2026 #[inline]
2027 fn next(&mut self) -> Option<I::Item> {
2028 if self.flag {
2029 None
2030 } else {
2031 let x = self.iter.next()?;
2032 if (self.predicate)(&x) {
2033 Some(x)
2034 } else {
2035 self.flag = true;
2036 None
2037 }
2038 }
2039 }
2040
2041 #[inline]
2042 fn size_hint(&self) -> (usize, Option<usize>) {
2043 if self.flag {
2044 (0, Some(0))
2045 } else {
2046 let (_, upper) = self.iter.size_hint();
2047 (0, upper) // can't know a lower bound, due to the predicate
2048 }
2049 }
2050
2051 #[inline]
2052 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2053 where
2054 Self: Sized,
2055 Fold: FnMut(Acc, Self::Item) -> R,
2056 R: Try<Ok = Acc>,
2057 {
2058 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2059 flag: &'a mut bool,
2060 p: &'a mut impl FnMut(&T) -> bool,
2061 mut fold: impl FnMut(Acc, T) -> R + 'a,
2062 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2063 move |acc, x| {
2064 if p(&x) {
2065 ControlFlow::from_try(fold(acc, x))
2066 } else {
2067 *flag = true;
2068 ControlFlow::Break(Try::from_ok(acc))
2069 }
2070 }
2071 }
2072
2073 if self.flag {
2074 Try::from_ok(init)
2075 } else {
2076 let flag = &mut self.flag;
2077 let p = &mut self.predicate;
2078 self.iter.try_fold(init, check(flag, p, fold)).into_try()
2079 }
2080 }
2081
2082 #[inline]
2083 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2084 where
2085 Self: Sized,
2086 Fold: FnMut(Acc, Self::Item) -> Acc,
2087 {
2088 #[inline]
2089 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2090 move |acc, x| Ok(f(acc, x))
2091 }
2092
2093 self.try_fold(init, ok(fold)).unwrap()
2094 }
2095 }
2096
2097 #[stable(feature = "fused", since = "1.26.0")]
2098 impl<I, P> FusedIterator for TakeWhile<I, P>
2099 where
2100 I: FusedIterator,
2101 P: FnMut(&I::Item) -> bool,
2102 {
2103 }
2104
2105 #[unstable(issue = "none", feature = "inplace_iteration")]
2106 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for TakeWhile<I, P>
2107 where
2108 P: FnMut(&I::Item) -> bool,
2109 I: SourceIter<Source = S>,
2110 {
2111 type Source = S;
2112
2113 #[inline]
2114 unsafe fn as_inner(&mut self) -> &mut S {
2115 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2116 unsafe { SourceIter::as_inner(&mut self.iter) }
2117 }
2118 }
2119
2120 #[unstable(issue = "none", feature = "inplace_iteration")]
2121 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> where
2122 F: FnMut(&I::Item) -> bool
2123 {
2124 }
2125
2126 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
2127 ///
2128 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
2129 /// documentation for more.
2130 ///
2131 /// [`map_while`]: trait.Iterator.html#method.map_while
2132 /// [`Iterator`]: trait.Iterator.html
2133 #[must_use = "iterators are lazy and do nothing unless consumed"]
2134 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2135 #[derive(Clone)]
2136 pub struct MapWhile<I, P> {
2137 iter: I,
2138 predicate: P,
2139 }
2140
2141 impl<I, P> MapWhile<I, P> {
2142 pub(super) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
2143 MapWhile { iter, predicate }
2144 }
2145 }
2146
2147 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2148 impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
2149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2150 f.debug_struct("MapWhile").field("iter", &self.iter).finish()
2151 }
2152 }
2153
2154 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2155 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
2156 where
2157 P: FnMut(I::Item) -> Option<B>,
2158 {
2159 type Item = B;
2160
2161 #[inline]
2162 fn next(&mut self) -> Option<B> {
2163 let x = self.iter.next()?;
2164 (self.predicate)(x)
2165 }
2166
2167 #[inline]
2168 fn size_hint(&self) -> (usize, Option<usize>) {
2169 let (_, upper) = self.iter.size_hint();
2170 (0, upper) // can't know a lower bound, due to the predicate
2171 }
2172
2173 #[inline]
2174 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
2175 where
2176 Self: Sized,
2177 Fold: FnMut(Acc, Self::Item) -> R,
2178 R: Try<Ok = Acc>,
2179 {
2180 let Self { iter, predicate } = self;
2181 iter.try_fold(init, |acc, x| match predicate(x) {
2182 Some(item) => ControlFlow::from_try(fold(acc, item)),
2183 None => ControlFlow::Break(Try::from_ok(acc)),
2184 })
2185 .into_try()
2186 }
2187
2188 #[inline]
2189 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2190 where
2191 Self: Sized,
2192 Fold: FnMut(Acc, Self::Item) -> Acc,
2193 {
2194 #[inline]
2195 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2196 move |acc, x| Ok(f(acc, x))
2197 }
2198
2199 self.try_fold(init, ok(fold)).unwrap()
2200 }
2201 }
2202
2203 #[unstable(issue = "none", feature = "inplace_iteration")]
2204 unsafe impl<S: Iterator, B, I: Iterator, P> SourceIter for MapWhile<I, P>
2205 where
2206 P: FnMut(I::Item) -> Option<B>,
2207 I: SourceIter<Source = S>,
2208 {
2209 type Source = S;
2210
2211 #[inline]
2212 unsafe fn as_inner(&mut self) -> &mut S {
2213 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2214 unsafe { SourceIter::as_inner(&mut self.iter) }
2215 }
2216 }
2217
2218 #[unstable(issue = "none", feature = "inplace_iteration")]
2219 unsafe impl<B, I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> where
2220 P: FnMut(I::Item) -> Option<B>
2221 {
2222 }
2223
2224 /// An iterator that skips over `n` elements of `iter`.
2225 ///
2226 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
2227 /// documentation for more.
2228 ///
2229 /// [`skip`]: trait.Iterator.html#method.skip
2230 /// [`Iterator`]: trait.Iterator.html
2231 #[derive(Clone, Debug)]
2232 #[must_use = "iterators are lazy and do nothing unless consumed"]
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 pub struct Skip<I> {
2235 iter: I,
2236 n: usize,
2237 }
2238 impl<I> Skip<I> {
2239 pub(super) fn new(iter: I, n: usize) -> Skip<I> {
2240 Skip { iter, n }
2241 }
2242 }
2243
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl<I> Iterator for Skip<I>
2246 where
2247 I: Iterator,
2248 {
2249 type Item = <I as Iterator>::Item;
2250
2251 #[inline]
2252 fn next(&mut self) -> Option<I::Item> {
2253 if self.n == 0 {
2254 self.iter.next()
2255 } else {
2256 let old_n = self.n;
2257 self.n = 0;
2258 self.iter.nth(old_n)
2259 }
2260 }
2261
2262 #[inline]
2263 fn nth(&mut self, n: usize) -> Option<I::Item> {
2264 // Can't just add n + self.n due to overflow.
2265 if self.n > 0 {
2266 let to_skip = self.n;
2267 self.n = 0;
2268 // nth(n) skips n+1
2269 self.iter.nth(to_skip - 1)?;
2270 }
2271 self.iter.nth(n)
2272 }
2273
2274 #[inline]
2275 fn count(mut self) -> usize {
2276 if self.n > 0 {
2277 // nth(n) skips n+1
2278 if self.iter.nth(self.n - 1).is_none() {
2279 return 0;
2280 }
2281 }
2282 self.iter.count()
2283 }
2284
2285 #[inline]
2286 fn last(mut self) -> Option<I::Item> {
2287 if self.n > 0 {
2288 // nth(n) skips n+1
2289 self.iter.nth(self.n - 1)?;
2290 }
2291 self.iter.last()
2292 }
2293
2294 #[inline]
2295 fn size_hint(&self) -> (usize, Option<usize>) {
2296 let (lower, upper) = self.iter.size_hint();
2297
2298 let lower = lower.saturating_sub(self.n);
2299 let upper = match upper {
2300 Some(x) => Some(x.saturating_sub(self.n)),
2301 None => None,
2302 };
2303
2304 (lower, upper)
2305 }
2306
2307 #[inline]
2308 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2309 where
2310 Self: Sized,
2311 Fold: FnMut(Acc, Self::Item) -> R,
2312 R: Try<Ok = Acc>,
2313 {
2314 let n = self.n;
2315 self.n = 0;
2316 if n > 0 {
2317 // nth(n) skips n+1
2318 if self.iter.nth(n - 1).is_none() {
2319 return Try::from_ok(init);
2320 }
2321 }
2322 self.iter.try_fold(init, fold)
2323 }
2324
2325 #[inline]
2326 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2327 where
2328 Fold: FnMut(Acc, Self::Item) -> Acc,
2329 {
2330 if self.n > 0 {
2331 // nth(n) skips n+1
2332 if self.iter.nth(self.n - 1).is_none() {
2333 return init;
2334 }
2335 }
2336 self.iter.fold(init, fold)
2337 }
2338 }
2339
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2342
2343 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
2344 impl<I> DoubleEndedIterator for Skip<I>
2345 where
2346 I: DoubleEndedIterator + ExactSizeIterator,
2347 {
2348 fn next_back(&mut self) -> Option<Self::Item> {
2349 if self.len() > 0 { self.iter.next_back() } else { None }
2350 }
2351
2352 #[inline]
2353 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
2354 let len = self.len();
2355 if n < len {
2356 self.iter.nth_back(n)
2357 } else {
2358 if len > 0 {
2359 // consume the original iterator
2360 self.iter.nth_back(len - 1);
2361 }
2362 None
2363 }
2364 }
2365
2366 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2367 where
2368 Self: Sized,
2369 Fold: FnMut(Acc, Self::Item) -> R,
2370 R: Try<Ok = Acc>,
2371 {
2372 fn check<T, Acc, R: Try<Ok = Acc>>(
2373 mut n: usize,
2374 mut fold: impl FnMut(Acc, T) -> R,
2375 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> {
2376 move |acc, x| {
2377 n -= 1;
2378 let r = fold(acc, x);
2379 if n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2380 }
2381 }
2382
2383 let n = self.len();
2384 if n == 0 {
2385 Try::from_ok(init)
2386 } else {
2387 self.iter.try_rfold(init, check(n, fold)).into_try()
2388 }
2389 }
2390
2391 fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2392 where
2393 Fold: FnMut(Acc, Self::Item) -> Acc,
2394 {
2395 #[inline]
2396 fn ok<Acc, T>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, T) -> Result<Acc, !> {
2397 move |acc, x| Ok(f(acc, x))
2398 }
2399
2400 self.try_rfold(init, ok(fold)).unwrap()
2401 }
2402 }
2403
2404 #[stable(feature = "fused", since = "1.26.0")]
2405 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2406
2407 #[unstable(issue = "none", feature = "inplace_iteration")]
2408 unsafe impl<S: Iterator, I: Iterator> SourceIter for Skip<I>
2409 where
2410 I: SourceIter<Source = S>,
2411 {
2412 type Source = S;
2413
2414 #[inline]
2415 unsafe fn as_inner(&mut self) -> &mut S {
2416 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2417 unsafe { SourceIter::as_inner(&mut self.iter) }
2418 }
2419 }
2420
2421 #[unstable(issue = "none", feature = "inplace_iteration")]
2422 unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {}
2423
2424 /// An iterator that only iterates over the first `n` iterations of `iter`.
2425 ///
2426 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2427 /// documentation for more.
2428 ///
2429 /// [`take`]: trait.Iterator.html#method.take
2430 /// [`Iterator`]: trait.Iterator.html
2431 #[derive(Clone, Debug)]
2432 #[must_use = "iterators are lazy and do nothing unless consumed"]
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 pub struct Take<I> {
2435 pub(super) iter: I,
2436 pub(super) n: usize,
2437 }
2438 impl<I> Take<I> {
2439 pub(super) fn new(iter: I, n: usize) -> Take<I> {
2440 Take { iter, n }
2441 }
2442 }
2443
2444 #[stable(feature = "rust1", since = "1.0.0")]
2445 impl<I> Iterator for Take<I>
2446 where
2447 I: Iterator,
2448 {
2449 type Item = <I as Iterator>::Item;
2450
2451 #[inline]
2452 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2453 if self.n != 0 {
2454 self.n -= 1;
2455 self.iter.next()
2456 } else {
2457 None
2458 }
2459 }
2460
2461 #[inline]
2462 fn nth(&mut self, n: usize) -> Option<I::Item> {
2463 if self.n > n {
2464 self.n -= n + 1;
2465 self.iter.nth(n)
2466 } else {
2467 if self.n > 0 {
2468 self.iter.nth(self.n - 1);
2469 self.n = 0;
2470 }
2471 None
2472 }
2473 }
2474
2475 #[inline]
2476 fn size_hint(&self) -> (usize, Option<usize>) {
2477 if self.n == 0 {
2478 return (0, Some(0));
2479 }
2480
2481 let (lower, upper) = self.iter.size_hint();
2482
2483 let lower = cmp::min(lower, self.n);
2484
2485 let upper = match upper {
2486 Some(x) if x < self.n => Some(x),
2487 _ => Some(self.n),
2488 };
2489
2490 (lower, upper)
2491 }
2492
2493 #[inline]
2494 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2495 where
2496 Self: Sized,
2497 Fold: FnMut(Acc, Self::Item) -> R,
2498 R: Try<Ok = Acc>,
2499 {
2500 fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2501 n: &'a mut usize,
2502 mut fold: impl FnMut(Acc, T) -> R + 'a,
2503 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2504 move |acc, x| {
2505 *n -= 1;
2506 let r = fold(acc, x);
2507 if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2508 }
2509 }
2510
2511 if self.n == 0 {
2512 Try::from_ok(init)
2513 } else {
2514 let n = &mut self.n;
2515 self.iter.try_fold(init, check(n, fold)).into_try()
2516 }
2517 }
2518
2519 #[inline]
2520 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2521 where
2522 Self: Sized,
2523 Fold: FnMut(Acc, Self::Item) -> Acc,
2524 {
2525 #[inline]
2526 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2527 move |acc, x| Ok(f(acc, x))
2528 }
2529
2530 self.try_fold(init, ok(fold)).unwrap()
2531 }
2532 }
2533
2534 #[unstable(issue = "none", feature = "inplace_iteration")]
2535 unsafe impl<S: Iterator, I: Iterator> SourceIter for Take<I>
2536 where
2537 I: SourceIter<Source = S>,
2538 {
2539 type Source = S;
2540
2541 #[inline]
2542 unsafe fn as_inner(&mut self) -> &mut S {
2543 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2544 unsafe { SourceIter::as_inner(&mut self.iter) }
2545 }
2546 }
2547
2548 #[unstable(issue = "none", feature = "inplace_iteration")]
2549 unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> {}
2550
2551 #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
2552 impl<I> DoubleEndedIterator for Take<I>
2553 where
2554 I: DoubleEndedIterator + ExactSizeIterator,
2555 {
2556 #[inline]
2557 fn next_back(&mut self) -> Option<Self::Item> {
2558 if self.n == 0 {
2559 None
2560 } else {
2561 let n = self.n;
2562 self.n -= 1;
2563 self.iter.nth_back(self.iter.len().saturating_sub(n))
2564 }
2565 }
2566
2567 #[inline]
2568 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2569 let len = self.iter.len();
2570 if self.n > n {
2571 let m = len.saturating_sub(self.n) + n;
2572 self.n -= n + 1;
2573 self.iter.nth_back(m)
2574 } else {
2575 if len > 0 {
2576 self.iter.nth_back(len - 1);
2577 }
2578 None
2579 }
2580 }
2581
2582 #[inline]
2583 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2584 where
2585 Self: Sized,
2586 Fold: FnMut(Acc, Self::Item) -> R,
2587 R: Try<Ok = Acc>,
2588 {
2589 if self.n == 0 {
2590 Try::from_ok(init)
2591 } else {
2592 let len = self.iter.len();
2593 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2594 Try::from_ok(init)
2595 } else {
2596 self.iter.try_rfold(init, fold)
2597 }
2598 }
2599 }
2600
2601 #[inline]
2602 fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2603 where
2604 Self: Sized,
2605 Fold: FnMut(Acc, Self::Item) -> Acc,
2606 {
2607 if self.n == 0 {
2608 init
2609 } else {
2610 let len = self.iter.len();
2611 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2612 init
2613 } else {
2614 self.iter.rfold(init, fold)
2615 }
2616 }
2617 }
2618 }
2619
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2622
2623 #[stable(feature = "fused", since = "1.26.0")]
2624 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2625
2626 #[unstable(feature = "trusted_len", issue = "37572")]
2627 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2628
2629 /// An iterator to maintain state while iterating another iterator.
2630 ///
2631 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2632 /// documentation for more.
2633 ///
2634 /// [`scan`]: trait.Iterator.html#method.scan
2635 /// [`Iterator`]: trait.Iterator.html
2636 #[must_use = "iterators are lazy and do nothing unless consumed"]
2637 #[stable(feature = "rust1", since = "1.0.0")]
2638 #[derive(Clone)]
2639 pub struct Scan<I, St, F> {
2640 iter: I,
2641 f: F,
2642 state: St,
2643 }
2644 impl<I, St, F> Scan<I, St, F> {
2645 pub(super) fn new(iter: I, state: St, f: F) -> Scan<I, St, F> {
2646 Scan { iter, state, f }
2647 }
2648 }
2649
2650 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2651 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2653 f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish()
2654 }
2655 }
2656
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<B, I, St, F> Iterator for Scan<I, St, F>
2659 where
2660 I: Iterator,
2661 F: FnMut(&mut St, I::Item) -> Option<B>,
2662 {
2663 type Item = B;
2664
2665 #[inline]
2666 fn next(&mut self) -> Option<B> {
2667 let a = self.iter.next()?;
2668 (self.f)(&mut self.state, a)
2669 }
2670
2671 #[inline]
2672 fn size_hint(&self) -> (usize, Option<usize>) {
2673 let (_, upper) = self.iter.size_hint();
2674 (0, upper) // can't know a lower bound, due to the scan function
2675 }
2676
2677 #[inline]
2678 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2679 where
2680 Self: Sized,
2681 Fold: FnMut(Acc, Self::Item) -> R,
2682 R: Try<Ok = Acc>,
2683 {
2684 fn scan<'a, T, St, B, Acc, R: Try<Ok = Acc>>(
2685 state: &'a mut St,
2686 f: &'a mut impl FnMut(&mut St, T) -> Option<B>,
2687 mut fold: impl FnMut(Acc, B) -> R + 'a,
2688 ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2689 move |acc, x| match f(state, x) {
2690 None => ControlFlow::Break(Try::from_ok(acc)),
2691 Some(x) => ControlFlow::from_try(fold(acc, x)),
2692 }
2693 }
2694
2695 let state = &mut self.state;
2696 let f = &mut self.f;
2697 self.iter.try_fold(init, scan(state, f, fold)).into_try()
2698 }
2699
2700 #[inline]
2701 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2702 where
2703 Self: Sized,
2704 Fold: FnMut(Acc, Self::Item) -> Acc,
2705 {
2706 #[inline]
2707 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2708 move |acc, x| Ok(f(acc, x))
2709 }
2710
2711 self.try_fold(init, ok(fold)).unwrap()
2712 }
2713 }
2714
2715 #[unstable(issue = "none", feature = "inplace_iteration")]
2716 unsafe impl<St, F, B, S: Iterator, I: Iterator> SourceIter for Scan<I, St, F>
2717 where
2718 I: SourceIter<Source = S>,
2719 F: FnMut(&mut St, I::Item) -> Option<B>,
2720 {
2721 type Source = S;
2722
2723 #[inline]
2724 unsafe fn as_inner(&mut self) -> &mut S {
2725 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2726 unsafe { SourceIter::as_inner(&mut self.iter) }
2727 }
2728 }
2729
2730 #[unstable(issue = "none", feature = "inplace_iteration")]
2731 unsafe impl<St, F, B, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F> where
2732 F: FnMut(&mut St, I::Item) -> Option<B>
2733 {
2734 }
2735
2736 /// An iterator that calls a function with a reference to each element before
2737 /// yielding it.
2738 ///
2739 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2740 /// documentation for more.
2741 ///
2742 /// [`inspect`]: trait.Iterator.html#method.inspect
2743 /// [`Iterator`]: trait.Iterator.html
2744 #[must_use = "iterators are lazy and do nothing unless consumed"]
2745 #[stable(feature = "rust1", since = "1.0.0")]
2746 #[derive(Clone)]
2747 pub struct Inspect<I, F> {
2748 iter: I,
2749 f: F,
2750 }
2751 impl<I, F> Inspect<I, F> {
2752 pub(super) fn new(iter: I, f: F) -> Inspect<I, F> {
2753 Inspect { iter, f }
2754 }
2755 }
2756
2757 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2758 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2760 f.debug_struct("Inspect").field("iter", &self.iter).finish()
2761 }
2762 }
2763
2764 impl<I: Iterator, F> Inspect<I, F>
2765 where
2766 F: FnMut(&I::Item),
2767 {
2768 #[inline]
2769 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2770 if let Some(ref a) = elt {
2771 (self.f)(a);
2772 }
2773
2774 elt
2775 }
2776 }
2777
2778 fn inspect_fold<T, Acc>(
2779 mut f: impl FnMut(&T),
2780 mut fold: impl FnMut(Acc, T) -> Acc,
2781 ) -> impl FnMut(Acc, T) -> Acc {
2782 move |acc, item| {
2783 f(&item);
2784 fold(acc, item)
2785 }
2786 }
2787
2788 fn inspect_try_fold<'a, T, Acc, R>(
2789 f: &'a mut impl FnMut(&T),
2790 mut fold: impl FnMut(Acc, T) -> R + 'a,
2791 ) -> impl FnMut(Acc, T) -> R + 'a {
2792 move |acc, item| {
2793 f(&item);
2794 fold(acc, item)
2795 }
2796 }
2797
2798 #[stable(feature = "rust1", since = "1.0.0")]
2799 impl<I: Iterator, F> Iterator for Inspect<I, F>
2800 where
2801 F: FnMut(&I::Item),
2802 {
2803 type Item = I::Item;
2804
2805 #[inline]
2806 fn next(&mut self) -> Option<I::Item> {
2807 let next = self.iter.next();
2808 self.do_inspect(next)
2809 }
2810
2811 #[inline]
2812 fn size_hint(&self) -> (usize, Option<usize>) {
2813 self.iter.size_hint()
2814 }
2815
2816 #[inline]
2817 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2818 where
2819 Self: Sized,
2820 Fold: FnMut(Acc, Self::Item) -> R,
2821 R: Try<Ok = Acc>,
2822 {
2823 self.iter.try_fold(init, inspect_try_fold(&mut self.f, fold))
2824 }
2825
2826 #[inline]
2827 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2828 where
2829 Fold: FnMut(Acc, Self::Item) -> Acc,
2830 {
2831 self.iter.fold(init, inspect_fold(self.f, fold))
2832 }
2833 }
2834
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2837 where
2838 F: FnMut(&I::Item),
2839 {
2840 #[inline]
2841 fn next_back(&mut self) -> Option<I::Item> {
2842 let next = self.iter.next_back();
2843 self.do_inspect(next)
2844 }
2845
2846 #[inline]
2847 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2848 where
2849 Self: Sized,
2850 Fold: FnMut(Acc, Self::Item) -> R,
2851 R: Try<Ok = Acc>,
2852 {
2853 self.iter.try_rfold(init, inspect_try_fold(&mut self.f, fold))
2854 }
2855
2856 #[inline]
2857 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2858 where
2859 Fold: FnMut(Acc, Self::Item) -> Acc,
2860 {
2861 self.iter.rfold(init, inspect_fold(self.f, fold))
2862 }
2863 }
2864
2865 #[stable(feature = "rust1", since = "1.0.0")]
2866 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2867 where
2868 F: FnMut(&I::Item),
2869 {
2870 fn len(&self) -> usize {
2871 self.iter.len()
2872 }
2873
2874 fn is_empty(&self) -> bool {
2875 self.iter.is_empty()
2876 }
2877 }
2878
2879 #[stable(feature = "fused", since = "1.26.0")]
2880 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F> where F: FnMut(&I::Item) {}
2881
2882 #[unstable(issue = "none", feature = "inplace_iteration")]
2883 unsafe impl<S: Iterator, I: Iterator, F> SourceIter for Inspect<I, F>
2884 where
2885 F: FnMut(&I::Item),
2886 I: SourceIter<Source = S>,
2887 {
2888 type Source = S;
2889
2890 #[inline]
2891 unsafe fn as_inner(&mut self) -> &mut S {
2892 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
2893 unsafe { SourceIter::as_inner(&mut self.iter) }
2894 }
2895 }
2896
2897 #[unstable(issue = "none", feature = "inplace_iteration")]
2898 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Inspect<I, F> where F: FnMut(&I::Item) {}
2899
2900 /// An iterator adapter that produces output as long as the underlying
2901 /// iterator produces `Result::Ok` values.
2902 ///
2903 /// If an error is encountered, the iterator stops and the error is
2904 /// stored.
2905 pub(crate) struct ResultShunt<'a, I, E> {
2906 iter: I,
2907 error: &'a mut Result<(), E>,
2908 }
2909
2910 /// Process the given iterator as if it yielded a `T` instead of a
2911 /// `Result<T, _>`. Any errors will stop the inner iterator and
2912 /// the overall result will be an error.
2913 pub(crate) fn process_results<I, T, E, F, U>(iter: I, mut f: F) -> Result<U, E>
2914 where
2915 I: Iterator<Item = Result<T, E>>,
2916 for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U,
2917 {
2918 let mut error = Ok(());
2919 let shunt = ResultShunt { iter, error: &mut error };
2920 let value = f(shunt);
2921 error.map(|()| value)
2922 }
2923
2924 impl<I, T, E> Iterator for ResultShunt<'_, I, E>
2925 where
2926 I: Iterator<Item = Result<T, E>>,
2927 {
2928 type Item = T;
2929
2930 fn next(&mut self) -> Option<Self::Item> {
2931 self.find(|_| true)
2932 }
2933
2934 fn size_hint(&self) -> (usize, Option<usize>) {
2935 if self.error.is_err() {
2936 (0, Some(0))
2937 } else {
2938 let (_, upper) = self.iter.size_hint();
2939 (0, upper)
2940 }
2941 }
2942
2943 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2944 where
2945 F: FnMut(B, Self::Item) -> R,
2946 R: Try<Ok = B>,
2947 {
2948 let error = &mut *self.error;
2949 self.iter
2950 .try_fold(init, |acc, x| match x {
2951 Ok(x) => ControlFlow::from_try(f(acc, x)),
2952 Err(e) => {
2953 *error = Err(e);
2954 ControlFlow::Break(Try::from_ok(acc))
2955 }
2956 })
2957 .into_try()
2958 }
2959
2960 fn fold<B, F>(mut self, init: B, fold: F) -> B
2961 where
2962 Self: Sized,
2963 F: FnMut(B, Self::Item) -> B,
2964 {
2965 #[inline]
2966 fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2967 move |acc, x| Ok(f(acc, x))
2968 }
2969
2970 self.try_fold(init, ok(fold)).unwrap()
2971 }
2972 }