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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use pin_project_lite::pin_project;
pin_project! {
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct Cancellable<F, S>
where
F: Future,
S: Future,
{
#[pin]
inner: F,
#[pin]
stopper: S,
}
}
#[derive(Debug)]
pub enum CancellableResult<T, S> {
Finished(T),
Cancelled(S),
}
impl<F, S> Future for Cancellable<F, S>
where
F: Future,
S: Future,
{
type Output = CancellableResult<F::Output, S::Output>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = self.project();
match this.inner.poll(cx) {
Poll::Pending => {}
Poll::Ready(ready) => {
return Poll::Ready(CancellableResult::Finished(ready));
}
};
match this.stopper.poll(cx) {
Poll::Ready(s) => return Poll::Ready(CancellableResult::Cancelled(s)),
Poll::Pending => {}
};
Poll::Pending
}
}
pub trait FutureCancellable: Future {
fn cancel_with<S>(self, stopper: impl FnOnce() -> S) -> Cancellable<Self, S>
where
S: Future,
Self: Sized,
{
Cancellable { inner: self, stopper: (stopper)() }
}
}
impl<T: ?Sized> FutureCancellable for T where T: Future {}