pub trait Format<T>: Sized {
type Error: std::error::Error + Send + Sync + 'static;
fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error>;
fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error>;
}
#[cfg(feature = "json-format")]
pub use self::json::Json;
#[cfg(feature = "bincode-format")]
pub use self::bincode::Bincode;
#[cfg(feature = "json-format")]
mod json {
use serde::{de::DeserializeOwned, Serialize};
use super::Format;
#[cfg_attr(docsrs, doc(cfg(feature = "json-format")))]
#[derive(Debug, std::default::Default)]
pub struct Json;
impl<T: DeserializeOwned + Serialize> Format<T> for Json {
type Error = serde_json::Error;
fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
Ok(serde_json::to_vec_pretty(value)?)
}
fn from_bytes(data: Vec<u8>) -> Result<T, serde_json::Error> {
Ok(serde_json::from_slice(&data)?)
}
}
}
#[cfg(feature = "bincode-format")]
mod bincode {
use serde::{de::DeserializeOwned, Serialize};
use super::Format;
#[cfg_attr(docsrs, doc(cfg(feature = "bincode-format")))]
#[derive(Debug, std::default::Default)]
pub struct Bincode;
impl<T: Serialize + DeserializeOwned> Format<T> for Bincode {
type Error = bincode::Error;
fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
Ok(bincode::serialize(value)?)
}
fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error> {
Ok(bincode::deserialize(&data)?)
}
}
}