Skip to main content

autoagents_core/
utils.rs

1use futures_core::Stream;
2#[cfg(target_arch = "wasm32")]
3use futures_util::stream::StreamExt;
4use std::pin::Pin;
5
6// -----------------------------
7// Channel aliases
8// -----------------------------
9#[cfg(not(target_arch = "wasm32"))]
10pub use tokio::sync::mpsc::{Receiver, Sender, channel};
11
12#[cfg(target_arch = "wasm32")]
13pub use futures::channel::mpsc::{Receiver, Sender, channel};
14
15// -----------------------------
16// Unified boxed stream type
17// -----------------------------
18#[cfg(not(target_arch = "wasm32"))]
19pub type BoxEventStream<T> = Pin<Box<dyn Stream<Item = T> + Send + Sync>>;
20
21#[cfg(target_arch = "wasm32")]
22pub type BoxEventStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
23
24// -----------------------------
25// Conversion helpers
26// -----------------------------
27#[cfg(not(target_arch = "wasm32"))]
28pub(crate) fn receiver_into_stream<T: 'static + Send>(rx: Receiver<T>) -> BoxEventStream<T> {
29    use tokio_stream::wrappers::ReceiverStream;
30    Box::pin(ReceiverStream::new(rx))
31}
32
33#[cfg(target_arch = "wasm32")]
34pub(crate) fn receiver_into_stream<T: 'static + Send>(rx: Receiver<T>) -> BoxEventStream<T> {
35    rx.boxed()
36}
37
38// Platform-specific spawn functions
39#[cfg(not(target_arch = "wasm32"))]
40pub(crate) fn spawn_future<F>(fut: F) -> tokio::task::JoinHandle<F::Output>
41where
42    F: std::future::Future + Send + 'static,
43    F::Output: Send + 'static,
44{
45    tokio::spawn(fut)
46}
47
48#[cfg(target_arch = "wasm32")]
49pub(crate) fn spawn_future<F>(fut: F)
50where
51    F: std::future::Future<Output = ()> + 'static,
52{
53    wasm_bindgen_futures::spawn_local(fut)
54}