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
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use completion_core::CompletionFuture;
use futures_core::ready;
use pin_project_lite::pin_project;
pin_project! {
#[derive(Debug)]
pub struct NowOrNever<F> {
#[pin]
fut: F,
cancelling: bool,
}
}
impl<F: CompletionFuture> NowOrNever<F> {
pub(super) fn new(fut: F) -> Self {
Self {
fut,
cancelling: false,
}
}
}
impl<F> CompletionFuture for NowOrNever<F>
where
F: CompletionFuture,
{
type Output = Option<F::Output>;
unsafe fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
if !*this.cancelling {
if let Poll::Ready(output) = this.fut.as_mut().poll(&mut crate::noop_cx()) {
return Poll::Ready(Some(output));
}
*this.cancelling = true;
}
ready!(this.fut.poll_cancel(cx));
Poll::Ready(None)
}
unsafe fn poll_cancel(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.project().fut.poll_cancel(cx)
}
}
impl<F> Future for NowOrNever<F>
where
F: CompletionFuture + Future<Output = <F as CompletionFuture>::Output>,
{
type Output = Option<<F as CompletionFuture>::Output>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe { CompletionFuture::poll(self, cx) }
}
}