use crate::{
form::{
Form,
MetaForm,
PortableForm,
},
IntoPortable,
MetaType,
Registry,
TypeInfo,
};
use scale::{
Decode,
Encode,
};
#[cfg(feature = "serde")]
use serde::{
de::DeserializeOwned,
Deserialize,
Serialize,
};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde",
serde(bound(
serialize = "T::Type: Serialize, T::String: Serialize",
deserialize = "T::Type: DeserializeOwned, T::String: DeserializeOwned",
))
)]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Encode, Decode)]
pub struct Field<T: Form = MetaForm> {
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", default)
)]
name: Option<T::String>,
#[cfg_attr(feature = "serde", serde(rename = "type"))]
ty: T::Type,
type_name: T::String,
}
impl IntoPortable for Field {
type Output = Field<PortableForm>;
fn into_portable(self, registry: &mut Registry) -> Self::Output {
Field {
name: self.name.map(|name| name.into_portable(registry)),
ty: registry.register_type(&self.ty),
type_name: self.type_name.into_portable(registry),
}
}
}
impl Field {
pub fn new(
name: Option<&'static str>,
ty: MetaType,
type_name: &'static str,
) -> Self {
Self {
name,
ty,
type_name,
}
}
pub fn named_of<T>(name: &'static str, type_name: &'static str) -> Field
where
T: TypeInfo + ?Sized + 'static,
{
Self::new(Some(name), MetaType::new::<T>(), type_name)
}
pub fn unnamed_of<T>(type_name: &'static str) -> Field
where
T: TypeInfo + ?Sized + 'static,
{
Self::new(None, MetaType::new::<T>(), type_name)
}
}
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
}
pub fn type_name(&self) -> &T::String {
&self.type_name
}
}