use std::future::Future;
use std::time::Duration;
use tokio::sync::oneshot;
#[derive(Debug, Clone, Copy)]
pub(crate) enum TimedOut {
TimedOut,
Cancelled,
}
#[derive(Default)]
#[repr(transparent)]
pub(crate) struct Timeout {
tx: Option<oneshot::Sender<()>>,
}
impl Timeout {
pub(crate) fn clear(&mut self) {
self.tx = None;
}
pub(crate) fn is_set(&self) -> bool {
self.tx.is_some()
}
pub(crate) fn set(&mut self, duration: Duration) -> impl Future<Output = TimedOut> {
let (tx, rx) = oneshot::channel();
self.tx = Some(tx);
async move {
let sleep = tokio::time::sleep(duration);
tokio::select! {
_ = rx => TimedOut::Cancelled,
_ = sleep => TimedOut::TimedOut,
}
}
}
}