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
use futures::future::{FusedFuture, OptionFuture};
use futures_intrusive::channel::{shared::StateReceiveFuture, StateId};
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::waker;
use crate::Canceled;
#[must_use = "futures do nothing unless polled"]
#[pin_project]
pub struct Cancellation {
#[pin]
inner: OptionFuture<StateReceiveFuture<parking_lot::RawMutex, bool>>,
state_id: StateId,
}
impl Cancellation {
pub(crate) fn none() -> Self {
Self {
inner: None.into(),
state_id: StateId::new(),
}
}
}
impl Future for Cancellation {
type Output = Option<Canceled>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.project();
this.inner
.as_mut()
.set(waker::cancellation(cx, *this.state_id));
this.inner.as_mut().poll(cx).map(|v| match v {
Some(Some((state_id, true))) => {
*this.state_id = state_id;
Some(Canceled::Graceful)
}
Some(Some((_, false))) => unreachable!(),
Some(None) => Some(Canceled::Forced),
None => None,
})
}
}
impl FusedFuture for Cancellation {
fn is_terminated(&self) -> bool {
self.inner.is_terminated()
}
}
pub fn cancellation() -> Cancellation {
Cancellation::none()
}