blocking_permit/
yield_stream.rs

1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use futures_core::stream::Stream;
5
6/// A `Stream` adapter that yields after every `Poll::Ready(Some(_))` result
7/// from its source.
8///
9/// The wrapper may be useful to ensure that a `Future` that polls a `Stream`
10/// (directly or indirectly) yields (return `Poll::Pending`) between items. If
11/// the source stream already returns `Poll::Pending` then this will not add
12/// further `Poll::Pending` returns.
13///
14/// The type is enabled via the *yield-stream* feature.
15#[derive(Debug)]
16#[must_use = "streams do nothing unless polled"]
17pub struct YieldStream<St, I>
18    where St: Stream<Item=I>
19{
20    source: St,
21    yielded: bool,
22}
23
24impl<St, I> YieldStream<St, I>
25    where St: Stream<Item=I>
26{
27    /// Construct with source to wrap.
28    pub fn new(source: St) -> Self {
29        YieldStream { source, yielded: true }
30    }
31}
32
33impl<St, I> Stream for YieldStream<St, I>
34    where St: Stream<Item=I>
35{
36    type Item = I;
37
38    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>)
39        -> Poll<Option<Self::Item>>
40    {
41        // Safety: This is for projection to source below, which is exclusively
42        // owned by this wrapper and never moved. The `unsafe` could be
43        // avoided, but at the cost of requiring the source stream be `Unpin`.
44        let this = unsafe { self.get_unchecked_mut() };
45
46        if this.yielded {
47            let src = unsafe { Pin::new_unchecked(&mut this.source) };
48            let next = src.poll_next(cx);
49            if let Poll::Ready(Some(_)) = next {
50                this.yielded = false;
51            }
52            next
53        } else {
54            this.yielded = true;
55            cx.waker().wake_by_ref();
56            Poll::Pending
57        }
58    }
59}