1use super::noop::NoopConsumer;
2use super::plumbing::*;
3use super::*;
4use std::cmp::min;
5
6/// `Skip` is an iterator that skips over the first `n` elements.
7/// This struct is created by the [`skip()`] method on [`IndexedParallelIterator`]
8///
9/// [`skip()`]: trait.IndexedParallelIterator.html#method.skip
10/// [`IndexedParallelIterator`]: trait.IndexedParallelIterator.html
11#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
12#[derive(Debug, Clone)]
13pub struct Skip<I> {
14 base: I,
15 n: usize,
16}
17
18impl<I> Skip<I>
19where
20 I: IndexedParallelIterator,
21{
22 /// Creates a new `Skip` iterator.
23 pub(super) fn new(base: I, n: usize) -> Self {
24 let n: usize = min(v1:base.len(), v2:n);
25 Skip { base, n }
26 }
27}
28
29impl<I> ParallelIterator for Skip<I>
30where
31 I: IndexedParallelIterator,
32{
33 type Item = I::Item;
34
35 fn drive_unindexed<C>(self, consumer: C) -> C::Result
36 where
37 C: UnindexedConsumer<Self::Item>,
38 {
39 bridge(self, consumer)
40 }
41
42 fn opt_len(&self) -> Option<usize> {
43 Some(self.len())
44 }
45}
46
47impl<I> IndexedParallelIterator for Skip<I>
48where
49 I: IndexedParallelIterator,
50{
51 fn len(&self) -> usize {
52 self.base.len() - self.n
53 }
54
55 fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
56 bridge(self, consumer)
57 }
58
59 fn with_producer<CB>(self, callback: CB) -> CB::Output
60 where
61 CB: ProducerCallback<Self::Item>,
62 {
63 return self.base.with_producer(Callback {
64 callback,
65 n: self.n,
66 });
67
68 struct Callback<CB> {
69 callback: CB,
70 n: usize,
71 }
72
73 impl<T, CB> ProducerCallback<T> for Callback<CB>
74 where
75 CB: ProducerCallback<T>,
76 {
77 type Output = CB::Output;
78 fn callback<P>(self, base: P) -> CB::Output
79 where
80 P: Producer<Item = T>,
81 {
82 crate::in_place_scope(|scope| {
83 let Self { callback, n } = self;
84 let (before_skip, after_skip) = base.split_at(n);
85
86 // Run the skipped part separately for side effects.
87 // We'll still get any panics propagated back by the scope.
88 scope.spawn(move |_| bridge_producer_consumer(n, before_skip, NoopConsumer));
89
90 callback.callback(after_skip)
91 })
92 }
93 }
94 }
95}
96