byte_trait.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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!(
  16. "Serial {:?} to bytes failed:{:?}",
  17. std::any::type_name::<T>(),
  18. e
  19. ))
  20. .into()),
  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. match T::try_from(bytes) {
  50. Ok(data) => Ok(data),
  51. Err(e) => {
  52. tracing::error!(
  53. "Parse payload to {} failed with error: {:?}",
  54. std::any::type_name::<T>(),
  55. e
  56. );
  57. Err(e.into())
  58. }
  59. }
  60. }
  61. }
  62. #[cfg(feature = "use_serde")]
  63. impl<T> FromBytes for T
  64. where
  65. T: serde::de::DeserializeOwned + 'static,
  66. {
  67. fn parse_from_bytes(bytes: Bytes) -> Result<Self, String> {
  68. let s = String::from_utf8_lossy(&bytes);
  69. match serde_json::from_str::<T>(s.as_ref()) {
  70. Ok(data) => Ok(data),
  71. Err(e) => Err(format!("{:?}", e)),
  72. }
  73. }
  74. }