AppFlowy/frontend/rust-lib/flowy-grid/src/macros.rs

83 lines
2.6 KiB
Rust
Raw Normal View History

2022-03-25 12:55:56 +00:00
#[macro_export]
macro_rules! impl_into_box_type_option_builder {
($target: ident) => {
2022-03-26 12:27:32 +00:00
impl std::convert::From<$target> for BoxTypeOptionBuilder {
fn from(target: $target) -> BoxTypeOptionBuilder {
Box::new(target)
2022-03-25 12:55:56 +00:00
}
}
};
}
2022-04-01 08:38:51 +00:00
macro_rules! impl_builder_from_json_str_and_from_bytes {
2022-03-25 12:55:56 +00:00
($target: ident,$type_option: ident) => {
impl $target {
2022-04-01 08:38:51 +00:00
pub fn from_protobuf_bytes(bytes: Bytes) -> $target {
let type_option = $type_option::from_protobuf_bytes(bytes);
$target(type_option)
2022-03-25 12:55:56 +00:00
}
2022-04-01 08:38:51 +00:00
pub fn from_json_str(s: &str) -> $target {
let type_option = $type_option::from_json_str(s);
2022-03-25 12:55:56 +00:00
$target(type_option)
}
}
};
}
2022-03-03 14:17:07 +00:00
#[macro_export]
2022-04-01 08:38:51 +00:00
macro_rules! impl_type_option {
2022-03-03 14:17:07 +00:00
($target: ident, $field_type:expr) => {
2022-03-15 03:07:18 +00:00
impl std::convert::From<&FieldMeta> for $target {
fn from(field_meta: &FieldMeta) -> $target {
2022-04-10 12:21:28 +00:00
match field_meta.get_type_option_entry::<$target>(&$field_type) {
2022-04-01 08:38:51 +00:00
None => $target::default(),
Some(target) => target,
}
2022-03-25 12:55:56 +00:00
}
}
2022-04-01 08:38:51 +00:00
impl std::convert::From<$target> for String {
fn from(type_option: $target) -> String {
type_option.json_str()
2022-03-03 14:17:07 +00:00
}
}
2022-04-01 08:38:51 +00:00
impl TypeOptionDataEntry for $target {
fn field_type(&self) -> FieldType {
2022-03-03 14:17:07 +00:00
$field_type
}
2022-04-01 08:38:51 +00:00
fn json_str(&self) -> String {
match serde_json::to_string(&self) {
2022-03-12 14:52:24 +00:00
Ok(s) => s,
2022-03-03 14:17:07 +00:00
Err(e) => {
2022-04-07 07:34:00 +00:00
tracing::error!("Field type data serialize to json fail, error: {:?}", e);
2022-03-12 14:52:24 +00:00
serde_json::to_string(&$target::default()).unwrap()
2022-03-03 14:17:07 +00:00
}
}
}
2022-04-01 08:38:51 +00:00
fn protobuf_bytes(&self) -> Bytes {
self.clone().try_into().unwrap()
}
}
2022-04-10 12:21:28 +00:00
impl TypeOptionDataDeserializer for $target {
2022-04-01 08:38:51 +00:00
fn from_json_str(s: &str) -> $target {
match serde_json::from_str(s) {
Ok(obj) => obj,
Err(err) => {
tracing::error!("{} convert from any data failed, {:?}", stringify!($target), err);
$target::default()
}
}
}
fn from_protobuf_bytes(bytes: Bytes) -> $target {
$target::try_from(bytes).unwrap_or($target::default())
}
2022-03-03 14:17:07 +00:00
}
};
}