use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use crate::client::transport::DynTransport;
use crate::client::transport::Transport;
#[derive(Default, Clone)]
pub(crate) struct TransportRegistry {
inner: Arc<Mutex<HashMap<String, Arc<dyn DynTransport>>>>,
}
impl Debug for TransportRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let m = self.inner.lock().unwrap();
for key in m.keys() {
write!(f, "k: {key:?}")?
}
Ok(())
}
}
impl TransportRegistry {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn add_transport<T>(&self, address_type: &str, transport: T)
where
T: Transport + 'static,
{
self.inner
.lock()
.unwrap()
.insert(address_type.to_string(), Arc::new(transport));
}
pub(crate) fn get_transport(
&self,
address_type: &str,
) -> Result<Arc<dyn DynTransport>, String> {
self.inner
.lock()
.unwrap()
.get(address_type)
.ok_or(format!(
"no transport found for address type {address_type}"
))
.cloned()
}
}
pub(crate) static GLOBAL_TRANSPORT_REGISTRY: LazyLock<TransportRegistry> =
LazyLock::new(TransportRegistry::new);