use serde::*;
#[derive(Clone, Debug, Hash, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
pub struct Field {
pub name: String,
#[serde(skip)]
pub description: String,
pub ty: Type,
}
impl Field {
pub fn new(name: impl Into<String>, ty: Type) -> Self {
Self {
name: name.into(),
description: "".into(),
ty,
}
}
pub fn new_with_description(
name: impl Into<String>,
description: impl Into<String>,
ty: Type,
) -> Self {
Self {
name: name.into(),
description: description.into(),
ty,
}
}
}
#[derive(Clone, Debug, Hash, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
pub struct EnumVariant {
pub name: String,
pub description: String,
pub value: i64,
}
impl EnumVariant {
pub fn new(name: impl Into<String>, value: i64) -> Self {
Self {
name: name.into(),
description: "".into(),
value,
}
}
pub fn new_with_description(
name: impl Into<String>,
description: impl Into<String>,
value: i64,
) -> Self {
Self {
name: name.into(),
description: description.into(),
value,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord)]
pub enum Type {
UInt32,
Int32,
Int64,
Float64,
Boolean,
String,
Bytea,
UUID,
IpAddr,
Struct {
name: String,
fields: Vec<Field>,
},
StructRef(String),
Object,
StructTable {
struct_ref: String,
},
Vec(Box<Type>),
Unit,
Optional(Box<Type>),
Enum {
name: String,
variants: Vec<EnumVariant>,
},
EnumRef {
name: String,
#[serde(default, skip_serializing)]
prefixed_name: bool,
},
TimeStampMs,
BlockchainDecimal,
BlockchainAddress,
BlockchainTransactionHash,
}
impl Type {
pub fn struct_(name: impl Into<String>, fields: Vec<Field>) -> Self {
Self::Struct {
name: name.into(),
fields,
}
}
pub fn struct_ref(name: impl Into<String>) -> Self {
Self::StructRef(name.into())
}
pub fn struct_table(struct_ref: impl Into<String>) -> Self {
Self::StructTable {
struct_ref: struct_ref.into(),
}
}
pub fn vec(ty: Type) -> Self {
Self::Vec(Box::new(ty))
}
pub fn optional(ty: Type) -> Self {
Self::Optional(Box::new(ty))
}
pub fn enum_ref(name: impl Into<String>, prefixed_name: bool) -> Self {
Self::EnumRef {
name: name.into(),
prefixed_name,
}
}
pub fn enum_(name: impl Into<String>, fields: Vec<EnumVariant>) -> Self {
Self::Enum {
name: name.into(),
variants: fields,
}
}
pub fn try_unwrap(self) -> Option<Self> {
match self {
Self::Vec(v) => Some(*v),
Self::StructTable { .. } => None,
_ => Some(self),
}
}
pub fn add_default_enum_derives(input: String) -> String {
format!(
r#"#[derive(Debug, Clone, Copy, Serialize, Deserialize, FromPrimitive, PartialEq, Eq, PartialOrd, Ord, EnumString, Display, Hash)]{input}"#
)
}
pub fn add_default_struct_derives(input: String) -> String {
format!(
r#" #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
{input}
"#
)
}
}