macros.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #[macro_export]
  2. macro_rules! impl_into_box_type_option_builder {
  3. ($target: ident) => {
  4. impl std::convert::From<$target> for BoxTypeOptionBuilder {
  5. fn from(target: $target) -> BoxTypeOptionBuilder {
  6. Box::new(target)
  7. }
  8. }
  9. };
  10. }
  11. macro_rules! impl_builder_from_json_str_and_from_bytes {
  12. ($target: ident,$type_option: ident) => {
  13. impl $target {
  14. pub fn from_protobuf_bytes(bytes: Bytes) -> $target {
  15. let type_option = $type_option::from_protobuf_bytes(bytes);
  16. $target(type_option)
  17. }
  18. pub fn from_json_str(s: &str) -> $target {
  19. let type_option = $type_option::from_json_str(s);
  20. $target(type_option)
  21. }
  22. }
  23. };
  24. }
  25. #[macro_export]
  26. macro_rules! impl_type_option {
  27. ($target: ident, $field_type:expr) => {
  28. impl std::convert::From<&FieldMeta> for $target {
  29. fn from(field_meta: &FieldMeta) -> $target {
  30. match field_meta.get_type_option_entry::<$target>(&$field_type) {
  31. None => $target::default(),
  32. Some(target) => target,
  33. }
  34. }
  35. }
  36. impl std::convert::From<$target> for String {
  37. fn from(type_option: $target) -> String {
  38. type_option.json_str()
  39. }
  40. }
  41. impl TypeOptionDataEntry for $target {
  42. fn field_type(&self) -> FieldType {
  43. $field_type
  44. }
  45. fn json_str(&self) -> String {
  46. match serde_json::to_string(&self) {
  47. Ok(s) => s,
  48. Err(e) => {
  49. tracing::error!("Field type data serialize to json fail, error: {:?}", e);
  50. serde_json::to_string(&$target::default()).unwrap()
  51. }
  52. }
  53. }
  54. fn protobuf_bytes(&self) -> Bytes {
  55. self.clone().try_into().unwrap()
  56. }
  57. }
  58. impl TypeOptionDataDeserializer for $target {
  59. fn from_json_str(s: &str) -> $target {
  60. match serde_json::from_str(s) {
  61. Ok(obj) => obj,
  62. Err(err) => {
  63. tracing::error!("{} convert from any data failed, {:?}", stringify!($target), err);
  64. $target::default()
  65. }
  66. }
  67. }
  68. fn from_protobuf_bytes(bytes: Bytes) -> $target {
  69. $target::try_from(bytes).unwrap_or($target::default())
  70. }
  71. }
  72. };
  73. }