1pub use runtime::{DefaultExecutor, Runtime, TaskExecutor};
5
6use std::future::Future;
7use std::pin::Pin;
8
9pub trait Executor: Send + Sync + 'static + Clone {
15 fn spawn(&mut self, future: Pin<Box<dyn Future<Output = ()> + Send>>);
21}
22
23#[cfg(all(feature = "tokio", not(feature = "async-std")))]
24mod runtime {
25 use super::*;
26
27 pub struct Runtime {
29 rt: tokio::runtime::Runtime,
30 spawner: TaskExecutor,
31 }
32
33 impl Runtime {
34 pub fn new() -> Option<Self> {
36 Some(Runtime {
37 rt: tokio::runtime::Runtime::new().unwrap(),
38 spawner: TaskExecutor,
39 })
40 }
41
42 pub fn handle(&self) -> &TaskExecutor {
44 &self.spawner
45 }
46
47 pub fn block_on<F, T>(&mut self, future: F) -> T
50 where
51 F: Future<Output = T>,
52 {
53 self.rt.block_on(future)
54 }
55
56 pub fn spawn<F, T>(&self, future: F)
58 where
59 F: Future<Output = T> + Send + 'static,
60 T: Send + 'static,
61 {
62 self.rt.spawn(future);
63 }
64 }
65
66 #[derive(Clone)]
68 pub struct TaskExecutor;
69
70 impl TaskExecutor {
71 pub fn spawn<F>(&self, future: F)
73 where
74 F: Future + Send + 'static,
75 F::Output: Send + 'static,
76 {
77 tokio::spawn(future);
78 }
79 }
80
81 #[derive(Clone)]
82 pub struct DefaultExecutor;
84
85 impl DefaultExecutor {
86 pub fn current() -> Self {
88 Self {}
89 }
90 }
91
92 impl Executor for DefaultExecutor {
93 fn spawn(&mut self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
94 tokio::spawn(future);
95 }
96 }
97}
98
99#[cfg(all(feature = "async-std"))]
100mod runtime {
101 use super::*;
102 use async_std::task;
103
104 #[derive(Clone)]
105 pub struct TaskExecutor;
106
107 impl TaskExecutor {
108 pub fn spawn<F>(&self, future: F)
109 where
110 F: Future + Send + 'static,
111 F::Output: Send + 'static,
112 {
113 task::spawn(future);
114 }
115 }
116
117 pub struct Runtime(TaskExecutor);
118
119 impl Runtime {
120 pub fn new() -> Option<Self> {
121 Some(Runtime(TaskExecutor))
122 }
123
124 pub fn handle(&self) -> &TaskExecutor {
125 &self.0
126 }
127
128 pub fn block_on<F, T>(&mut self, future: F) -> T
129 where
130 F: Future<Output = T>,
131 {
132 task::block_on(future)
133 }
134
135 pub fn spawn<F, T>(&self, future: F)
136 where
137 F: Future<Output = T> + Send + 'static,
138 T: Send + 'static,
139 {
140 task::spawn(future);
141 }
142 }
143
144 #[derive(Clone)]
145 pub struct DefaultExecutor;
146
147 impl DefaultExecutor {
148 pub fn current() -> Self {
149 Self {}
150 }
151 }
152
153 impl Executor for DefaultExecutor {
154 fn spawn(&mut self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
155 task::spawn(future);
156 }
157 }
158}