cubecl_common/
future.rs

1use alloc::boxed::Box;
2use core::{future::Future, pin::Pin};
3
4/// A dynamically typed, boxed, future. Useful for futures that need to ensure they
5/// are not capturing any of their inputs.
6pub type DynFut<T> = Pin<Box<dyn Future<Output = T> + Send>>;
7
8/// Spawns a future to run detached. This will use a thread on native, or the browser runtime
9/// on WASM. The returned JoinOnDrop will join the thread when it is dropped.
10pub fn spawn_detached_fut(fut: impl Future<Output = ()> + Send + 'static) {
11    cfg_if::cfg_if! {
12        if #[cfg(target_family = "wasm")] {
13            wasm_bindgen_futures::spawn_local(fut);
14        } else if #[cfg(feature = "std")] {
15            std::thread::spawn(|| block_on(fut));
16        } else {
17            drop(fut); // Just to prevent unused.
18            panic!("spawn_detached_fut is only supported with 'std' or on 'wasm' targets");
19        }
20    }
21}
22
23/// Block until the [future](Future) is completed and returns the result.
24pub fn block_on<O>(fut: impl Future<Output = O>) -> O {
25    #[cfg(target_family = "wasm")]
26    {
27        super::reader::read_sync(fut)
28    }
29
30    #[cfg(all(not(target_family = "wasm"), not(feature = "std")))]
31    {
32        embassy_futures::block_on(fut)
33    }
34
35    #[cfg(all(not(target_family = "wasm"), feature = "std"))]
36    {
37        futures_lite::future::block_on(fut)
38    }
39}