use core::future::{Future, poll_fn};
use core::pin::Pin;
use core::task::{Context, Poll};
use futures_core::Stream;
use futures_core::stream::FusedStream;
use crate::{Duration, Instant};
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TimeoutError;
pub fn with_timeout<F: Future>(timeout: impl Into<Duration>, fut: F) -> TimeoutFuture<F> {
let timeout = timeout.into();
with_deadline(Instant::now() + timeout, fut)
}
pub fn try_with_timeout<F: Future>(timeout: impl Into<Duration>, fut: F) -> Option<TimeoutFuture<F>> {
let timeout = timeout.into();
Some(with_deadline(Instant::now().checked_add(timeout)?, fut))
}
pub fn with_deadline<F: Future>(at: Instant, fut: F) -> TimeoutFuture<F> {
TimeoutFuture {
timer: Timer::at(at),
fut,
}
}
pub trait WithTimeout: Sized {
type Output;
fn with_timeout(self, timeout: impl Into<Duration>) -> TimeoutFuture<Self> {
let timeout = timeout.into();
self.with_deadline(Instant::now() + timeout)
}
fn try_with_timeout(self, timeout: impl Into<Duration>) -> Option<TimeoutFuture<Self>> {
let timeout = timeout.into();
Some(self.with_deadline(Instant::now().checked_add(timeout)?))
}
fn with_deadline(self, at: Instant) -> TimeoutFuture<Self>;
}
impl<F: Future> WithTimeout for F {
type Output = F::Output;
fn with_deadline(self, at: Instant) -> TimeoutFuture<Self> {
with_deadline(at, self)
}
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TimeoutFuture<F> {
timer: Timer,
fut: F,
}
impl<F: Unpin> Unpin for TimeoutFuture<F> {}
impl<F: Future> Future for TimeoutFuture<F> {
type Output = Result<F::Output, TimeoutError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = unsafe { self.get_unchecked_mut() };
let fut = unsafe { Pin::new_unchecked(&mut this.fut) };
let timer = unsafe { Pin::new_unchecked(&mut this.timer) };
if let Poll::Ready(x) = fut.poll(cx) {
return Poll::Ready(Ok(x));
}
if let Poll::Ready(_) = timer.poll(cx) {
return Poll::Ready(Err(TimeoutError));
}
Poll::Pending
}
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Timer {
expires_at: Instant,
yielded_once: bool,
}
impl Timer {
pub fn at(expires_at: Instant) -> Self {
Self {
expires_at,
yielded_once: false,
}
}
pub fn after(duration: impl Into<Duration>) -> Self {
let expires_at = Instant::now() + duration.into();
Self::at(expires_at)
}
pub fn try_after(duration: impl Into<Duration>) -> Option<Self> {
let expires_at = Instant::now().checked_add(duration.into())?;
Some(Self::at(expires_at))
}
#[inline]
pub fn after_ticks(ticks: u64) -> Self {
Self::after(Duration::from_ticks(ticks))
}
#[inline]
pub fn try_after_ticks(ticks: u64) -> Option<Self> {
Self::try_after(Duration::from_ticks(ticks))
}
#[inline]
pub fn after_nanos(nanos: u64) -> Self {
Self::after(Duration::from_nanos(nanos))
}
#[inline]
pub fn try_after_nanos(nanos: u64) -> Option<Self> {
Self::try_after(Duration::from_nanos(nanos))
}
#[inline]
pub fn after_micros(micros: u64) -> Self {
Self::after(Duration::from_micros(micros))
}
#[inline]
pub fn try_after_micros(micros: u64) -> Option<Self> {
Self::try_after(Duration::from_micros(micros))
}
#[inline]
pub fn after_millis(millis: u64) -> Self {
Self::after(Duration::from_millis(millis))
}
#[inline]
pub fn try_after_millis(millis: u64) -> Option<Self> {
Self::try_after(Duration::from_millis(millis))
}
#[inline]
pub fn after_secs(secs: u64) -> Self {
Self::after(Duration::from_secs(secs))
}
#[inline]
pub fn try_after_secs(secs: u64) -> Option<Self> {
Self::try_after(Duration::from_secs(secs))
}
}
impl Unpin for Timer {}
impl Future for Timer {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.yielded_once && self.expires_at <= Instant::now() {
Poll::Ready(())
} else {
hazard3_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
self.yielded_once = true;
Poll::Pending
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Ticker {
expires_at: Instant,
duration: Duration,
}
impl Ticker {
pub fn every(duration: impl Into<Duration>) -> Self {
let duration = duration.into();
let expires_at = Instant::now() + duration;
Self { expires_at, duration }
}
pub fn try_every(duration: impl Into<Duration>) -> Option<Self> {
let duration = duration.into();
let expires_at = Instant::now().checked_add(duration)?;
Some(Self { expires_at, duration })
}
pub fn now_and_every(duration: impl Into<Duration>) -> Self {
let duration = duration.into();
let expires_at = Instant::now();
Self { expires_at, duration }
}
pub fn reset(&mut self) {
self.expires_at = Instant::now() + self.duration;
}
pub fn checked_reset(&mut self) -> Option<()> {
self.expires_at = Instant::now().checked_add(self.duration)?;
Some(())
}
pub fn reset_at(&mut self, deadline: Instant) {
self.expires_at = deadline + self.duration;
}
pub fn checked_reset_at(&mut self, deadline: Instant) -> Option<()> {
self.expires_at = deadline.checked_add(self.duration)?;
Some(())
}
pub fn reset_after(&mut self, after: impl Into<Duration>) {
let after = after.into();
self.expires_at = Instant::now() + after + self.duration;
}
pub fn checked_reset_after(&mut self, after: impl Into<Duration>) -> Option<()> {
let after = after.into();
self.expires_at = Instant::now().checked_add(after)?.checked_add(self.duration)?;
Some(())
}
pub fn reset_to_now(&mut self) {
self.expires_at = Instant::now();
}
pub fn next(&mut self) -> impl Future<Output = ()> + Send + Sync + '_ {
poll_fn(|cx| {
if self.expires_at <= Instant::now() {
let dur = self.duration;
self.expires_at += dur;
Poll::Ready(())
} else {
hazard3_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
Poll::Pending
}
})
}
}
impl Unpin for Ticker {}
impl Stream for Ticker {
type Item = ();
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.expires_at <= Instant::now() {
let dur = self.duration;
self.expires_at += dur;
Poll::Ready(Some(()))
} else {
hazard3_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
Poll::Pending
}
}
}
impl FusedStream for Ticker {
fn is_terminated(&self) -> bool {
false
}
}
impl core::fmt::Display for TimeoutError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("TimeoutError")
}
}
impl core::error::Error for TimeoutError {}
#[cfg(all(test, feature = "std"))]
mod test {
use super::*;
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn with_timeout_panics() {
while Instant::now() == Instant::MIN {} let _ = with_timeout(Duration::MAX, async {}); }
#[test]
fn try_with_timeout_none() {
while Instant::now() == Instant::MIN {} assert!(try_with_timeout(Duration::MAX, async {}).is_none());
}
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn timer_after_panics() {
while Instant::now() == Instant::MIN {} let _ = Timer::after(Duration::MAX); }
#[test]
fn timer_try_after_none() {
while Instant::now() == Instant::MIN {} assert!(Timer::try_after(Duration::MAX).is_none());
}
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn ticker_every_panics() {
while Instant::now() == Instant::MIN {} let _ = Ticker::every(Duration::MAX); }
#[test]
fn ticker_try_every_none() {
while Instant::now() == Instant::MIN {} assert!(Ticker::try_every(Duration::MAX).is_none());
}
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn ticker_reset_panics() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
while Instant::now() == Instant::MIN {} ticker.reset(); }
#[test]
fn ticker_checked_reset_none() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
while Instant::now() == Instant::MIN {} assert!(ticker.checked_reset().is_none());
}
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn ticker_reset_at_panics() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
ticker.reset_at(Instant::MAX); }
#[test]
fn ticker_checked_reset_at_none() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
assert!(ticker.checked_reset_at(Instant::MAX).is_none());
}
#[test]
#[should_panic(expected = "overflow")]
#[cfg(panic = "unwind")]
fn ticker_reset_after_panics() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
while Instant::now() == Instant::MIN {} ticker.reset_after(Duration::MAX); }
#[test]
fn ticker_checked_reset_after_none() {
let mut ticker = Ticker {
expires_at: Instant::MAX,
duration: Duration::MAX,
};
while Instant::now() == Instant::MIN {} assert!(ticker.checked_reset_after(Duration::MAX).is_none());
}
}