byte_trait.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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) => Err(InternalError::ProtobufError(format!("{:?}", e)).into()),
  16. }
  17. }
  18. }
  19. #[cfg(feature = "use_serde")]
  20. impl<T> ToBytes for T
  21. where
  22. T: serde::Serialize,
  23. {
  24. fn into_bytes(self) -> Result<Bytes, DispatchError> {
  25. match serde_json::to_string(&self.0) {
  26. Ok(s) => Ok(Bytes::from(s)),
  27. Err(e) => Err(InternalError::SerializeToBytes(format!("{:?}", e)).into()),
  28. }
  29. }
  30. }
  31. // From bytes
  32. pub trait FromBytes: Sized {
  33. fn parse_from_bytes(bytes: Bytes) -> Result<Self, DispatchError>;
  34. }
  35. #[cfg(feature = "use_protobuf")]
  36. impl<T> FromBytes for T
  37. where
  38. // // https://stackoverflow.com/questions/62871045/tryfromu8-trait-bound-in-trait
  39. // T: for<'a> std::convert::TryFrom<&'a Bytes, Error =
  40. // protobuf::ProtobufError>,
  41. T: std::convert::TryFrom<Bytes, Error = protobuf::ProtobufError>,
  42. {
  43. fn parse_from_bytes(bytes: Bytes) -> Result<Self, DispatchError> {
  44. match T::try_from(bytes) {
  45. Ok(data) => Ok(data),
  46. Err(e) => {
  47. tracing::error!(
  48. "Parse payload to {} failed with error: {:?}",
  49. std::any::type_name::<T>(),
  50. e
  51. );
  52. Err(e.into())
  53. }
  54. }
  55. }
  56. }
  57. #[cfg(feature = "use_serde")]
  58. impl<T> FromBytes for T
  59. where
  60. T: serde::de::DeserializeOwned + 'static,
  61. {
  62. fn parse_from_bytes(bytes: Bytes) -> Result<Self, String> {
  63. let s = String::from_utf8_lossy(&bytes);
  64. match serde_json::from_str::<T>(s.as_ref()) {
  65. Ok(data) => Ok(data),
  66. Err(e) => Err(format!("{:?}", e)),
  67. }
  68. }
  69. }