use serde::{de::DeserializeOwned, Serialize};
use serde_derive::{Deserialize as Des, Serialize as Ser};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Ser, Des)]
pub enum Representation {
BinaryStable,
BinaryDynamic,
HumanReadable,
}
pub use Representation::*;
impl Representation {
pub fn serialize<S>(self, data: &S) -> Result<Vec<u8>, String>
where
S: Serialize,
{
use Representation::*;
Ok(match self {
BinaryStable => bincode::serialize(data).map_err(|e| e.to_string())?,
BinaryDynamic => rmp_serde::to_vec(data).map_err(|e| e.to_string())?,
HumanReadable => serde_yaml::to_vec(data).map_err(|e| e.to_string())?,
})
}
pub fn deserialize<B, D>(self, bytes: B) -> Result<D, String>
where
B: AsRef<[u8]>,
D: DeserializeOwned,
{
use Representation::*;
Ok(match self {
BinaryStable => bincode::deserialize(bytes.as_ref()).map_err(|e| e.to_string())?,
BinaryDynamic => rmp_serde::from_slice(bytes.as_ref()).map_err(|e| e.to_string())?,
HumanReadable => serde_yaml::from_slice(bytes.as_ref()).map_err(|e| e.to_string())?,
})
}
}