Skip to main content

atomr_core/serialization/
registry.rs

1//! Registry mapping types to serializers.
2//!
3//! The default impl only supports `JsonSerializer` to keep the public API
4//! simple. Callers who need additional codecs add an enum-based
5//! `Serializer` trait variant; the registry stays `TypeId`-keyed.
6
7use std::any::{Any, TypeId};
8use std::sync::Arc;
9
10use dashmap::DashMap;
11
12use super::json::JsonSerializer;
13use super::traits::SerializerError;
14
15#[derive(Default)]
16pub struct SerializationRegistry {
17    by_type: DashMap<TypeId, Arc<dyn Any + Send + Sync>>,
18}
19
20impl SerializationRegistry {
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    pub fn register<T>(&self, serializer: JsonSerializer<T>)
26    where
27        T: Any + Send + Sync + 'static + serde::Serialize + serde::de::DeserializeOwned,
28    {
29        self.by_type.insert(TypeId::of::<T>(), Arc::new(serializer));
30    }
31
32    pub fn to_bytes<T>(&self, value: &T) -> Result<Vec<u8>, SerializerError>
33    where
34        T: Any + Send + Sync + 'static + serde::Serialize + serde::de::DeserializeOwned,
35    {
36        let e = self.by_type.get(&TypeId::of::<T>()).ok_or(SerializerError::NotRegistered)?;
37        let s = e.clone().downcast::<JsonSerializer<T>>().map_err(|_| SerializerError::NotRegistered)?;
38        super::traits::Serializer::to_bytes(&*s, value)
39    }
40
41    pub fn from_bytes<T>(&self, bytes: &[u8]) -> Result<T, SerializerError>
42    where
43        T: Any + Send + Sync + 'static + serde::Serialize + serde::de::DeserializeOwned,
44    {
45        let e = self.by_type.get(&TypeId::of::<T>()).ok_or(SerializerError::NotRegistered)?;
46        let s = e.clone().downcast::<JsonSerializer<T>>().map_err(|_| SerializerError::NotRegistered)?;
47        super::traits::Serializer::from_bytes(&*s, bytes)
48    }
49}