cubecl_common/
reader.rs

1use core::future::Future;
2
3/// Read a future synchronously.
4///
5/// On WASM futures cannot block, so this only succeeds if the future returns immediately.
6/// If you want to handle this error, please use
7/// try_read_sync instead.
8pub fn read_sync<F: Future<Output = T>, T>(f: F) -> T {
9    try_read_sync(f).expect("Failed to read tensor data synchronously. This can happen on platforms that don't support blocking futures like WASM. If possible, try using an async variant of this function instead.")
10}
11
12/// Read a future synchronously.
13///
14/// On WASM futures cannot block, so this only succeeds if the future returns immediately.
15/// otherwise this returns None.
16pub fn try_read_sync<F: Future<Output = T>, T>(f: F) -> Option<T> {
17    #[cfg(target_family = "wasm")]
18    {
19        use core::task::Poll;
20
21        match embassy_futures::poll_once(f) {
22            Poll::Ready(output) => Some(output),
23            _ => None,
24        }
25    }
26    #[cfg(not(target_family = "wasm"))]
27    {
28        Some(super::future::block_on(f))
29    }
30}