Remove create_serde_registry_for_trait macro (#1815)

* remove `create_serde_registry_for_trait` macro

* fix `clippy` errors

* fix formatting
This commit is contained in:
Karthik Prakash 2024-01-28 22:21:50 +05:30 committed by GitHub
parent e7df233dc1
commit 07f9a9d06a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -4,6 +4,7 @@ use alloc::boxed::Box;
use core::{any::Any, fmt::Debug}; use core::{any::Any, fmt::Debug};
use serde::{de::DeserializeSeed, Deserialize, Deserializer, Serialize, Serializer}; use serde::{de::DeserializeSeed, Deserialize, Deserializer, Serialize, Serializer};
pub use serdeany_registry::*;
/// A (de)serializable Any trait /// A (de)serializable Any trait
pub trait SerdeAny: Any + erased_serde::Serialize + Debug { pub trait SerdeAny: Any + erased_serde::Serialize + Debug {
@ -63,11 +64,7 @@ where
/// Creates the [`serde`] registry for serialization and deserialization of [`SerdeAny`]. /// Creates the [`serde`] registry for serialization and deserialization of [`SerdeAny`].
/// Each element needs to be registered so that it can be deserialized. /// Each element needs to be registered so that it can be deserialized.
#[macro_export] pub mod serdeany_registry {
macro_rules! create_serde_registry_for_trait {
($mod_name:ident, $trait_name:path) => {
/// A [`crate::serdeany`] module.
pub mod $mod_name {
use alloc::boxed::Box; use alloc::boxed::Box;
use core::{any::TypeId, fmt}; use core::{any::TypeId, fmt};
@ -78,7 +75,8 @@ macro_rules! create_serde_registry_for_trait {
}; };
use postcard; use postcard;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use $crate::{
use crate::{
anymap::{pack_type_id, unpack_type_id}, anymap::{pack_type_id, unpack_type_id},
hash_std, hash_std,
serdeany::{DeserializeCallback, DeserializeCallbackSeed}, serdeany::{DeserializeCallback, DeserializeCallbackSeed},
@ -90,7 +88,7 @@ macro_rules! create_serde_registry_for_trait {
pub struct BoxDynVisitor {} pub struct BoxDynVisitor {}
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
impl<'de> serde::de::Visitor<'de> for BoxDynVisitor { impl<'de> serde::de::Visitor<'de> for BoxDynVisitor {
type Value = Box<dyn $trait_name>; type Value = Box<dyn crate::serdeany::SerdeAny>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Expecting a serialized trait object") formatter.write_str("Expecting a serialized trait object")
@ -109,7 +107,7 @@ macro_rules! create_serde_registry_for_trait {
.get(&id) .get(&id)
.expect("Cannot deserialize an unregistered type") .expect("Cannot deserialize an unregistered type")
}; };
let seed = DeserializeCallbackSeed::<dyn $trait_name> { cb }; let seed = DeserializeCallbackSeed::<dyn crate::serdeany::SerdeAny> { cb };
let obj: Self::Value = visitor.next_element_seed(seed)?.unwrap(); let obj: Self::Value = visitor.next_element_seed(seed)?.unwrap();
Ok(obj) Ok(obj)
} }
@ -117,7 +115,7 @@ macro_rules! create_serde_registry_for_trait {
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
struct Registry { struct Registry {
deserializers: Option<HashMap<u128, DeserializeCallback<dyn $trait_name>>>, deserializers: Option<HashMap<u128, DeserializeCallback<dyn crate::serdeany::SerdeAny>>>,
finalized: bool, finalized: bool,
} }
@ -125,7 +123,7 @@ macro_rules! create_serde_registry_for_trait {
impl Registry { impl Registry {
pub fn register<T>(&mut self) pub fn register<T>(&mut self)
where where
T: $trait_name + Serialize + serde::de::DeserializeOwned, T: crate::serdeany::SerdeAny + Serialize + serde::de::DeserializeOwned,
{ {
assert!(!self.finalized, "Registry is already finalized!"); assert!(!self.finalized, "Registry is already finalized!");
@ -159,7 +157,7 @@ macro_rules! create_serde_registry_for_trait {
/// It dereferences the `REGISTRY` hashmap and adds the given type to it. /// It dereferences the `REGISTRY` hashmap and adds the given type to it.
pub unsafe fn register<T>() pub unsafe fn register<T>()
where where
T: $trait_name + Serialize + serde::de::DeserializeOwned, T: crate::serdeany::SerdeAny + Serialize + serde::de::DeserializeOwned,
{ {
unsafe { unsafe {
REGISTRY.register::<T>(); REGISTRY.register::<T>();
@ -183,7 +181,7 @@ macro_rules! create_serde_registry_for_trait {
#[allow(clippy::unsafe_derive_deserialize)] #[allow(clippy::unsafe_derive_deserialize)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct SerdeAnyMap { pub struct SerdeAnyMap {
map: HashMap<u128, Box<dyn $trait_name>>, map: HashMap<u128, Box<dyn crate::serdeany::SerdeAny>>,
} }
// Cloning by serializing and deserializing. It ain't fast, but it's honest work. // Cloning by serializing and deserializing. It ain't fast, but it's honest work.
@ -218,7 +216,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn get<T>(&self) -> Option<&T> pub fn get<T>(&self) -> Option<&T>
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.map self.map
.get(&unpack_type_id(TypeId::of::<T>())) .get(&unpack_type_id(TypeId::of::<T>()))
@ -230,7 +228,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn get_mut<T>(&mut self) -> Option<&mut T> pub fn get_mut<T>(&mut self) -> Option<&mut T>
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.map self.map
.get_mut(&unpack_type_id(TypeId::of::<T>())) .get_mut(&unpack_type_id(TypeId::of::<T>()))
@ -242,7 +240,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn remove<T>(&mut self) -> Option<Box<T>> pub fn remove<T>(&mut self) -> Option<Box<T>>
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.map self.map
.remove(&unpack_type_id(TypeId::of::<T>())) .remove(&unpack_type_id(TypeId::of::<T>()))
@ -253,7 +251,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn insert<T>(&mut self, t: T) pub fn insert<T>(&mut self, t: T)
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.insert_boxed(Box::new(t)); self.insert_boxed(Box::new(t));
} }
@ -262,7 +260,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn insert_boxed<T>(&mut self, t: Box<T>) pub fn insert_boxed<T>(&mut self, t: Box<T>)
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
let id = unpack_type_id(TypeId::of::<T>()); let id = unpack_type_id(TypeId::of::<T>());
assert!( assert!(
@ -299,7 +297,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn contains<T>(&self) -> bool pub fn contains<T>(&self) -> bool
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.map.contains_key(&unpack_type_id(TypeId::of::<T>())) self.map.contains_key(&unpack_type_id(TypeId::of::<T>()))
} }
@ -324,7 +322,7 @@ macro_rules! create_serde_registry_for_trait {
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct NamedSerdeAnyMap { pub struct NamedSerdeAnyMap {
map: HashMap<u128, HashMap<u64, Box<dyn $trait_name>>>, map: HashMap<u128, HashMap<u64, Box<dyn crate::serdeany::SerdeAny>>>,
} }
// Cloning by serializing and deserializing. It ain't fast, but it's honest work. // Cloning by serializing and deserializing. It ain't fast, but it's honest work.
@ -343,7 +341,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn get<T>(&self, name: &str) -> Option<&T> pub fn get<T>(&self, name: &str) -> Option<&T>
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
match self.map.get(&unpack_type_id(TypeId::of::<T>())) { match self.map.get(&unpack_type_id(TypeId::of::<T>())) {
None => None, None => None,
@ -357,12 +355,14 @@ macro_rules! create_serde_registry_for_trait {
#[must_use] #[must_use]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[inline] #[inline]
pub fn by_typeid(&self, name: &str, typeid: &TypeId) -> Option<&dyn $trait_name> { pub fn by_typeid(
&self,
name: &str,
typeid: &TypeId,
) -> Option<&dyn crate::serdeany::SerdeAny> {
match self.map.get(&unpack_type_id(*typeid)) { match self.map.get(&unpack_type_id(*typeid)) {
None => None, None => None,
Some(h) => h Some(h) => h.get(&hash_std(name.as_bytes())).map(AsRef::as_ref),
.get(&hash_std(name.as_bytes()))
.map(AsRef::as_ref),
} }
} }
@ -371,7 +371,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn get_mut<T>(&mut self, name: &str) -> Option<&mut T> pub fn get_mut<T>(&mut self, name: &str) -> Option<&mut T>
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
match self.map.get_mut(&unpack_type_id(TypeId::of::<T>())) { match self.map.get_mut(&unpack_type_id(TypeId::of::<T>())) {
None => None, None => None,
@ -388,12 +388,10 @@ macro_rules! create_serde_registry_for_trait {
&mut self, &mut self,
name: &str, name: &str,
typeid: &TypeId, typeid: &TypeId,
) -> Option<&mut dyn $trait_name> { ) -> Option<&mut dyn crate::serdeany::SerdeAny> {
match self.map.get_mut(&unpack_type_id(*typeid)) { match self.map.get_mut(&unpack_type_id(*typeid)) {
None => None, None => None,
Some(h) => h Some(h) => h.get_mut(&hash_std(name.as_bytes())).map(AsMut::as_mut),
.get_mut(&hash_std(name.as_bytes()))
.map(AsMut::as_mut),
} }
} }
@ -401,23 +399,22 @@ macro_rules! create_serde_registry_for_trait {
#[must_use] #[must_use]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[inline] #[inline]
#[allow(clippy::type_complexity)]
pub fn get_all<T>( pub fn get_all<T>(
&self, &self,
) -> Option< ) -> Option<
core::iter::Map< core::iter::Map<
Values<'_, u64, Box<dyn $trait_name>>, Values<'_, u64, Box<dyn crate::serdeany::SerdeAny>>,
fn(&Box<dyn $trait_name>) -> &T, fn(&Box<dyn crate::serdeany::SerdeAny>) -> &T,
>, >,
> >
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
#[allow(clippy::manual_map)] #[allow(clippy::manual_map)]
match self.map.get(&unpack_type_id(TypeId::of::<T>())) { match self.map.get(&unpack_type_id(TypeId::of::<T>())) {
None => None, None => None,
Some(h) => { Some(h) => Some(h.values().map(|x| x.as_any().downcast_ref::<T>().unwrap())),
Some(h.values().map(|x| x.as_any().downcast_ref::<T>().unwrap()))
}
} }
} }
@ -425,13 +422,14 @@ macro_rules! create_serde_registry_for_trait {
#[must_use] #[must_use]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[inline] #[inline]
#[allow(clippy::type_complexity)]
pub fn all_by_typeid( pub fn all_by_typeid(
&self, &self,
typeid: &TypeId, typeid: &TypeId,
) -> Option< ) -> Option<
core::iter::Map< core::iter::Map<
Values<'_, u64, Box<dyn $trait_name>>, Values<'_, u64, Box<dyn crate::serdeany::SerdeAny>>,
fn(&Box<dyn $trait_name>) -> &dyn $trait_name, fn(&Box<dyn crate::serdeany::SerdeAny>) -> &dyn crate::serdeany::SerdeAny,
>, >,
> { > {
#[allow(clippy::manual_map)] #[allow(clippy::manual_map)]
@ -444,16 +442,17 @@ macro_rules! create_serde_registry_for_trait {
/// Get all elements contained in this map, as mut. /// Get all elements contained in this map, as mut.
#[inline] #[inline]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[allow(clippy::type_complexity)]
pub fn get_all_mut<T>( pub fn get_all_mut<T>(
&mut self, &mut self,
) -> Option< ) -> Option<
core::iter::Map< core::iter::Map<
ValuesMut<'_, u64, Box<dyn $trait_name>>, ValuesMut<'_, u64, Box<dyn crate::serdeany::SerdeAny>>,
fn(&mut Box<dyn $trait_name>) -> &mut T, fn(&mut Box<dyn crate::serdeany::SerdeAny>) -> &mut T,
>, >,
> >
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
#[allow(clippy::manual_map)] #[allow(clippy::manual_map)]
match self.map.get_mut(&unpack_type_id(TypeId::of::<T>())) { match self.map.get_mut(&unpack_type_id(TypeId::of::<T>())) {
@ -468,13 +467,14 @@ macro_rules! create_serde_registry_for_trait {
/// Get all [`TypeId`]`s` contained in this map, as mut. /// Get all [`TypeId`]`s` contained in this map, as mut.
#[inline] #[inline]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[allow(clippy::type_complexity)]
pub fn all_by_typeid_mut( pub fn all_by_typeid_mut(
&mut self, &mut self,
typeid: &TypeId, typeid: &TypeId,
) -> Option< ) -> Option<
core::iter::Map< core::iter::Map<
ValuesMut<'_, u64, Box<dyn $trait_name>>, ValuesMut<'_, u64, Box<dyn crate::serdeany::SerdeAny>>,
fn(&mut Box<dyn $trait_name>) -> &mut dyn $trait_name, fn(&mut Box<dyn crate::serdeany::SerdeAny>) -> &mut dyn crate::serdeany::SerdeAny,
>, >,
> { > {
#[allow(clippy::manual_map)] #[allow(clippy::manual_map)]
@ -487,10 +487,11 @@ macro_rules! create_serde_registry_for_trait {
/// Get all [`TypeId`]`s` contained in this map. /// Get all [`TypeId`]`s` contained in this map.
#[inline] #[inline]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
#[allow(clippy::type_complexity)]
pub fn all_typeids( pub fn all_typeids(
&self, &self,
) -> core::iter::Map< ) -> core::iter::Map<
Keys<'_, u128, HashMap<u64, Box<dyn $trait_name>>>, Keys<'_, u128, HashMap<u64, Box<dyn crate::serdeany::SerdeAny>>>,
fn(&u128) -> TypeId, fn(&u128) -> TypeId,
> { > {
self.map.keys().map(|x| pack_type_id(*x)) self.map.keys().map(|x| pack_type_id(*x))
@ -499,11 +500,13 @@ macro_rules! create_serde_registry_for_trait {
/// Run `func` for each element in this map. /// Run `func` for each element in this map.
#[inline] #[inline]
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
pub fn for_each<F: FnMut(&TypeId, &Box<dyn $trait_name>) -> Result<(), Error>>( pub fn for_each<
F: FnMut(&TypeId, &Box<dyn crate::serdeany::SerdeAny>) -> Result<(), Error>,
>(
&self, &self,
func: &mut F, func: &mut F,
) -> Result<(), Error> { ) -> Result<(), Error> {
for (id, h) in self.map.iter() { for (id, h) in &self.map {
for x in h.values() { for x in h.values() {
func(&pack_type_id(*id), x)?; func(&pack_type_id(*id), x)?;
} }
@ -514,12 +517,12 @@ macro_rules! create_serde_registry_for_trait {
/// Run `func` for each element in this map, getting a mutable borrow. /// Run `func` for each element in this map, getting a mutable borrow.
#[inline] #[inline]
pub fn for_each_mut< pub fn for_each_mut<
F: FnMut(&TypeId, &mut Box<dyn $trait_name>) -> Result<(), Error>, F: FnMut(&TypeId, &mut Box<dyn crate::serdeany::SerdeAny>) -> Result<(), Error>,
>( >(
&mut self, &mut self,
func: &mut F, func: &mut F,
) -> Result<(), Error> { ) -> Result<(), Error> {
for (id, h) in self.map.iter_mut() { for (id, h) in &mut self.map {
for x in h.values_mut() { for x in h.values_mut() {
func(&pack_type_id(*id), x)?; func(&pack_type_id(*id), x)?;
} }
@ -532,7 +535,7 @@ macro_rules! create_serde_registry_for_trait {
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
pub fn insert<T>(&mut self, val: T, name: &str) pub fn insert<T>(&mut self, val: T, name: &str)
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
let id = unpack_type_id(TypeId::of::<T>()); let id = unpack_type_id(TypeId::of::<T>());
assert!( assert!(
@ -575,7 +578,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn contains_type<T>(&self) -> bool pub fn contains_type<T>(&self) -> bool
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
self.map.contains_key(&unpack_type_id(TypeId::of::<T>())) self.map.contains_key(&unpack_type_id(TypeId::of::<T>()))
} }
@ -585,7 +588,7 @@ macro_rules! create_serde_registry_for_trait {
#[inline] #[inline]
pub fn contains<T>(&self, name: &str) -> bool pub fn contains<T>(&self, name: &str) -> bool
where where
T: $trait_name, T: crate::serdeany::SerdeAny,
{ {
match self.map.get(&unpack_type_id(TypeId::of::<T>())) { match self.map.get(&unpack_type_id(TypeId::of::<T>())) {
None => false, None => false,
@ -610,35 +613,30 @@ macro_rules! create_serde_registry_for_trait {
} }
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
impl Serialize for dyn $trait_name { impl Serialize for dyn crate::serdeany::SerdeAny {
fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, se: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
{ {
use serde::ser::SerializeSeq; use serde::ser::SerializeSeq;
let id = $crate::anymap::unpack_type_id(self.type_id()); let id = crate::anymap::unpack_type_id(self.type_id());
let mut seq = se.serialize_seq(Some(2))?; let mut seq = se.serialize_seq(Some(2))?;
seq.serialize_element(&id)?; seq.serialize_element(&id)?;
seq.serialize_element(&$crate::serdeany::Wrap(self))?; seq.serialize_element(&crate::serdeany::Wrap(self))?;
seq.end() seq.end()
} }
} }
#[allow(unused_qualifications)] #[allow(unused_qualifications)]
impl<'de> Deserialize<'de> for Box<dyn $trait_name> { impl<'de> Deserialize<'de> for Box<dyn crate::serdeany::SerdeAny> {
fn deserialize<D>(deserializer: D) -> Result<Box<dyn $trait_name>, D::Error> fn deserialize<D>(deserializer: D) -> Result<Box<dyn crate::serdeany::SerdeAny>, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
deserializer.deserialize_seq($mod_name::BoxDynVisitor {}) deserializer.deserialize_seq(serdeany_registry::BoxDynVisitor {})
} }
} }
};
}
create_serde_registry_for_trait!(serdeany_registry, crate::serdeany::SerdeAny);
pub use serdeany_registry::*;
/// Register a `SerdeAny` type in the [`RegistryBuilder`] /// Register a `SerdeAny` type in the [`RegistryBuilder`]
/// ///