Skip to main content

timvw_rust_runtime/
maybe.rs

1//! `Send` and `Sync` natively, nothing on WebAssembly.
2//!
3//! On `wasm32-unknown-unknown` there is one thread, and what the JavaScript host hands out (a `fetch` response, a
4//! timer) cannot leave it: reqwest's futures and streams there are neither `Send` nor `Sync`. So the bounds this crate
5//! puts on services, bodies, streams and futures are [`MaybeSend`] and [`MaybeSync`]: `Send` and `Sync` natively, no
6//! bound at all on WebAssembly (`target_family = "wasm"`).
7
8use std::future::Future;
9use std::pin::Pin;
10
11use futures_core::Stream;
12
13/// `Send` natively; any type on WebAssembly (`target_family = "wasm"`), where futures and streams of the JavaScript
14/// host are not `Send`. Use it in bounds that must hold on both, such as a service given to
15/// [`Client::from_service`](crate::Client::from_service).
16#[cfg(not(target_family = "wasm"))]
17pub trait MaybeSend: Send {}
18#[cfg(not(target_family = "wasm"))]
19impl<T: Send + ?Sized> MaybeSend for T {}
20
21/// `Send` natively; any type on WebAssembly (`target_family = "wasm"`), where futures and streams of the JavaScript
22/// host are not `Send`. Use it in bounds that must hold on both, such as a service given to
23/// [`Client::from_service`](crate::Client::from_service).
24#[cfg(target_family = "wasm")]
25pub trait MaybeSend {}
26#[cfg(target_family = "wasm")]
27impl<T: ?Sized> MaybeSend for T {}
28
29/// `Sync` natively; any type on WebAssembly (`target_family = "wasm"`).
30#[cfg(not(target_family = "wasm"))]
31pub trait MaybeSync: Sync {}
32#[cfg(not(target_family = "wasm"))]
33impl<T: Sync + ?Sized> MaybeSync for T {}
34
35/// `Sync` natively; any type on WebAssembly (`target_family = "wasm"`).
36#[cfg(target_family = "wasm")]
37pub trait MaybeSync {}
38#[cfg(target_family = "wasm")]
39impl<T: ?Sized> MaybeSync for T {}
40
41/// A boxed future: `Send` natively.
42#[cfg(not(target_family = "wasm"))]
43pub(crate) type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
44#[cfg(target_family = "wasm")]
45pub(crate) type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
46
47/// A boxed stream: `Send` natively.
48#[cfg(not(target_family = "wasm"))]
49pub(crate) type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
50#[cfg(target_family = "wasm")]
51pub(crate) type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
52
53/// Boxes a stream: `Send` natively.
54pub(crate) fn box_stream<'a, S: Stream + MaybeSend + 'a>(stream: S) -> BoxStream<'a, S::Item> {
55    Box::pin(stream)
56}