1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use core::pin::Pin;
use core::task::{Context, Poll};
use async_std::task::ready;
use pin_project_lite::pin_project;
use crate::ParallelStream;
pin_project! {
#[derive(Clone, Debug)]
pub struct Take<S> {
#[pin]
stream: S,
remaining: usize,
limit: Option<usize>,
}
}
impl<S: ParallelStream> Take<S> {
pub(super) fn new(stream: S, remaining: usize) -> Self {
Self {
limit: stream.get_limit(),
remaining,
stream,
}
}
}
impl<S: ParallelStream> ParallelStream for Take<S> {
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
let this = self.project();
if *this.remaining == 0 {
Poll::Ready(None)
} else {
let next = ready!(this.stream.poll_next(cx));
match next {
Some(_) => *this.remaining -= 1,
None => *this.remaining = 0,
}
Poll::Ready(next)
}
}
fn limit(mut self, limit: impl Into<Option<usize>>) -> Self {
self.limit = limit.into();
self
}
fn get_limit(&self) -> Option<usize> {
self.limit
}
}