#![deny(unsafe_code)]
#![warn(
missing_debug_implementations,
missing_docs,
nonstandard_style,
rust_2018_idioms
)]
use futures::executor;
use futures::future::BoxFuture;
use futures::prelude::*;
use futures::task::SpawnError;
use std::cell::Cell;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::time::{Duration, Instant};
mod tcp;
mod time;
mod udp;
pub use tcp::*;
pub use time::*;
pub use udp::*;
thread_local! {
static RUNTIME: Cell<Option<&'static dyn Runtime>> = Cell::new(None);
}
#[inline]
pub fn current_runtime() -> &'static dyn Runtime {
RUNTIME.with(|r| r.get().expect("the runtime has not been set"))
}
pub fn set_runtime(runtime: &'static dyn Runtime) {
RUNTIME.with(|r| {
assert!(r.get().is_none(), "the runtime has already been set");
r.set(Some(runtime))
});
}
pub fn enter<R, F, T>(rt: R, fut: F) -> T
where
R: Runtime,
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = futures::channel::oneshot::channel();
let fut = async move {
let t = fut.await;
let _ = tx.send(t);
};
rt.spawn_boxed(fut.boxed()).expect("cannot spawn a future");
executor::block_on(rx).expect("the main future has panicked")
}
pub trait Runtime: Send + Sync + 'static {
fn spawn_boxed(&self, fut: BoxFuture<'static, ()>) -> Result<(), SpawnError>;
fn connect_tcp_stream(
&self,
addr: &SocketAddr,
) -> BoxFuture<'static, io::Result<Pin<Box<dyn TcpStream>>>>;
fn bind_tcp_listener(&self, addr: &SocketAddr) -> io::Result<Pin<Box<dyn TcpListener>>>;
fn bind_udp_socket(&self, addr: &SocketAddr) -> io::Result<Pin<Box<dyn UdpSocket>>>;
fn new_delay(&self, dur: Duration) -> Pin<Box<dyn Delay>>;
fn new_delay_at(&self, at: Instant) -> Pin<Box<dyn Delay>>;
fn new_interval(&self, dur: Duration) -> Pin<Box<dyn Interval>>;
}