use std::{future::Future, pin::Pin, task};
use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
#[must_use]
pub fn mk_stop_token() -> (StopToken, StopFlag) {
let token = CancellationToken::new();
let flag = StopFlag::new(token.clone());
(StopToken(token), flag)
}
#[derive(Clone)]
pub struct StopToken(CancellationToken);
pub struct StopFlag {
token: CancellationToken,
wait: Pin<Box<WaitForCancellationFutureOwned>>,
}
impl StopToken {
pub fn stop(&self) {
self.0.cancel();
}
}
impl StopFlag {
fn new(token: CancellationToken) -> Self {
let wait = Box::pin(token.clone().cancelled_owned());
Self { token, wait }
}
#[must_use]
pub fn is_stopped(&self) -> bool {
self.token.is_cancelled()
}
}
impl Clone for StopFlag {
fn clone(&self) -> Self {
Self::new(self.token.clone())
}
}
impl Future for StopFlag {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
if self.is_stopped() {
task::Poll::Ready(())
} else {
self.wait.as_mut().poll(cx)
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{atomic::AtomicBool, Arc};
use futures::task::{waker, ArcWake};
use super::*;
#[test]
fn stop_wakes_every_registered_flag() {
struct Wake(AtomicBool);
impl ArcWake for Wake {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.0.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
let (token, flag) = mk_stop_token();
let mut flags = [flag.clone(), flag];
let wakes =
[Arc::new(Wake(AtomicBool::new(false))), Arc::new(Wake(AtomicBool::new(false)))];
for (flag, wake) in flags.iter_mut().zip(&wakes) {
let waker = waker(Arc::clone(wake));
assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_pending());
}
token.stop();
for (flag, wake) in flags.iter_mut().zip(wakes) {
assert!(wake.0.load(std::sync::atomic::Ordering::Relaxed));
let waker = waker(wake);
assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_ready());
}
}
}