#[derive(Clone, Default, Debug)]
pub struct CancelToken(tokio_util::sync::CancellationToken);
impl CancelToken {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.cancel();
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.0.is_cancelled()
}
pub async fn cancelled(&self) {
self.0.cancelled().await;
}
pub async fn until_cancelled<F: std::future::Future>(&self, fut: F) -> Option<F::Output> {
self.0.run_until_cancelled(fut).await
}
}
impl From<tokio_util::sync::CancellationToken> for CancelToken {
fn from(t: tokio_util::sync::CancellationToken) -> Self {
Self(t)
}
}
impl From<CancelToken> for tokio_util::sync::CancellationToken {
fn from(t: CancelToken) -> Self {
t.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shares_state_across_clones() {
let a = CancelToken::new();
let b = a.clone();
assert!(!b.is_cancelled());
a.cancel();
assert!(b.is_cancelled());
}
#[tokio::test(start_paused = true)]
async fn a_pending_wait_is_interrupted_not_polled() {
let token = CancelToken::new();
let t = token.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
t.cancel();
});
let out = token.until_cancelled(std::future::pending::<()>()).await;
assert!(out.is_none());
}
#[tokio::test(start_paused = true)]
async fn an_uncancelled_wait_yields_the_value() {
let token = CancelToken::new();
let out = token
.until_cancelled(async {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
"done"
})
.await;
assert_eq!(out, Some("done"));
}
}