Skip to main content

lumina_utils/
cond_send.rs

1//! Conditional `Send` bound and boxed future abstractions.
2//!
3//! On native targets futures must be `Send` (for `tokio::spawn`).
4//! On wasm32 there is only one thread, so `Send` is unnecessary and some
5//! transports (e.g. `tonic-web-wasm-client`) return `!Send` futures.
6//!
7//! This module provides:
8//! - `CondSend` — equals `Send` on native, no-op on wasm32.
9//! - `BoxFuture` — a boxed future that is `Send` on native, `!Send` on wasm32.
10//! - `into_boxed` — box a future into a `BoxFuture`.
11
12use std::future::Future;
13use std::pin::Pin;
14
15/// A conditionally compiled trait indirection for `Send` bounds.
16/// On native targets this requires `Send`.
17#[cfg(not(target_arch = "wasm32"))]
18pub trait CondSend: Send {}
19
20/// A conditionally compiled trait indirection for `Send` bounds.
21/// On wasm32 this is a no-op (no marker traits required).
22#[cfg(target_arch = "wasm32")]
23pub trait CondSend {}
24
25#[cfg(not(target_arch = "wasm32"))]
26impl<S: Send> CondSend for S {}
27
28#[cfg(target_arch = "wasm32")]
29impl<S> CondSend for S {}
30
31/// A boxed future that is `Send` on native and `!Send` on wasm32.
32#[cfg(not(target_arch = "wasm32"))]
33pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
34
35/// A boxed future that is `Send` on native and `!Send` on wasm32.
36#[cfg(target_arch = "wasm32")]
37pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
38
39/// Box a future into a `BoxFuture`.
40#[cfg(not(target_arch = "wasm32"))]
41pub fn into_boxed<F, T>(fut: F) -> BoxFuture<'static, T>
42where
43    F: Future<Output = T> + Send + 'static,
44{
45    Box::pin(fut)
46}
47
48/// Box a future into a [`BoxFuture`] (wasm32 variant).
49#[cfg(target_arch = "wasm32")]
50pub fn into_boxed<F, T>(fut: F) -> BoxFuture<'static, T>
51where
52    F: Future<Output = T> + 'static,
53{
54    Box::pin(fut)
55}