use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use std::time::SystemTime;
use futures_core::Stream;
#[cfg(not(target_arch = "wasm32"))]
mod bounds {
pub trait MaybeSend: Send {}
impl<T: Send + ?Sized> MaybeSend for T {}
}
#[cfg(target_arch = "wasm32")]
mod bounds {
pub trait MaybeSend {}
impl<T: ?Sized> MaybeSend for T {}
}
pub use bounds::MaybeSend;
#[cfg(not(target_arch = "wasm32"))]
pub type MaybeSendFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type MaybeSendFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
#[cfg(target_arch = "wasm32")]
pub(crate) type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;
#[cfg(all(target_arch = "wasm32", feature = "service-account-wasm"))]
pub(crate) use futures_util::lock::Mutex;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use tokio::sync::Mutex;
const MAX_BROWSER_TIMER: Duration = Duration::from_millis(i32::MAX as u64);
pub(crate) async fn sleep(delay: Duration) {
#[cfg(not(target_arch = "wasm32"))]
tokio::time::sleep(delay).await;
#[cfg(target_arch = "wasm32")]
gloo_timers::future::sleep(browser_timer(delay)).await;
}
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
fn browser_timer(delay: Duration) -> Duration {
delay.min(MAX_BROWSER_TIMER)
}
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
pub(crate) fn now() -> SystemTime {
#[cfg(not(target_arch = "wasm32"))]
{
SystemTime::now()
}
#[cfg(target_arch = "wasm32")]
{
let millis = js_sys::Date::now() as u64;
SystemTime::UNIX_EPOCH + Duration::from_millis(millis)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_browser_timer_waits_at_most_what_set_timeout_takes() {
let max = Duration::from_millis(2_147_483_647);
assert_eq!(
browser_timer(Duration::from_millis(200)),
Duration::from_millis(200)
);
assert_eq!(browser_timer(max), max);
assert_eq!(browser_timer(max + Duration::from_millis(1)), max);
assert_eq!(
browser_timer(Duration::from_secs(10 * 365 * 24 * 60 * 60)),
max
);
assert_eq!(browser_timer(Duration::MAX), max);
}
}