2021-08-20 14:00:03 +00:00
|
|
|
use bytes::Bytes;
|
|
|
|
|
2021-07-11 09:38:03 +00:00
|
|
|
// To bytes
|
|
|
|
pub trait ToBytes {
|
2021-08-20 14:00:03 +00:00
|
|
|
fn into_bytes(self) -> Result<Bytes, String>;
|
2021-07-11 09:38:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "use_protobuf")]
|
|
|
|
impl<T> ToBytes for T
|
|
|
|
where
|
2021-08-20 14:00:03 +00:00
|
|
|
T: std::convert::TryInto<Bytes, Error = String>,
|
2021-07-11 09:38:03 +00:00
|
|
|
{
|
2021-08-20 14:00:03 +00:00
|
|
|
fn into_bytes(self) -> Result<Bytes, String> { self.try_into() }
|
2021-07-11 09:38:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "use_serde")]
|
|
|
|
impl<T> ToBytes for T
|
|
|
|
where
|
|
|
|
T: serde::Serialize,
|
|
|
|
{
|
2021-08-20 14:00:03 +00:00
|
|
|
fn into_bytes(self) -> Result<Bytes, String> {
|
2021-07-11 09:38:03 +00:00
|
|
|
match serde_json::to_string(&self.0) {
|
2021-08-20 14:00:03 +00:00
|
|
|
Ok(s) => Ok(Bytes::from(s)),
|
2021-07-11 09:38:03 +00:00
|
|
|
Err(e) => Err(format!("{:?}", e)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// From bytes
|
|
|
|
|
|
|
|
pub trait FromBytes: Sized {
|
2021-08-20 14:00:03 +00:00
|
|
|
fn parse_from_bytes(bytes: Bytes) -> Result<Self, String>;
|
2021-07-11 09:38:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "use_protobuf")]
|
|
|
|
impl<T> FromBytes for T
|
|
|
|
where
|
|
|
|
// https://stackoverflow.com/questions/62871045/tryfromu8-trait-bound-in-trait
|
2021-08-20 14:00:03 +00:00
|
|
|
T: for<'a> std::convert::TryFrom<&'a Bytes, Error = String>,
|
2021-07-11 09:38:03 +00:00
|
|
|
{
|
2021-08-20 14:00:03 +00:00
|
|
|
fn parse_from_bytes(bytes: Bytes) -> Result<Self, String> { T::try_from(&bytes) }
|
2021-07-11 09:38:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "use_serde")]
|
|
|
|
impl<T> FromBytes for T
|
|
|
|
where
|
|
|
|
T: serde::de::DeserializeOwned + 'static,
|
|
|
|
{
|
2021-08-20 14:00:03 +00:00
|
|
|
fn parse_from_bytes(bytes: Bytes) -> Result<Self, String> {
|
|
|
|
let s = String::from_utf8_lossy(&bytes);
|
|
|
|
|
2021-07-11 09:38:03 +00:00
|
|
|
match serde_json::from_str::<T>(s.as_ref()) {
|
|
|
|
Ok(data) => Ok(data),
|
|
|
|
Err(e) => Err(format!("{:?}", e)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|