byte_trait.rs 2.1 KB

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