use std::future::Future;
use tokio::runtime::Handle;
use tokio::runtime::RuntimeFlavor;
use tokio_util::sync::CancellationToken;
pub(crate) fn spawn<F>(future: F)
where
F: Future + 'static,
F::Output: 'static,
{
if Handle::current().runtime_flavor() == RuntimeFlavor::CurrentThread {
drop(deno_unsync::spawn(future));
} else {
drop(tokio::task::spawn_local(future));
}
}
pub(crate) type Cancel = CancellationToken;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Cancelled;
pub(crate) trait OrCancel: Future + Sized {
fn or_cancel(
self,
token: Cancel,
) -> impl Future<Output = Result<Self::Output, Cancelled>> {
async move { token.run_until_cancelled_owned(self).await.ok_or(Cancelled) }
}
}
impl<F: Future> OrCancel for F {}
pub(crate) fn poll_now<'a, T>(
mut future: crate::gate::LocalBoxFuture<'a, T>,
) -> Result<T, crate::gate::LocalBoxFuture<'a, T>> {
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
match future.as_mut().poll(&mut cx) {
std::task::Poll::Ready(value) => Ok(value),
std::task::Poll::Pending => Err(future),
}
}