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