use std::{convert::Infallible, future::Future, pin::Pin, task};
use futures::future::{pending, AbortHandle, Abortable, Pending};
#[must_use]
pub fn mk_stop_token() -> (StopToken, StopFlag) {
let (handle, reg) = AbortHandle::new_pair();
let token = StopToken(handle);
let flag = StopFlag(Abortable::new(pending(), reg));
(token, flag)
}
#[derive(Clone)]
pub struct StopToken(AbortHandle);
#[pin_project::pin_project]
#[derive(Clone)]
pub struct StopFlag(#[pin] Abortable<Pending<Infallible>>);
impl StopToken {
pub fn stop(&self) {
self.0.abort()
}
}
impl StopFlag {
#[must_use]
pub fn is_stopped(&self) -> bool {
self.0.is_aborted()
}
}
impl Future for StopFlag {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
self.project().0.poll(cx).map(|res| match res {
Err(_aborted) => (),
Ok(unreachable) => match unreachable {},
})
}
}