future_runner/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/piot/swamp-render
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5
6/*!
7# future-runner
8
9A lightweight crate for executing Rust futures on different target platforms.
10
11## Features
12
13- Cross-platform future execution support (native and WASM)
14- Configurable blocking/non-blocking execution via features
15- Simple API with a single `run_future` function
16
17## Usage
18
19```rust
20use future_runner::run_future;
21
22async fn my_async_task() {
23    // Your async code here
24}
25
26fn main() {
27    run_future(my_async_task());
28}
29```
30*/
31
32#[cfg(all(not(target_arch = "wasm32"), feature = "threaded"))]
33pub fn run_future<F: std::future::Future<Output = ()> + Send + 'static>(future: F) {
34    use std::thread;
35
36    thread::spawn(move || {
37        let rt = tokio::runtime::Builder::new_current_thread()
38            .enable_all()
39            .build()
40            .expect("Failed to create runtime");
41
42        rt.block_on(future);
43    })
44    .join()
45    .expect("Thread panicked");
46}
47
48#[cfg(all(not(target_arch = "wasm32"), not(feature = "threaded")))]
49pub fn run_future<F: std::future::Future<Output = ()> + 'static>(future: F) {
50    // Existing implementation stays the same
51    #[cfg(feature = "block")]
52    futures::executor::block_on(future);
53
54    #[cfg(not(feature = "block"))]
55    {
56        let mut local_pool = futures::executor::LocalPool::new();
57        use futures::task::LocalSpawnExt;
58        let spawner = local_pool.spawner();
59        spawner.spawn_local(future).expect("Failed to spawn future");
60        local_pool.run();
61    }
62}
63
64#[cfg(target_arch = "wasm32")]
65pub fn run_future<F: std::future::Future<Output = ()> + 'static>(future: F) {
66    // WASM implementation stays the same
67    wasm_bindgen_futures::spawn_local(future);
68}