/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rayon-1.11.0/src/iter/take.rs
Line | Count | Source |
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()`]: IndexedParallelIterator::take() |
8 | | #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] |
9 | | #[derive(Debug, Clone)] |
10 | | pub struct Take<I> { |
11 | | base: I, |
12 | | n: usize, |
13 | | } |
14 | | |
15 | | impl<I> Take<I> |
16 | | where |
17 | | I: IndexedParallelIterator, |
18 | | { |
19 | | /// Creates a new `Take` iterator. |
20 | 0 | pub(super) fn new(base: I, n: usize) -> Self { |
21 | 0 | let n = Ord::min(base.len(), n); |
22 | 0 | Take { base, n } |
23 | 0 | } |
24 | | } |
25 | | |
26 | | impl<I> ParallelIterator for Take<I> |
27 | | where |
28 | | I: IndexedParallelIterator, |
29 | | { |
30 | | type Item = I::Item; |
31 | | |
32 | 0 | fn drive_unindexed<C>(self, consumer: C) -> C::Result |
33 | 0 | where |
34 | 0 | C: UnindexedConsumer<Self::Item>, |
35 | | { |
36 | 0 | bridge(self, consumer) |
37 | 0 | } |
38 | | |
39 | 0 | fn opt_len(&self) -> Option<usize> { |
40 | 0 | Some(self.len()) |
41 | 0 | } |
42 | | } |
43 | | |
44 | | impl<I> IndexedParallelIterator for Take<I> |
45 | | where |
46 | | I: IndexedParallelIterator, |
47 | | { |
48 | 0 | fn len(&self) -> usize { |
49 | 0 | self.n |
50 | 0 | } |
51 | | |
52 | 0 | fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result { |
53 | 0 | bridge(self, consumer) |
54 | 0 | } |
55 | | |
56 | 0 | fn with_producer<CB>(self, callback: CB) -> CB::Output |
57 | 0 | where |
58 | 0 | CB: ProducerCallback<Self::Item>, |
59 | | { |
60 | 0 | return self.base.with_producer(Callback { |
61 | 0 | callback, |
62 | 0 | n: self.n, |
63 | 0 | }); |
64 | | |
65 | | struct Callback<CB> { |
66 | | callback: CB, |
67 | | n: usize, |
68 | | } |
69 | | |
70 | | impl<T, CB> ProducerCallback<T> for Callback<CB> |
71 | | where |
72 | | CB: ProducerCallback<T>, |
73 | | { |
74 | | type Output = CB::Output; |
75 | 0 | fn callback<P>(self, base: P) -> CB::Output |
76 | 0 | where |
77 | 0 | P: Producer<Item = T>, |
78 | | { |
79 | 0 | let (producer, _) = base.split_at(self.n); |
80 | 0 | self.callback.callback(producer) |
81 | 0 | } |
82 | | } |
83 | 0 | } |
84 | | } |