dptree-fork 0.8.0

An asynchronous event dispatch mechanism for Rust
Documentation
//! Conditional `Send`/`Sync` helpers for wasm32 target.
//!
//! On `wasm32`, dptree handlers and their futures can capture non-`Send` or
//! non-`Sync` state. Injected dependencies still need `Send + Sync` on every
//! target, so `Rc<T>` can be captured but cannot be stored in a
//! [`DependencyMap`](crate::di::DependencyMap). This support applies to dptree,
//! not to the teloxide dispatcher, which does not support `wasm32`.

use std::future::Future;
use std::pin::Pin;

/// `Send` on native targets; no bound on `wasm32`.
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + ?Sized> MaybeSend for T {}

/// `Send` on native targets; no bound on `wasm32`.
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSend for T {}

/// `Sync` on native targets; no bound on `wasm32`.
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSync: Sync {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Sync + ?Sized> MaybeSync for T {}

/// `Sync` on native targets; no bound on `wasm32`.
#[cfg(target_arch = "wasm32")]
pub trait MaybeSync {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSync for T {}

/// A boxed future that is `Send` on native targets and not required to be `Send`
/// on `wasm32`.
#[cfg(not(target_arch = "wasm32"))]
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

#[cfg(all(test, target_arch = "wasm32"))]
mod tests {
    use std::rc::Rc;

    #[wasm_bindgen_test::wasm_bindgen_test]
    async fn handler_and_future_can_capture_rc_on_wasm32() {
        let captured = Rc::new(7_u32);
        let handler: crate::Handler<_> = crate::endpoint(move |injected: u32| {
            let captured = Rc::clone(&captured);
            async move { injected + *captured }
        });
        assert_eq!(handler.dispatch(crate::deps![42_u32]).await.break_value(), Some(49));
    }
}