use core::{
future::{Future, Ready},
time::Duration,
};
pub trait Sleeper: 'static {
type Sleep: Future<Output = ()>;
fn sleep(&self, dur: Duration) -> Self::Sleep;
}
#[doc(hidden)]
pub trait MaybeSleeper: 'static {
type Sleep: Future<Output = ()>;
}
impl<T: Sleeper + ?Sized> MaybeSleeper for T {
type Sleep = <T as Sleeper>::Sleep;
}
impl<F: Fn(Duration) -> Fut + 'static, Fut: Future<Output = ()>> Sleeper for F {
type Sleep = Fut;
fn sleep(&self, dur: Duration) -> Self::Sleep {
self(dur)
}
}
#[cfg(all(not(feature = "tokio-sleep"), not(feature = "gloo-timers-sleep"),))]
pub type DefaultSleeper = PleaseEnableAFeatureOrProvideACustomSleeper;
#[cfg(all(not(target_arch = "wasm32"), feature = "tokio-sleep"))]
pub type DefaultSleeper = TokioSleeper;
#[cfg(all(target_arch = "wasm32", feature = "gloo-timers-sleep"))]
pub type DefaultSleeper = GlooTimersSleep;
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default)]
pub struct PleaseEnableAFeatureOrProvideACustomSleeper;
impl MaybeSleeper for PleaseEnableAFeatureOrProvideACustomSleeper {
type Sleep = Ready<()>;
}
#[cfg(all(not(target_arch = "wasm32"), feature = "tokio-sleep"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct TokioSleeper;
#[cfg(all(not(target_arch = "wasm32"), feature = "tokio-sleep"))]
impl Sleeper for TokioSleeper {
type Sleep = tokio::time::Sleep;
fn sleep(&self, dur: Duration) -> Self::Sleep {
tokio::time::sleep(dur)
}
}
#[cfg(feature = "futures-timer-sleep")]
#[derive(Clone, Copy, Debug, Default)]
pub struct FuturesTimerSleep;
#[cfg(feature = "futures-timer-sleep")]
impl Sleeper for FuturesTimerSleep {
type Sleep = futures_timer::Delay;
fn sleep(&self, dur: Duration) -> Self::Sleep {
futures_timer::Delay::new(dur)
}
}
#[cfg(all(target_arch = "wasm32", feature = "gloo-timers-sleep"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct GlooTimersSleep;
#[cfg(all(target_arch = "wasm32", feature = "gloo-timers-sleep"))]
impl Sleeper for GlooTimersSleep {
type Sleep = gloo_timers::future::TimeoutFuture;
fn sleep(&self, dur: Duration) -> Self::Sleep {
gloo_timers::future::sleep(dur)
}
}