#[cfg(target_os = "fuchsia")]
mod fuchsia;
#[cfg(target_os = "fuchsia")]
use self::fuchsia as implementation;
#[cfg(all(not(target_os = "fuchsia"), not(target_arch = "wasm32")))]
mod portable;
#[cfg(all(not(target_os = "fuchsia"), not(target_arch = "wasm32")))]
use self::portable as implementation;
#[cfg(all(not(target_os = "fuchsia"), target_arch = "wasm32"))]
mod stub;
#[cfg(all(not(target_os = "fuchsia"), target_arch = "wasm32"))]
use self::stub as implementation;
pub use implementation::executor::{
LocalExecutor, MonotonicDuration, MonotonicInstant, SendExecutor, TestExecutor,
};
pub use implementation::task::{unblock, JoinHandle, Task};
pub use implementation::timer::Timer;
#[cfg(not(target_arch = "wasm32"))]
mod task_group;
#[cfg(not(target_arch = "wasm32"))]
pub use task_group::*;
#[cfg(target_os = "fuchsia")]
pub use self::fuchsia::{
executor::{BootInstant, EHandle, PacketReceiver, ReceiverRegistration},
timer::Interval,
};
pub mod scope {
pub use super::implementation::scope::{Scope, ScopeHandle};
#[cfg(target_os = "fuchsia")]
pub use super::implementation::scope::Join;
}
pub use scope::{Scope, ScopeHandle};
use futures::prelude::*;
use pin_project_lite::pin_project;
use std::pin::Pin;
use std::task::{ready, Context, Poll};
pub trait DurationExt {
fn after_now(self) -> MonotonicInstant;
}
pub trait WakeupTime {
fn into_timer(self) -> Timer;
}
#[cfg(target_os = "fuchsia")]
impl WakeupTime for std::time::Duration {
fn into_timer(self) -> Timer {
EHandle::local().mono_timers().new_timer(MonotonicInstant::now() + self.into())
}
}
#[cfg(not(target_os = "fuchsia"))]
impl WakeupTime for std::time::Duration {
fn into_timer(self) -> Timer {
Timer::from(self)
}
}
#[cfg(target_os = "fuchsia")]
impl WakeupTime for MonotonicDuration {
fn into_timer(self) -> Timer {
EHandle::local().mono_timers().new_timer(MonotonicInstant::after(self))
}
}
#[cfg(target_os = "fuchsia")]
impl WakeupTime for zx::BootDuration {
fn into_timer(self) -> Timer {
EHandle::local().boot_timers().new_timer(BootInstant::after(self))
}
}
impl DurationExt for std::time::Duration {
fn after_now(self) -> MonotonicInstant {
MonotonicInstant::now() + self.into()
}
}
pub trait TimeoutExt: Future + Sized {
fn on_timeout<WT, OT>(self, time: WT, on_timeout: OT) -> OnTimeout<Self, OT>
where
WT: WakeupTime,
OT: FnOnce() -> Self::Output,
{
OnTimeout { timer: time.into_timer(), future: self, on_timeout: Some(on_timeout) }
}
fn on_stalled<OS>(self, timeout: std::time::Duration, on_stalled: OS) -> OnStalled<Self, OS>
where
OS: FnOnce() -> Self::Output,
{
OnStalled {
timer: timeout.into_timer(),
future: self,
timeout,
on_stalled: Some(on_stalled),
}
}
}
impl<F: Future + Sized> TimeoutExt for F {}
pin_project! {
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct OnTimeout<F, OT> {
#[pin]
timer: Timer,
#[pin]
future: F,
on_timeout: Option<OT>,
}
}
impl<F: Future, OT> Future for OnTimeout<F, OT>
where
OT: FnOnce() -> F::Output,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Poll::Ready(item) = this.future.poll(cx) {
return Poll::Ready(item);
}
if let Poll::Ready(()) = this.timer.poll(cx) {
let ot = this.on_timeout.take().expect("polled withtimeout after completion");
let item = (ot)();
return Poll::Ready(item);
}
Poll::Pending
}
}
pin_project! {
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct OnStalled<F, OS> {
#[pin]
timer: Timer,
#[pin]
future: F,
timeout: std::time::Duration,
on_stalled: Option<OS>,
}
}
impl<F: Future, OS> Future for OnStalled<F, OS>
where
OS: FnOnce() -> F::Output,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
if let Poll::Ready(item) = this.future.poll(cx) {
return Poll::Ready(item);
}
match this.timer.as_mut().poll(cx) {
Poll::Ready(()) => {}
Poll::Pending => {
this.timer.set(this.timeout.into_timer());
ready!(this.timer.as_mut().poll(cx));
}
}
Poll::Ready((this.on_stalled.take().expect("polled after completion"))())
}
}
#[cfg(test)]
mod task_tests {
use super::*;
use futures::channel::oneshot;
fn run(f: impl Send + 'static + Future<Output = ()>) {
const TEST_THREADS: usize = 2;
SendExecutor::new(TEST_THREADS).run(f)
}
#[test]
fn can_detach() {
run(async move {
let (tx_started, rx_started) = oneshot::channel();
let (tx_continue, rx_continue) = oneshot::channel();
let (tx_done, rx_done) = oneshot::channel();
{
Task::spawn(async move {
tx_started.send(()).unwrap();
rx_continue.await.unwrap();
tx_done.send(()).unwrap();
})
.detach();
}
rx_started.await.unwrap();
tx_continue.send(()).unwrap();
rx_done.await.unwrap();
});
}
#[test]
fn can_join() {
run(async move {
assert_eq!(42, Task::spawn(async move { 42u8 }).await);
})
}
#[test]
fn can_join_unblock() {
run(async move {
assert_eq!(42, unblock(|| 42u8).await);
})
}
#[test]
fn can_join_unblock_local() {
LocalExecutor::new().run_singlethreaded(async move {
assert_eq!(42, unblock(|| 42u8).await);
});
}
#[test]
#[should_panic]
#[cfg_attr(feature = "variant_asan", ignore)]
fn unblock_fn_panics() {
run(async move {
unblock(|| panic!("bad")).await;
})
}
#[test]
fn can_join_local() {
LocalExecutor::new().run_singlethreaded(async move {
assert_eq!(42, Task::local(async move { 42u8 }).await);
})
}
#[test]
fn can_cancel() {
run(async move {
let (_tx_start, rx_start) = oneshot::channel::<()>();
let (tx_done, rx_done) = oneshot::channel();
let _ = Task::spawn(async move {
rx_start.await.unwrap();
tx_done.send(()).unwrap();
});
rx_done.await.expect_err("done should not be sent");
})
}
}
#[cfg(test)]
mod timer_tests {
use super::*;
use futures::future::Either;
use std::pin::pin;
#[test]
fn shorter_fires_first_instant() {
use std::time::{Duration, Instant};
let mut exec = LocalExecutor::new();
let now = Instant::now();
let shorter = pin!(Timer::new(now + Duration::from_millis(100)));
let longer = pin!(Timer::new(now + Duration::from_secs(1)));
match exec.run_singlethreaded(future::select(shorter, longer)) {
Either::Left((_, _)) => {}
Either::Right((_, _)) => panic!("wrong timer fired"),
}
}
#[cfg(target_os = "fuchsia")]
#[test]
fn can_use_zx_duration() {
let mut exec = LocalExecutor::new();
let start = MonotonicInstant::now();
let timer = Timer::new(MonotonicDuration::from_millis(100));
exec.run_singlethreaded(timer);
let end = MonotonicInstant::now();
assert!(end - start > MonotonicDuration::from_millis(100));
}
#[test]
fn can_detect_stalls() {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
let runs = Arc::new(AtomicU64::new(0));
assert_eq!(
{
let runs = runs.clone();
LocalExecutor::new().run_singlethreaded(
async move {
let mut sleep = Duration::from_millis(1);
loop {
Timer::new(sleep).await;
sleep *= 2;
runs.fetch_add(1, Ordering::SeqCst);
}
}
.on_stalled(Duration::from_secs(1), || 1u8),
)
},
1u8
);
assert!(runs.load(Ordering::SeqCst) >= 9);
}
}