byte_trait.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // To bytes
  2. pub trait ToBytes {
  3. fn into_bytes(self) -> Result<Vec<u8>, String>;
  4. }
  5. #[cfg(feature = "use_protobuf")]
  6. impl<T> ToBytes for T
  7. where
  8. T: std::convert::TryInto<Vec<u8>, Error = String>,
  9. {
  10. fn into_bytes(self) -> Result<Vec<u8>, String> { self.try_into() }
  11. }
  12. #[cfg(feature = "use_serde")]
  13. impl<T> ToBytes for T
  14. where
  15. T: serde::Serialize,
  16. {
  17. fn into_bytes(self) -> Result<Vec<u8>, String> {
  18. match serde_json::to_string(&self.0) {
  19. Ok(s) => Ok(s.into_bytes()),
  20. Err(e) => Err(format!("{:?}", e)),
  21. }
  22. }
  23. }
  24. // From bytes
  25. pub trait FromBytes: Sized {
  26. fn parse_from_bytes(bytes: &Vec<u8>) -> Result<Self, String>;
  27. }
  28. #[cfg(feature = "use_protobuf")]
  29. impl<T> FromBytes for T
  30. where
  31. // https://stackoverflow.com/questions/62871045/tryfromu8-trait-bound-in-trait
  32. T: for<'a> std::convert::TryFrom<&'a Vec<u8>, Error = String>,
  33. {
  34. fn parse_from_bytes(bytes: &Vec<u8>) -> Result<Self, String> { T::try_from(bytes) }
  35. }
  36. #[cfg(feature = "use_serde")]
  37. impl<T> FromBytes for T
  38. where
  39. T: serde::de::DeserializeOwned + 'static,
  40. {
  41. fn parse_from_bytes(bytes: &Vec<u8>) -> Result<Self, String> {
  42. let s = String::from_utf8_lossy(bytes);
  43. match serde_json::from_str::<T>(s.as_ref()) {
  44. Ok(data) => Ok(data),
  45. Err(e) => Err(format!("{:?}", e)),
  46. }
  47. }
  48. }