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
use futures_core::stream::Stream;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::{
    marker::Unpin,
    pin::Pin,
    task::{Context, Poll},
};

/// Stream for the [`interleave_pending`](super::StreamTestExt::interleave_pending) method.
#[derive(Debug)]
pub struct InterleavePending<St: Stream> {
    stream: St,
    pended: bool,
}

impl<St: Stream + Unpin> Unpin for InterleavePending<St> {}

impl<St: Stream> InterleavePending<St> {
    unsafe_pinned!(stream: St);
    unsafe_unpinned!(pended: bool);

    pub(crate) fn new(stream: St) -> InterleavePending<St> {
        InterleavePending {
            stream,
            pended: false,
        }
    }
}

impl<St: Stream> Stream for InterleavePending<St> {
    type Item = St::Item;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        if *self.as_mut().pended() {
            let next = self.as_mut().stream().poll_next(cx);
            if next.is_ready() {
                *self.pended() = false;
            }
            next
        } else {
            cx.waker().wake_by_ref();
            *self.pended() = true;
            Poll::Pending
        }
    }
}