use std::time::Duration;
use base::Result as SysResult;
use base::Timer;
use base::TimerTrait;
use crate::AsyncResult;
use crate::Error;
use crate::Executor;
use crate::IntoAsync;
use crate::IoSource;
pub struct TimerAsync<T: TimerTrait + IntoAsync> {
pub(crate) io_source: IoSource<T>,
}
impl<T: TimerTrait + IntoAsync> TimerAsync<T> {
pub fn new(timer: T, ex: &Executor) -> AsyncResult<TimerAsync<T>> {
ex.async_from(timer)
.map(|io_source| TimerAsync { io_source })
}
pub async fn wait(&self) -> AsyncResult<()> {
self.wait_sys().await
}
pub fn reset_oneshot(&mut self, dur: Duration) -> SysResult<()> {
self.io_source.as_source_mut().reset_oneshot(dur)
}
pub fn reset_repeating(&mut self, dur: Duration) -> SysResult<()> {
self.io_source.as_source_mut().reset_repeating(dur)
}
pub fn clear(&mut self) -> SysResult<()> {
self.io_source.as_source_mut().clear()
}
}
impl TimerAsync<Timer> {
pub async fn sleep(ex: &Executor, dur: Duration) -> std::result::Result<(), Error> {
let mut tfd = Timer::new().map_err(Error::Timer)?;
tfd.reset_oneshot(dur).map_err(Error::Timer)?;
let t = TimerAsync::new(tfd, ex).map_err(Error::TimerAsync)?;
t.wait().await.map_err(Error::TimerAsync)?;
Ok(())
}
}
impl IntoAsync for Timer {}