alloy_transport/
utils.rs

1use crate::{TransportError, TransportResult};
2use serde::Serialize;
3use serde_json::value::{to_raw_value, RawValue};
4use std::future::Future;
5use url::Url;
6
7/// Convert to a `Box<RawValue>` from a `Serialize` type, mapping the error
8/// to a `TransportError`.
9pub fn to_json_raw_value<S>(s: &S) -> TransportResult<Box<RawValue>>
10where
11    S: Serialize,
12{
13    to_raw_value(s).map_err(TransportError::ser_err)
14}
15
16/// Guess whether the URL is local, based on the hostname or IP.
17///
18/// Best-effort heuristic: returns `true` if the connection has no hostname, or
19/// the host is `localhost`, `127.0.0.1`, or the IPv6 loopback `::1`.
20pub fn guess_local_url(s: impl AsRef<str>) -> bool {
21    fn _guess_local_url(url: &str) -> bool {
22        url.parse::<Url>().is_ok_and(|url| {
23            url.host_str()
24                .is_none_or(|host| host == "localhost" || host == "127.0.0.1" || host == "::1")
25        })
26    }
27    _guess_local_url(s.as_ref())
28}
29
30#[doc(hidden)]
31pub trait Spawnable {
32    /// Spawn the future as a task.
33    ///
34    /// In wasm32-unknown-unknown this will be a `wasm-bindgen-futures::spawn_local` call,
35    /// in wasm32-wasip1 it will be a `tokio::task::spawn_local` call,
36    /// and native will be a `tokio::spawn` call.
37    fn spawn_task(self);
38}
39
40#[cfg(not(target_family = "wasm"))]
41impl<T> Spawnable for T
42where
43    T: Future<Output = ()> + Send + 'static,
44{
45    fn spawn_task(self) {
46        tokio::spawn(self);
47    }
48}
49
50#[cfg(all(target_family = "wasm", target_os = "unknown"))]
51impl<T> Spawnable for T
52where
53    T: Future<Output = ()> + 'static,
54{
55    fn spawn_task(self) {
56        #[cfg(not(feature = "wasm-bindgen"))]
57        panic!("The 'wasm-bindgen' feature must be enabled");
58
59        #[cfg(feature = "wasm-bindgen")]
60        wasm_bindgen_futures::spawn_local(self);
61    }
62}
63
64#[cfg(all(target_family = "wasm", target_os = "wasi"))]
65impl<T> Spawnable for T
66where
67    T: Future<Output = ()> + 'static,
68{
69    fn spawn_task(self) {
70        tokio::task::spawn_local(self);
71    }
72}