use crate::tm_std::*;
use crate::{
form::{CompactForm, Form, MetaForm},
IntoCompact, MetaType, Registry, TypeInfo,
};
use scale::{Decode, Encode};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize, Encode, Decode)]
#[serde(bound(
serialize = "T::Type: Serialize, T::String: Serialize",
deserialize = "T::Type: DeserializeOwned, T::String: DeserializeOwned"
))]
pub struct Field<T: Form = MetaForm> {
#[serde(skip_serializing_if = "Option::is_none", default)]
name: Option<T::String>,
#[serde(rename = "type")]
ty: T::Type,
}
impl IntoCompact for Field {
type Output = Field<CompactForm>;
fn into_compact(self, registry: &mut Registry) -> Self::Output {
Field {
name: self.name.map(|name| name.into_compact(registry)),
ty: registry.register_type(&self.ty),
}
}
}
impl Field {
pub fn new(name: Option<&'static str>, ty: MetaType) -> Self {
Self { name, ty }
}
pub fn named(name: &'static str, ty: MetaType) -> Self {
Self::new(Some(name), ty)
}
pub fn named_of<T>(name: &'static str) -> Self
where
T: TypeInfo + ?Sized + 'static,
{
Self::new(Some(name), MetaType::new::<T>())
}
pub fn unnamed(meta_type: MetaType) -> Self {
Self::new(None, meta_type)
}
pub fn unnamed_of<T>() -> Self
where
T: TypeInfo + ?Sized + 'static,
{
Self::new(None, MetaType::new::<T>())
}
}
impl<T> Field<T>
where
T: Form,
{
pub fn name(&self) -> Option<&T::String> {
self.name.as_ref()
}
pub fn ty(&self) -> &T::Type {
&self.ty
}
}