use crate::envelope::StreamItem;
use crate::error::TransportError;
use futures_core::Stream;
use serde_json::Value;
use std::fmt;
use std::pin::Pin;
#[cfg(not(target_arch = "wasm32"))]
pub type ItemStream<'a> =
Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type ItemStream<'a> = Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MethodRef {
namespace: &'static str,
method: &'static str,
path: &'static str,
}
impl MethodRef {
pub const fn new(namespace: &'static str, method: &'static str) -> Self {
Self { namespace, method, path: "" }
}
pub fn at(self, path: &'static str) -> Self {
if path.is_empty() || path == self.namespace {
Self { path: "", ..self }
} else {
Self { path, ..self }
}
}
pub const fn namespace(&self) -> &'static str {
self.namespace
}
pub const fn method(&self) -> &'static str {
self.method
}
pub const fn path(&self) -> &'static str {
if self.path.is_empty() {
self.namespace
} else {
self.path
}
}
pub fn qualified(&self) -> String {
format!("{}.{}", self.path(), self.method)
}
}
impl fmt::Display for MethodRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.path(), self.method)
}
}
#[doc(hidden)]
pub fn join_path(parent: &'static str, segment: &'static str) -> &'static str {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
if parent.is_empty() {
return segment;
}
static PATHS: OnceLock<Mutex<HashMap<(&'static str, &'static str), &'static str>>> = OnceLock::new();
let mut paths = PATHS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
paths
.entry((parent, segment))
.or_insert_with(|| Box::leak(format!("{parent}.{segment}").into_boxed_str()))
}
pub trait Transport {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
}
impl<T: Transport + ?Sized> Transport for &T {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
}
impl<T: Transport + ?Sized> Transport for Box<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
}
impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
}
impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
}