mod cancel;
pub use cancel::{CancellationToken, WaitForCancel};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Elapsed;
pub struct BlockingHandle {
inner: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
}
impl BlockingHandle {
fn new(fut: impl Future<Output = ()> + Send + 'static) -> Self {
Self {
inner: Box::pin(fut),
}
}
}
impl Future for BlockingHandle {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.inner.as_mut().poll(cx)
}
}
#[cfg(not(feature = "tokio"))]
mod imp {
use super::*;
pub fn spawn<F>(future: F)
where
F: Future<Output = ()> + Send + 'static,
{
async_global_executor::spawn(future).detach();
}
pub fn sleep(dur: Duration) -> impl Future<Output = ()> + Send + 'static {
futures_timer::Delay::new(dur)
}
}
#[cfg(feature = "tokio")]
mod imp {
use super::*;
pub fn spawn<F>(future: F)
where
F: Future<Output = ()> + Send + 'static,
{
tokio::spawn(future);
}
pub fn sleep(dur: Duration) -> impl Future<Output = ()> + Send + 'static {
tokio::time::sleep(dur)
}
}
pub fn spawn<F>(future: F)
where
F: Future<Output = ()> + Send + 'static,
{
imp::spawn(future)
}
pub fn spawn_blocking<F, R>(f: F) -> BlockingHandle
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = async_channel::bounded::<()>(1);
std::thread::spawn(move || {
let _ = f();
let _ = tx.try_send(());
});
BlockingHandle::new(async move {
let _ = rx.recv().await;
})
}
pub async fn spawn_blocking_value<F, R>(f: F) -> R
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = async_channel::bounded::<R>(1);
std::thread::spawn(move || {
let _ = tx.send_blocking(f());
});
rx.recv().await.expect("blocking task panicked")
}
pub fn sleep(dur: Duration) -> impl Future<Output = ()> + Send + 'static {
imp::sleep(dur)
}
pub async fn timeout<F>(dur: Duration, fut: F) -> Result<F::Output, Elapsed>
where
F: Future,
{
enum Outcome<T> {
Value(T),
TimedOut,
}
match futures_lite::future::race(async { Outcome::Value(fut.await) }, async {
sleep(dur).await;
Outcome::TimedOut
})
.await
{
Outcome::Value(output) => Ok(output),
Outcome::TimedOut => Err(Elapsed),
}
}
pub fn block_on<F: Future>(future: F) -> F::Output {
futures_lite::future::block_on(future)
}
pub mod oneshot {
pub use futures::channel::oneshot::{channel, Canceled, Receiver, Sender};
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[test]
fn block_on_runs_future_to_completion() {
let value = block_on(async { 7 });
assert_eq!(value, 7);
}
#[test]
fn spawn_blocking_value_returns_result() {
let value = block_on(spawn_blocking_value(|| 21 * 2));
assert_eq!(value, 42);
}
#[test]
fn spawn_blocking_handle_completes() {
let flag = Arc::new(AtomicBool::new(false));
let flag_clone = flag.clone();
let handle = spawn_blocking(move || {
flag_clone.store(true, Ordering::SeqCst);
});
block_on(handle);
assert!(flag.load(Ordering::SeqCst));
}
#[test]
fn timeout_resolves_value_when_future_completes_first() {
let result = block_on(timeout(Duration::from_secs(5), async { 42 }));
assert_eq!(result, Ok(42));
}
#[test]
fn timeout_returns_elapsed_on_deadline() {
let result = block_on(timeout(Duration::from_millis(10), async {
futures::future::pending::<()>().await;
}));
assert_eq!(result, Err(Elapsed));
}
#[test]
fn spawn_runs_detached_future() {
let flag = Arc::new(AtomicBool::new(false));
let flag_clone = flag.clone();
spawn(async move {
flag_clone.store(true, Ordering::SeqCst);
});
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while !flag.load(Ordering::SeqCst) && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(flag.load(Ordering::SeqCst));
}
}