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
use futures_core::future::{Future, FusedFuture};
use futures_core::task::{Context, Poll};
use std::pin::Pin;
use pin_utils::{unsafe_pinned, unsafe_unpinned};
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PendingOnce<Fut: Future> {
future: Fut,
polled_before: bool,
}
impl<Fut: Future> PendingOnce<Fut> {
unsafe_pinned!(future: Fut);
unsafe_unpinned!(polled_before: bool);
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(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Self::Output> {
if self.polled_before {
self.as_mut().future().poll(cx)
} else {
*self.as_mut().polled_before() = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
impl<Fut: Future + FusedFuture> FusedFuture for PendingOnce<Fut> {
fn is_terminated(&self) -> bool {
self.polled_before && self.future.is_terminated()
}
}