use crate::prelude::vec::Vec;
use crate::{
build::FieldsBuilder,
form::{
Form,
MetaForm,
PortableForm,
},
Field,
IntoPortable,
Registry,
};
use derive_more::From;
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 = "lowercase"))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, From, Encode, Decode)]
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",
))
)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Encode, Decode)]
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>>,
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", default)
)]
discriminant: Option<u64>,
}
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),
discriminant: self.discriminant,
}
}
}
impl Variant {
pub fn with_fields<F>(name: &'static str, fields: FieldsBuilder<F>) -> Self {
Self {
name,
fields: fields.finalize(),
discriminant: None,
}
}
pub fn with_discriminant(name: &'static str, discriminant: u64) -> Self {
Self {
name,
fields: Vec::new(),
discriminant: Some(discriminant),
}
}
}
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 discriminant(&self) -> Option<u64> {
self.discriminant
}
}