Skip to main content

dptree/
send.rs

1//! Conditional `Send`/`Sync` helpers for wasm32 target.
2//!
3//! On `wasm32`, dptree handlers and their futures can capture non-`Send` or
4//! non-`Sync` state. Injected dependencies still need `Send + Sync` on every
5//! target, so `Rc<T>` can be captured but cannot be stored in a
6//! [`DependencyMap`](crate::di::DependencyMap). This support applies to dptree,
7//! not to the teloxide dispatcher, which does not support `wasm32`.
8
9use std::future::Future;
10use std::pin::Pin;
11
12/// `Send` on native targets; no bound on `wasm32`.
13#[cfg(not(target_arch = "wasm32"))]
14pub trait MaybeSend: Send {}
15#[cfg(not(target_arch = "wasm32"))]
16impl<T: Send + ?Sized> MaybeSend for T {}
17
18/// `Send` on native targets; no bound on `wasm32`.
19#[cfg(target_arch = "wasm32")]
20pub trait MaybeSend {}
21#[cfg(target_arch = "wasm32")]
22impl<T: ?Sized> MaybeSend for T {}
23
24/// `Sync` on native targets; no bound on `wasm32`.
25#[cfg(not(target_arch = "wasm32"))]
26pub trait MaybeSync: Sync {}
27#[cfg(not(target_arch = "wasm32"))]
28impl<T: Sync + ?Sized> MaybeSync for T {}
29
30/// `Sync` on native targets; no bound on `wasm32`.
31#[cfg(target_arch = "wasm32")]
32pub trait MaybeSync {}
33#[cfg(target_arch = "wasm32")]
34impl<T: ?Sized> MaybeSync for T {}
35
36/// A boxed future that is `Send` on native targets and not required to be `Send`
37/// on `wasm32`.
38#[cfg(not(target_arch = "wasm32"))]
39pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
40#[cfg(target_arch = "wasm32")]
41pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
42
43#[cfg(all(test, target_arch = "wasm32"))]
44mod tests {
45    use std::rc::Rc;
46
47    #[wasm_bindgen_test::wasm_bindgen_test]
48    async fn handler_and_future_can_capture_rc_on_wasm32() {
49        let captured = Rc::new(7_u32);
50        let handler: crate::Handler<_> = crate::endpoint(move |injected: u32| {
51            let captured = Rc::clone(&captured);
52            async move { injected + *captured }
53        });
54        assert_eq!(handler.dispatch(crate::deps![42_u32]).await.break_value(), Some(49));
55    }
56}