1use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::Arc;
15use tokio::sync::Notify;
16
17#[derive(Clone, Debug, Default)]
18pub struct Cancel {
19 inner: Arc<Inner>,
20}
21
22#[derive(Debug, Default)]
23struct Inner {
24 flag: AtomicBool,
25 notify: Notify,
26}
27
28impl Cancel {
29 pub fn new() -> Self {
30 Self::default()
31 }
32
33 pub fn cancel(&self) {
36 self.inner.flag.store(true, Ordering::SeqCst);
37 self.inner.notify.notify_waiters();
38 }
39
40 pub fn is_cancelled(&self) -> bool {
41 self.inner.flag.load(Ordering::SeqCst)
42 }
43
44 pub async fn cancelled(&self) {
47 let notified = self.inner.notify.notified();
49 if self.is_cancelled() {
50 return;
51 }
52 notified.await;
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use std::time::Duration;
60
61 #[test]
62 fn starts_uncancelled_and_latches() {
63 let c = Cancel::new();
64 assert!(!c.is_cancelled());
65 c.cancel();
66 assert!(c.is_cancelled());
67 c.cancel();
68 assert!(c.is_cancelled());
69 }
70
71 #[test]
72 fn clones_share_one_flag() {
73 let a = Cancel::new();
74 let b = a.clone();
75 b.cancel();
76 assert!(a.is_cancelled());
77 }
78
79 #[tokio::test]
80 async fn cancelled_wakes_a_waiter() {
81 let c = Cancel::new();
82 let woken = {
83 let c = c.clone();
84 tokio::spawn(async move { c.cancelled().await })
85 };
86 tokio::time::sleep(Duration::from_millis(20)).await;
87 assert!(!woken.is_finished());
88 c.cancel();
89 tokio::time::timeout(Duration::from_secs(1), woken)
90 .await
91 .expect("waiter should wake")
92 .unwrap();
93 }
94
95 #[tokio::test]
96 async fn cancelled_returns_at_once_when_already_set() {
97 let c = Cancel::new();
98 c.cancel();
99 tokio::time::timeout(Duration::from_millis(200), c.cancelled())
100 .await
101 .expect("an already-cancelled token must not wait");
102 }
103}