byte_trait.rs 2.0 KB

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