1use std::{future::Future, pin::Pin, task};
6
7use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
8
9#[must_use]
11pub fn mk_stop_token() -> (StopToken, StopFlag) {
12 let token = CancellationToken::new();
13 let flag = StopFlag::new(token.clone());
14 (StopToken(token), flag)
15}
16
17#[derive(Clone)]
19pub struct StopToken(CancellationToken);
20
21pub struct StopFlag {
28 token: CancellationToken,
29 wait: Pin<Box<WaitForCancellationFutureOwned>>,
30}
31
32impl StopToken {
33 pub fn stop(&self) {
37 self.0.cancel();
38 }
39}
40
41impl StopFlag {
42 fn new(token: CancellationToken) -> Self {
43 let wait = Box::pin(token.clone().cancelled_owned());
44 Self { token, wait }
45 }
46
47 #[must_use]
49 pub fn is_stopped(&self) -> bool {
50 self.token.is_cancelled()
51 }
52}
53
54impl Clone for StopFlag {
55 fn clone(&self) -> Self {
56 Self::new(self.token.clone())
57 }
58}
59
60impl Future for StopFlag {
62 type Output = ();
63
64 fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
65 if self.is_stopped() {
66 task::Poll::Ready(())
67 } else {
68 self.wait.as_mut().poll(cx)
69 }
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use std::sync::{atomic::AtomicBool, Arc};
76
77 use futures::task::{waker, ArcWake};
78
79 use super::*;
80
81 #[test]
82 fn stop_wakes_every_registered_flag() {
83 struct Wake(AtomicBool);
84
85 impl ArcWake for Wake {
86 fn wake_by_ref(arc_self: &Arc<Self>) {
87 arc_self.0.store(true, std::sync::atomic::Ordering::Relaxed);
88 }
89 }
90
91 let (token, flag) = mk_stop_token();
92 let mut flags = [flag.clone(), flag];
93 let wakes =
94 [Arc::new(Wake(AtomicBool::new(false))), Arc::new(Wake(AtomicBool::new(false)))];
95 for (flag, wake) in flags.iter_mut().zip(&wakes) {
96 let waker = waker(Arc::clone(wake));
97 assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_pending());
98 }
99 token.stop();
100 for (flag, wake) in flags.iter_mut().zip(wakes) {
101 assert!(wake.0.load(std::sync::atomic::Ordering::Relaxed));
102 let waker = waker(wake);
103 assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_ready());
104 }
105 }
106}