pub trait BinarySerializable {
fn serialize<'a>(&'a self) -> &'a [u8];
}
impl BinarySerializable for String {
fn serialize<'a>(&'a self) -> &'a [u8] {
self.as_bytes()
}
}
impl BinarySerializable for &str {
fn serialize<'a>(&'a self) -> &'a [u8] {
self.as_bytes()
}
}
impl BinarySerializable for Vec<u8> {
fn serialize<'a>(&'a self) -> &'a [u8] {
self.as_slice()
}
}
impl BinarySerializable for &[u8] {
fn serialize<'a>(&'a self) -> &'a [u8] {
self
}
}
pub trait BinaryDeserializable
where
Self: Sized,
{
type Error: std::error::Error + Send + Sync + 'static;
fn deserialize(bytes: Vec<u8>) -> Result<Self, Self::Error>;
}
impl BinaryDeserializable for String {
type Error = std::string::FromUtf8Error;
fn deserialize(bytes: Vec<u8>) -> Result<Self, Self::Error> {
Ok(String::from_utf8(bytes)?)
}
}
impl BinaryDeserializable for Vec<u8> {
type Error = std::convert::Infallible;
fn deserialize(bytes: Vec<u8>) -> Result<Self, Self::Error> {
Ok(bytes)
}
}