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.
17///
18/// The output of this function is best-efforts, and should be checked if
19/// possible. It simply returns `true` if the connection has no hostname,
20/// or the hostname is `localhost` or `127.0.0.1`.
21pub fn guess_local_url(s: impl AsRef<str>) -> bool {
22 fn _guess_local_url(url: &str) -> bool {
23 url.parse::<Url>().is_ok_and(|url| {
24 url.host_str().is_none_or(|host| host == "localhost" || host == "127.0.0.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 WASM this will be a `wasm-bindgen-futures::spawn_local` call, while
35 /// in native it will be a `tokio::spawn` call.
36 fn spawn_task(self);
37}
38
39#[cfg(not(target_family = "wasm"))]
40impl<T> Spawnable for T
41where
42 T: Future<Output = ()> + Send + 'static,
43{
44 fn spawn_task(self) {
45 tokio::spawn(self);
46 }
47}
48
49#[cfg(target_family = "wasm")]
50impl<T> Spawnable for T
51where
52 T: Future<Output = ()> + 'static,
53{
54 fn spawn_task(self) {
55 #[cfg(not(feature = "wasm-bindgen"))]
56 panic!("The 'wasm-bindgen' feature must be enabled");
57
58 #[cfg(feature = "wasm-bindgen")]
59 wasm_bindgen_futures::spawn_local(self);
60 }
61}