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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use std::pin::Pin;
use std::sync::{Arc, Weak, Mutex};
use std::future::Future;
use std::task::{Poll, Waker, Context};
use std::sync::atomic::{AtomicBool, Ordering};
use discard::{Discard, DiscardOnDrop};
use pin_project::pin_project;
#[derive(Debug)]
struct CancelableFutureState {
is_cancelled: AtomicBool,
waker: Mutex<Option<Waker>>,
}
#[derive(Debug)]
pub struct CancelableFutureHandle {
state: Weak<CancelableFutureState>,
}
impl Discard for CancelableFutureHandle {
fn discard(self) {
if let Some(state) = self.state.upgrade() {
let mut lock = state.waker.lock().unwrap();
state.is_cancelled.store(true, Ordering::SeqCst);
if let Some(waker) = lock.take() {
drop(lock);
waker.wake();
}
}
}
}
#[pin_project(project = CancelableFutureProj)]
#[derive(Debug)]
#[must_use = "Futures do nothing unless polled"]
pub struct CancelableFuture<A, B> {
state: Arc<CancelableFutureState>,
#[pin]
future: Option<A>,
when_cancelled: Option<B>,
}
impl<A, B> Future for CancelableFuture<A, B>
where A: Future,
B: FnOnce() -> A::Output {
type Output = A::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let CancelableFutureProj { state, mut future, when_cancelled } = self.project();
if state.is_cancelled.load(Ordering::SeqCst) {
future.set(None);
let callback = when_cancelled.take().unwrap();
Poll::Ready(callback())
} else {
match future.as_pin_mut().unwrap().poll(cx) {
Poll::Pending => {
*state.waker.lock().unwrap() = Some(cx.waker().clone());
Poll::Pending
},
a => a,
}
}
}
}
pub fn cancelable_future<A, B>(future: A, when_cancelled: B) -> (DiscardOnDrop<CancelableFutureHandle>, CancelableFuture<A, B>)
where A: Future,
B: FnOnce() -> A::Output {
let state = Arc::new(CancelableFutureState {
is_cancelled: AtomicBool::new(false),
waker: Mutex::new(None),
});
let cancel_handle = DiscardOnDrop::new(CancelableFutureHandle {
state: Arc::downgrade(&state),
});
let cancel_future = CancelableFuture {
state,
future: Some(future),
when_cancelled: Some(when_cancelled),
};
(cancel_handle, cancel_future)
}