byte_trait.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use crate::errors::{DispatchError, InternalError};
  2. use bytes::Bytes;
  3. use protobuf::ProtobufError;
  4. use std::convert::TryFrom;
  5. // To bytes
  6. pub trait ToBytes {
  7. fn into_bytes(self) -> Result<Bytes, DispatchError>;
  8. }
  9. #[cfg(feature = "use_protobuf")]
  10. impl<T> ToBytes for T
  11. where
  12. T: std::convert::TryInto<Bytes, Error = protobuf::ProtobufError>,
  13. {
  14. fn into_bytes(self) -> Result<Bytes, DispatchError> {
  15. match self.try_into() {
  16. Ok(data) => Ok(data),
  17. Err(e) => {
  18. // let system_err: DispatchError = InternalError::new(format!("{:?}",
  19. // e)).into(); system_err.into()
  20. // Err(format!("{:?}", e))
  21. Err(InternalError::ProtobufError(format!("{:?}", e)).into())
  22. },
  23. }
  24. }
  25. }
  26. #[cfg(feature = "use_serde")]
  27. impl<T> ToBytes for T
  28. where
  29. T: serde::Serialize,
  30. {
  31. fn into_bytes(self) -> Result<Bytes, DispatchError> {
  32. match serde_json::to_string(&self.0) {
  33. Ok(s) => Ok(Bytes::from(s)),
  34. Err(e) => Err(InternalError::SerializeToBytes(format!("{:?}", e)).into()),
  35. }
  36. }
  37. }
  38. // From bytes
  39. pub trait FromBytes: Sized {
  40. fn parse_from_bytes(bytes: Bytes) -> Result<Self, DispatchError>;
  41. }
  42. #[cfg(feature = "use_protobuf")]
  43. impl<T> FromBytes for T
  44. where
  45. // // https://stackoverflow.com/questions/62871045/tryfromu8-trait-bound-in-trait
  46. // T: for<'a> std::convert::TryFrom<&'a Bytes, Error =
  47. // protobuf::ProtobufError>,
  48. T: std::convert::TryFrom<Bytes, Error = protobuf::ProtobufError>,
  49. {
  50. fn parse_from_bytes(bytes: Bytes) -> Result<Self, DispatchError> {
  51. let data = T::try_from(bytes.clone())?;
  52. Ok(data)
  53. }
  54. }
  55. #[cfg(feature = "use_serde")]
  56. impl<T> FromBytes for T
  57. where
  58. T: serde::de::DeserializeOwned + 'static,
  59. {
  60. fn parse_from_bytes(bytes: Bytes) -> Result<Self, String> {
  61. let s = String::from_utf8_lossy(&bytes);
  62. match serde_json::from_str::<T>(s.as_ref()) {
  63. Ok(data) => Ok(data),
  64. Err(e) => Err(format!("{:?}", e)),
  65. }
  66. }
  67. }