macros.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #[macro_export]
  2. macro_rules! impl_any_data {
  3. ($target: ident, $field_type:expr) => {
  4. impl_field_type_data_from_field!($target);
  5. impl_field_type_data_from_field_type_option!($target);
  6. impl_type_option_from_field_data!($target, $field_type);
  7. };
  8. }
  9. #[macro_export]
  10. macro_rules! impl_field_type_data_from_field {
  11. ($target: ident) => {
  12. impl std::convert::From<&Field> for $target {
  13. fn from(field: &Field) -> $target {
  14. $target::from(&field.type_options)
  15. }
  16. }
  17. };
  18. }
  19. #[macro_export]
  20. macro_rules! impl_field_type_data_from_field_type_option {
  21. ($target: ident) => {
  22. impl std::convert::From<&AnyData> for $target {
  23. fn from(any_data: &AnyData) -> $target {
  24. match $target::try_from(Bytes::from(any_data.value.clone())) {
  25. Ok(obj) => obj,
  26. Err(err) => {
  27. tracing::error!("{} convert from any data failed, {:?}", stringify!($target), err);
  28. $target::default()
  29. }
  30. }
  31. }
  32. }
  33. };
  34. }
  35. #[macro_export]
  36. macro_rules! impl_type_option_from_field_data {
  37. ($target: ident, $field_type:expr) => {
  38. impl $target {
  39. pub fn field_type() -> FieldType {
  40. $field_type
  41. }
  42. }
  43. impl std::convert::From<$target> for AnyData {
  44. fn from(field_data: $target) -> Self {
  45. match field_data.try_into() {
  46. Ok(bytes) => {
  47. let bytes: Bytes = bytes;
  48. AnyData::from_bytes(&$target::field_type(), bytes)
  49. }
  50. Err(e) => {
  51. tracing::error!("Field type data convert to AnyData fail, error: {:?}", e);
  52. // it's impossible to fail when unwrapping the default field type data
  53. let default_bytes: Bytes = $target::default().try_into().unwrap();
  54. AnyData::from_bytes(&$target::field_type(), default_bytes)
  55. }
  56. }
  57. }
  58. }
  59. };
  60. }