use crate::prelude::vec::Vec;
use crate::{
form::{
Form,
MetaForm,
PortableForm,
},
Field,
IntoPortable,
Registry,
};
use derive_more::From;
use scale::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 = "lowercase"))]
#[cfg_attr(any(feature = "std", feature = "decode"), derive(scale::Decode))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, From, Encode)]
pub struct TypeDefVariant<T: Form = MetaForm> {
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Vec::is_empty", default)
)]
variants: Vec<Variant<T>>,
}
impl IntoPortable for TypeDefVariant {
type Output = TypeDefVariant<PortableForm>;
fn into_portable(self, registry: &mut Registry) -> Self::Output {
TypeDefVariant {
variants: registry.map_into_portable(self.variants),
}
}
}
impl TypeDefVariant {
pub fn new<I>(variants: I) -> Self
where
I: IntoIterator<Item = Variant>,
{
Self {
variants: variants.into_iter().collect(),
}
}
}
impl<T> TypeDefVariant<T>
where
T: Form,
{
pub fn variants(&self) -> &[Variant<T>] {
&self.variants
}
}
#[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(any(feature = "std", feature = "decode"), derive(scale::Decode))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Encode)]
pub struct Variant<T: Form = MetaForm> {
name: T::String,
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Vec::is_empty", default)
)]
fields: Vec<Field<T>>,
index: u8,
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Vec::is_empty", default)
)]
docs: Vec<T::String>,
}
impl IntoPortable for Variant {
type Output = Variant<PortableForm>;
fn into_portable(self, registry: &mut Registry) -> Self::Output {
Variant {
name: self.name.into_portable(registry),
fields: registry.map_into_portable(self.fields),
index: self.index,
docs: registry.map_into_portable(self.docs),
}
}
}
impl Variant {
pub(crate) fn new(
name: &'static str,
fields: Vec<Field<MetaForm>>,
index: u8,
docs: Vec<&'static str>,
) -> Self {
Self {
name,
fields,
index,
docs,
}
}
}
impl<T> Variant<T>
where
T: Form,
{
pub fn name(&self) -> &T::String {
&self.name
}
pub fn fields(&self) -> &[Field<T>] {
&self.fields
}
pub fn index(&self) -> u8 {
self.index
}
pub fn docs(&self) -> &[T::String] {
&self.docs
}
}