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 62 63 64 65 66 67 68 69
use crate::yielder::Receiver; use futures_core::{FusedStream, Stream}; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; #[doc(hidden)] #[derive(Debug)] pub struct AsyncStream<T, U> { rx: Receiver<T>, done: bool, generator: U, } impl<T, U> AsyncStream<T, U> { #[doc(hidden)] pub fn new(rx: Receiver<T>, generator: U) -> AsyncStream<T, U> { AsyncStream { rx, done: false, generator, } } } impl<T, U> FusedStream for AsyncStream<T, U> where U: Future<Output = ()>, { fn is_terminated(&self) -> bool { self.done } } impl<T, U> Stream for AsyncStream<T, U> where U: Future<Output = ()>, { type Item = T; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { unsafe { let me = Pin::get_unchecked_mut(self); if me.done { return Poll::Ready(None); } let mut dst = None; let res = { let _enter = me.rx.enter(&mut dst); Pin::new_unchecked(&mut me.generator).poll(cx) }; me.done = res.is_ready(); if dst.is_some() { return Poll::Ready(dst.take()); } if me.done { Poll::Ready(None) } else { Poll::Pending } } } }