async_std/stream/stream/
fuse.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 `None` forever after the underlying stream yields `None` once.
10    ///
11    /// This `struct` is created by the [`fuse`] method on [`Stream`]. See its
12    /// documentation for more.
13    ///
14    /// [`fuse`]: trait.Stream.html#method.fuse
15    /// [`Stream`]: trait.Stream.html
16    #[derive(Clone, Debug)]
17    pub struct Fuse<S> {
18        #[pin]
19        pub(crate) stream: S,
20        pub(crate) done: bool,
21    }
22}
23
24impl<S> Fuse<S> {
25    pub(super) fn new(stream: S) -> Self {
26        Self {
27            stream,
28            done: false,
29        }
30    }
31}
32
33impl<S: Stream> Stream for Fuse<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.done {
39            Poll::Ready(None)
40        } else {
41            let next = futures_core::ready!(this.stream.poll_next(cx));
42            if next.is_none() {
43                *this.done = true;
44            }
45            Poll::Ready(next)
46        }
47    }
48}