use std::fmt;
use std::time::{Duration, Instant};
use super::executor::{BoxFuture, Executor, LocalBoxFuture, NotLocal};
#[derive(Clone)]
pub struct TokioExecutor {
handle: ::tokio::runtime::Handle,
}
impl TokioExecutor {
pub fn new(handle: ::tokio::runtime::Handle) -> Self {
Self { handle }
}
pub fn current() -> Option<Self> {
::tokio::runtime::Handle::try_current().ok().map(Self::new)
}
pub fn handle(&self) -> &::tokio::runtime::Handle {
&self.handle
}
}
impl fmt::Debug for TokioExecutor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TokioExecutor")
.field("runtime_flavor", &self.handle.runtime_flavor())
.finish()
}
}
impl Executor for TokioExecutor {
fn spawn(&self, fut: BoxFuture<'static, ()>) {
drop(self.handle.spawn(fut));
}
fn spawn_local(&self, _fut: LocalBoxFuture<'static, ()>) -> Result<(), NotLocal> {
Err(NotLocal)
}
fn spawn_blocking(&self, f: Box<dyn FnOnce() + Send>) {
drop(self.handle.spawn_blocking(f));
}
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
let _guard = self.handle.enter();
Box::pin(::tokio::time::sleep(d))
}
fn now(&self) -> Instant {
let _guard = self.handle.enter();
::tokio::time::Instant::now().into_std()
}
}