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.
24#[cfg_attr(feature = "tracing", tracing::instrument(skip(fut)))]
25#[cfg_attr(feature = "std", allow(clippy::needless_lifetimes))]
26pub fn block_on<O>(fut: impl Future<Output = O>) -> O {
27    #[cfg(target_family = "wasm")]
28    {
29        super::reader::read_sync(fut)
30    }
31
32    #[cfg(all(not(target_family = "wasm"), not(feature = "std")))]
33    {
34        embassy_futures::block_on(fut)
35    }
36
37    #[cfg(all(not(target_family = "wasm"), feature = "std"))]
38    {
39        futures_lite::future::block_on(fut)
40    }
41}