Debian Codegraph @

debian/rust-vendor/rayon/src/iter/take.rs

raw
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 pub(super) fn new(base: I, n: usize) -> Self {
21 let n = Ord::min(base.len(), n);
22 Take { base, n }
23 }
24 }
25
26 impl<I> ParallelIterator for Take<I>
27 where
28 I: IndexedParallelIterator,
29 {
30 type Item = I::Item;
31
32 fn drive_unindexed<C>(self, consumer: C) -> C::Result
33 where
34 C: UnindexedConsumer<Self::Item>,
35 {
36 bridge(self, consumer)
37 }
38
39 fn opt_len(&self) -> Option<usize> {
40 Some(self.len())
41 }
42 }
43
44 impl<I> IndexedParallelIterator for Take<I>
45 where
46 I: IndexedParallelIterator,
47 {
48 fn len(&self) -> usize {
49 self.n
50 }
51
52 fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
53 bridge(self, consumer)
54 }
55
56 fn with_producer<CB>(self, callback: CB) -> CB::Output
57 where
58 CB: ProducerCallback<Self::Item>,
59 {
60 return self.base.with_producer(Callback {
61 callback,
62 n: self.n,
63 });
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 fn callback<P>(self, base: P) -> CB::Output
76 where
77 P: Producer<Item = T>,
78 {
79 let (producer, _) = base.split_at(self.n);
80 self.callback.callback(producer)
81 }
82 }
83 }
84 }