1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#![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>>;
}