moonproof-utils 0.2.1

Shared helpers (hex parsing, validation) used across moonproof crates. Mirror of midnight-js/packages/utils.
Documentation
//! Timers and clocks that work the same on a host and in a browser:
//! tokio's timer and `std::time` on a host, the browser's `setTimeout`
//! and `performance.now()` under `wasm32-unknown-unknown`, where
//! `std::time::Instant::now` and tokio's timer driver are unavailable.

use std::future::Future;
use std::time::Duration;

/// A monotonic instant: tokio's on a host, so a paused test clock moves
/// it; `performance.now()` in a browser.
#[cfg(not(target_arch = "wasm32"))]
pub use tokio::time::Instant;
#[cfg(target_arch = "wasm32")]
pub use web_time::Instant;
pub use web_time::{SystemTime, UNIX_EPOCH};

/// `Send` on a host; nothing in a browser, where values that touch
/// JavaScript stay on the thread that made them. Bound a future or
/// stream by it where a host needs `Send` and a browser cannot give it.
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + ?Sized> MaybeSend for T {}

/// `Send` on a host; nothing in a browser.
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSend for T {}

/// Run `future` in the background: on tokio's runtime on a host, on the
/// browser's event loop in a browser.
pub fn spawn<F>(future: F)
where
    F: Future<Output = ()> + MaybeSend + 'static,
{
    #[cfg(not(target_arch = "wasm32"))]
    drop(tokio::spawn(future));
    #[cfg(target_arch = "wasm32")]
    wasm_bindgen_futures::spawn_local(future);
}

/// A background task that can be awaited or aborted, on either target.
/// Dropping it detaches the task, which runs on, as tokio's
/// `JoinHandle` does.
pub struct Task<T: 'static> {
    handle: Option<futures_util::future::RemoteHandle<Result<T, futures_util::future::Aborted>>>,
    abort: futures_util::future::AbortHandle,
}

/// The task was aborted before it finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the task was aborted")]
pub struct Aborted;

/// Run `future` in the background, as [`spawn`] does, keeping a handle
/// to await or abort it.
pub fn spawn_task<F>(future: F) -> Task<F::Output>
where
    F: Future + MaybeSend + 'static,
    F::Output: MaybeSend + 'static,
{
    use futures_util::FutureExt;
    let (future, abort) = futures_util::future::abortable(future);
    let (future, handle) = future.remote_handle();
    spawn(future);
    Task {
        handle: Some(handle),
        abort,
    }
}

impl<T: 'static> Task<T> {
    /// The task's output once it finishes.
    ///
    /// # Errors
    ///
    /// [`Aborted`] when [`Self::abort`] stopped it first.
    pub async fn join(mut self) -> Result<T, Aborted> {
        match self.handle.take() {
            Some(handle) => handle.await.map_err(|_| Aborted),
            None => Err(Aborted),
        }
    }

    /// Stop the task at its next suspension point.
    pub fn abort(&self) {
        self.abort.abort();
    }
}

impl<T: 'static> Drop for Task<T> {
    fn drop(&mut self) {
        if let Some(handle) = self.handle.take() {
            handle.forget();
        }
    }
}

/// A deadline passed before the future finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("timed out after {0:?}")]
pub struct Elapsed(pub Duration);

/// Wait for `duration`.
pub async fn sleep(duration: Duration) {
    #[cfg(not(target_arch = "wasm32"))]
    tokio::time::sleep(duration).await;
    #[cfg(target_arch = "wasm32")]
    gloo_timers::future::sleep(duration).await;
}

/// `future`'s output, unless `duration` passes first.
///
/// # Errors
///
/// [`Elapsed`] when the deadline passes first; `future` is dropped.
pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output, Elapsed> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        tokio::time::timeout(duration, future)
            .await
            .map_err(|_| Elapsed(duration))
    }
    #[cfg(target_arch = "wasm32")]
    {
        use futures_util::future::{select, Either};
        let future = std::pin::pin!(future);
        let deadline = std::pin::pin!(sleep(duration));
        match select(future, deadline).await {
            Either::Left((output, _)) => Ok(output),
            Either::Right(((), _)) => Err(Elapsed(duration)),
        }
    }
}