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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Executor agnostic task spawning
//!
//! ```rust
//! # use core::future::Future;
//! # use core::pin::Pin;
//! # type BoxedFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
//! #[async_std::main]
//! async fn main() {
//!     struct AsyncStd;
//!     impl async_spawner::Executor for AsyncStd {
//!         fn block_on(&self, future: BoxedFuture) {
//!             async_std::task::block_on(future);
//!         }
//!
//!         fn spawn(&self, future: BoxedFuture) -> BoxedFuture {
//!             Box::pin(async_std::task::spawn(future))
//!         }
//!
//!         fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture {
//!             Box::pin(async_std::task::spawn_blocking(task))
//!         }
//!
//!         fn spawn_local(
//!             &self,
//!             future: Pin<Box<dyn Future<Output = ()> + 'static>>,
//!         ) -> BoxedFuture {
//!             Box::pin(async_std::task::spawn_local(future))
//!         }
//!     }
//!
//!     async_spawner::register_executor(Box::new(AsyncStd));
//!     let res = async_spawner::spawn(async {
//!         println!("executor agnostic spawning");
//!         1
//!     })
//!     .await;
//!     assert_eq!(res, 1);
//! }
//! ```
//!
//! ```rust
//! # use core::future::Future;
//! # use core::pin::Pin;
//! # type BoxedFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
//! #[tokio::main]
//! async fn main() {
//!     struct Tokio;
//!     impl async_spawner::Executor for Tokio {
//!         fn block_on(&self, future: BoxedFuture) {
//!             tokio::runtime::Builder::new_multi_thread()
//!                 .build()
//!                 .unwrap()
//!                 .block_on(future);
//!         }
//!
//!         fn spawn(&self, future: BoxedFuture) -> BoxedFuture {
//!             Box::pin(async { tokio::task::spawn(future).await.unwrap() })
//!         }
//!
//!         fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture {
//!             Box::pin(async { tokio::task::spawn_blocking(task).await.unwrap() })
//!         }
//!
//!         fn spawn_local(
//!             &self,
//!             future: Pin<Box<dyn Future<Output = ()> + 'static>>,
//!         ) -> BoxedFuture {
//!             let handle = tokio::task::spawn_local(future);
//!             Box::pin(async { handle.await.unwrap() })
//!         }
//!     }
//!
//!     async_spawner::register_executor(Box::new(Tokio));
//!     let res = async_spawner::spawn(async {
//!         println!("executor agnostic spawning");
//!         1
//!     })
//!     .await;
//!     assert_eq!(res, 1);
//! }
//! ```
#![deny(missing_docs)]
#![deny(warnings)]
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures::channel::oneshot;
use futures::future::FutureExt;
use once_cell::sync::OnceCell;

type BoxedFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;

/// Trait abstracting over an executor.
pub trait Executor: Send + Sync {
    /// Blocks until the future has finished.
    fn block_on(&self, future: BoxedFuture);

    /// Spawns an asynchronous task using the underlying executor.
    fn spawn(&self, future: BoxedFuture) -> BoxedFuture;

    /// Runs the provided closure on a thread, which can execute blocking tasks asynchronously.
    fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture;

    /// Spawns a future that doesn't implement [Send].
    ///
    /// The spawned future will be executed on the same thread that called `spawn_local`.
    ///
    /// [Send]: https://doc.rust-lang.org/std/marker/trait.Send.html
    fn spawn_local(&self, future: Pin<Box<dyn Future<Output = ()> + 'static>>) -> BoxedFuture;
}

static EXECUTOR: OnceCell<Box<dyn Executor>> = OnceCell::new();

/// Error returned by `try_register_executor` indicating that an executor was registered.
#[derive(Debug)]
pub struct ExecutorRegistered;

impl core::fmt::Display for ExecutorRegistered {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "async_spawner: executor already registered")
    }
}

impl std::error::Error for ExecutorRegistered {}

/// Tries registering an executor.
pub fn try_register_executor(executor: Box<dyn Executor>) -> Result<(), ExecutorRegistered> {
    EXECUTOR.set(executor).map_err(|_| ExecutorRegistered)
}

/// Register an executor. Panics if an executor was already registered.
pub fn register_executor(executor: Box<dyn Executor>) {
    try_register_executor(executor).unwrap();
}

/// Returns the registered executor.
pub fn executor() -> &'static dyn Executor {
    &**EXECUTOR
        .get()
        .expect("async_spawner: no executor registered")
}

/// Blocks until the future has finished.
pub fn block_on<F, T>(future: F) -> T
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    let (tx, rx) = oneshot::channel();
    executor().block_on(Box::pin(async move {
        let res = future.await;
        tx.send(res).ok();
    }));
    rx.now_or_never().unwrap().unwrap()
}

