macros.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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<&FieldRevision> for $target {
  29. fn from(field_rev: &FieldRevision) -> $target {
  30. match field_rev.get_type_option_entry::<$target>($field_type.into()) {
  31. None => $target::default(),
  32. Some(target) => target,
  33. }
  34. }
  35. }
  36. impl std::convert::From<&std::sync::Arc<FieldRevision>> for $target {
  37. fn from(field_rev: &std::sync::Arc<FieldRevision>) -> $target {
  38. match field_rev.get_type_option_entry::<$target>($field_type.into()) {
  39. None => $target::default(),
  40. Some(target) => target,
  41. }
  42. }
  43. }
  44. impl std::convert::From<$target> for String {
  45. fn from(type_option: $target) -> String {
  46. type_option.json_str()
  47. }
  48. }
  49. impl TypeOptionDataEntry for $target {
  50. fn json_str(&self) -> String {
  51. match serde_json::to_string(&self) {
  52. Ok(s) => s,
  53. Err(e) => {
  54. tracing::error!("Field type data serialize to json fail, error: {:?}", e);
  55. serde_json::to_string(&$target::default()).unwrap()
  56. }
  57. }
  58. }
  59. fn protobuf_bytes(&self) -> Bytes {
  60. self.clone().try_into().unwrap()
  61. }
  62. }
  63. impl TypeOptionDataDeserializer for $target {
  64. fn from_json_str(s: &str) -> $target {
  65. match serde_json::from_str(s) {
  66. Ok(obj) => obj,
  67. Err(err) => {
  68. tracing::error!("{} convert from any data failed, {:?}", stringify!($target), err);
  69. $target::default()
  70. }
  71. }
  72. }
  73. fn from_protobuf_bytes(bytes: Bytes) -> $target {
  74. $target::try_from(bytes).unwrap_or($target::default())
  75. }
  76. }
  77. };
  78. }