futures_test/future/
pending_once.rs

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
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
use pin_project::pin_project;
use std::pin::Pin;

/// Combinator that guarantees one [`Poll::Pending`] before polling its inner
/// future.
///
/// This is created by the
/// [`FutureTestExt::pending_once`](super::FutureTestExt::pending_once)
/// method.
#[pin_project]
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PendingOnce<Fut> {
    #[pin]
    future: Fut,
    polled_before: bool,
}

impl<Fut: Future> PendingOnce<Fut> {
    pub(super) fn new(future: Fut) -> Self {
        Self { future, polled_before: false }
    }
}

impl<Fut: Future> Future for PendingOnce<Fut> {
    type Output = Fut::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        if *this.polled_before {
            this.future.poll(cx)
        } else {
            *this.polled_before = true;
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

impl<Fut: FusedFuture> FusedFuture for PendingOnce<Fut> {
    fn is_terminated(&self) -> bool {
        self.polled_before && self.future.is_terminated()
    }
}