/// Executor agnostic join handle.
pub struct JoinHandle<T> {
    handle: BoxedFuture,
    rx: oneshot::Receiver<T>,
}

impl<T> Future for JoinHandle<T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        if let Poll::Ready(()) = Pin::new(&mut self.handle).poll(cx) {
            if let Poll::Ready(Ok(res)) = Pin::new(&mut self.rx).poll(cx) {
                Poll::Ready(res)
            } else {
                panic!("task paniced");
            }
        } else {
            Poll::Pending
        }
    }
}

/// Spawns an asynchronous task using the underlying executor.
pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    let (tx, rx) = oneshot::channel();
    let handle = executor().spawn(Box::pin(async move {
        let res = future.await;
        tx.send(res).ok();
    }));
    JoinHandle { handle, rx }
}

/// Runs the provided closure on a thread, which can execute blocking tasks asynchronously.
pub fn spawn_blocking<F, T>(task: F) -> JoinHandle<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    let (tx, rx) = oneshot::channel();
    let handle = executor().spawn_blocking(Box::new(move || {
        let res = task();
        tx.send(res).ok();
    }));
    JoinHandle { handle, rx }
}

/// Spawns a future that doesn't implement [Send].
///
/// The spawned future will be executed on the same thread that called `spawn_local`.
///
/// [Send]: https://doc.rust-lang.org/std/marker/trait.Send.html
pub fn spawn_local<F, T>(future: F) -> JoinHandle<T>
where
    F: Future<Output = T> + 'static,
    T: Send + 'static,
{
    let (tx, rx) = oneshot::channel();
    let handle = executor().spawn_local(Box::pin(async move {
        let res = future.await;
        tx.send(res).ok();
    }));
    JoinHandle { handle, rx }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[async_std::test]
    #[ignore]
    async fn test_async_std() {
        struct AsyncStd;

        impl Executor for AsyncStd {
            fn block_on(&self, future: BoxedFuture) {
                async_std::task::block_on(future);
            }

            fn spawn(&self, future: BoxedFuture) -> BoxedFuture {
                Box::pin(async_std::task::spawn(future))
            }

            fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture {
                Box::pin(async_std::task::spawn_blocking(task))
            }

            fn spawn_local(
                &self,
                future: Pin<Box<dyn Future<Output = ()> + 'static>>,
            ) -> BoxedFuture {
                Box::pin(async_std::task::spawn_local(future))
            }
        }

        try_register_executor(Box::new(AsyncStd)).ok();
        let res = spawn(async {
            println!("spaw on async-std");
            1
        })
        .await;
        assert_eq!(res, 1);
        let res = spawn_blocking(|| {
            println!("spawn_blocking on async-std");
            1
        })
        .await;
        assert_eq!(res, 1);
        let res = spawn_local(async {
            println!("spaw_local on async-std");
            1
        })
        .await;
        assert_eq!(res, 1);
        let res = block_on(async {
            println!("block_on on async_std");
            1
        });
        assert_eq!(res, 1);
    }

    #[tokio::test]
    #[ignore]
    async fn test_tokio() {
        struct Tokio;

        impl Executor for Tokio {
            fn block_on(&self, future: BoxedFuture) {
                tokio::runtime::Builder::new_multi_thread()
                    .build()
                    .unwrap()
                    .block_on(future);
            }

            fn spawn(&self, future: BoxedFuture) -> BoxedFuture {
                Box::pin(async { tokio::task::spawn(future).await.unwrap() })
            }

            fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture {
                Box::pin(async { tokio::task::spawn_blocking(task).await.unwrap() })
            }

            fn spawn_local(
                &self,
                future: Pin<Box<dyn Future<Output = ()> + 'static>>,
            ) -> BoxedFuture {
                let handle = tokio::task::spawn_local(future);
                Box::pin(async { handle.await.unwrap() })
            }
        }

        try_register_executor(Box::new(Tokio)).ok();
        let res = spawn(async {
            println!("spaw on tokio");
            1
        })
        .await;
        assert_eq!(res, 1);
        let res = spawn_blocking(|| {
            println!("spawn_blocking on tokio");
            1
        })
        .await;
        assert_eq!(res, 1);
        tokio::task::LocalSet::new()
            .run_until(async {
                let res = spawn_local(async {
                    println!("spaw_local on tokio");
                    1
                })
                .await;
                assert_eq!(res, 1);
            })
            .await;
        spawn_blocking(|| {
            let res = block_on(async {
                println!("block_on on tokio");
                1
            });
            assert_eq!(res, 1);
        })
        .await;
    }
}