async_std/stream/stream/
take.rs1use core::pin::Pin;
2
3use pin_project_lite::pin_project;
4
5use crate::stream::Stream;
6use crate::task::{Context, Poll};
7
8pin_project! {
9 #[derive(Clone, Debug)]
17 pub struct Take<S> {
18 #[pin]
19 pub(crate) stream: S,
20 pub(crate) remaining: usize,
21 }
22}
23
24impl<S> Take<S> {
25 pub(super) fn new(stream: S, remaining: usize) -> Self {
26 Self {
27 stream,
28 remaining,
29 }
30 }
31}
32
33impl<S: Stream> Stream for Take<S> {
34 type Item = S::Item;
35
36 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
37 let this = self.project();
38 if *this.remaining == 0 {
39 Poll::Ready(None)
40 } else {
41 let next = futures_core::ready!(this.stream.poll_next(cx));
42 match next {
43 Some(_) => *this.remaining -= 1,
44 None => *this.remaining = 0,
45 }
46 Poll::Ready(next)
47 }
48 }
49}