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