use std::error::Error;
#[cfg(feature = "serializer-serde")]
use bincode::config;
#[cfg(feature = "serializer-serde")]
use bincode::serde::{decode_from_slice, encode_to_vec};
use crate::{
frame::FrameMetadata,
message::{DecodeWith, DeserializeContext, EncodeWith, Message},
};
pub trait MessageCompatibilitySerializer {}
#[cfg(feature = "serializer-serde")]
pub trait SerdeSerializerBridge {
fn serialize_serde<T: serde::Serialize>(
&self,
value: &T,
) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>>;
fn deserialize_serde<T: serde::de::DeserializeOwned>(
&self,
bytes: &[u8],
context: &DeserializeContext<'_>,
) -> Result<(T, usize), Box<dyn Error + Send + Sync>>;
}
pub trait Serializer {
fn serialize<M>(&self, value: &M) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>>
where
M: EncodeWith<Self>,
Self: Sized;
fn deserialize<M>(&self, bytes: &[u8]) -> Result<(M, usize), Box<dyn Error + Send + Sync>>
where
M: DecodeWith<Self>,
Self: Sized;
fn deserialize_with_context<M>(
&self,
bytes: &[u8],
_context: &DeserializeContext<'_>,
) -> Result<(M, usize), Box<dyn Error + Send + Sync>>
where
M: DecodeWith<Self>,
Self: Sized,
{
self.deserialize(bytes)
}
#[must_use]
fn should_deserialize_after_parse(&self) -> bool { true }
}
#[derive(Clone, Copy, Debug, Default)]
pub struct BincodeSerializer;
impl MessageCompatibilitySerializer for BincodeSerializer {}
impl Serializer for BincodeSerializer {
fn serialize<M>(&self, value: &M) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>>
where
M: EncodeWith<Self>,
{
value.encode_with(self)
}
fn deserialize<M>(&self, bytes: &[u8]) -> Result<(M, usize), Box<dyn Error + Send + Sync>>
where
M: DecodeWith<Self>,
{
M::decode_with(self, bytes, &DeserializeContext::empty())
}
fn deserialize_with_context<M>(
&self,
bytes: &[u8],
context: &DeserializeContext<'_>,
) -> Result<(M, usize), Box<dyn Error + Send + Sync>>
where
M: DecodeWith<Self>,
{
M::decode_with(self, bytes, context)
}
fn should_deserialize_after_parse(&self) -> bool { false }
}
impl FrameMetadata for BincodeSerializer {
type Frame = crate::app::Envelope;
type Error = bincode::error::DecodeError;
fn parse(&self, src: &[u8]) -> Result<(Self::Frame, usize), Self::Error> {
crate::app::Envelope::from_bytes(src)
}
}
#[cfg(feature = "serializer-serde")]
impl SerdeSerializerBridge for BincodeSerializer {
fn serialize_serde<T: serde::Serialize>(
&self,
value: &T,
) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> {
encode_to_vec(value, config::standard())
.map_err(|error| Box::new(error) as Box<dyn Error + Send + Sync>)
}
fn deserialize_serde<T: serde::de::DeserializeOwned>(
&self,
bytes: &[u8],
_context: &DeserializeContext<'_>,
) -> Result<(T, usize), Box<dyn Error + Send + Sync>> {
decode_from_slice(bytes, config::standard())
.map_err(|error| Box::new(error) as Box<dyn Error + Send + Sync>)
}
}