async_std/stream/stream/
take.rs

1use core::pin::Pin;
2
3use pin_project_lite::pin_project;
4
5use crate::stream::Stream;
6use crate::task::{Context, Poll};
7
8pin_project! {
9    /// A stream that yields the first `n` items of another stream.
10    ///
11    /// This `struct` is created by the [`take`] method on [`Stream`]. See its
12    /// documentation for more.
13    ///
14    /// [`take`]: trait.Stream.html#method.take
15    /// [`Stream`]: trait.Stream.html
16    #[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}