use alux_ext::{ext, for_tuples};
#[diagnostic::on_unimplemented(
message = "`{Self}` is not stated as a product of its fields",
note = "`#[derive(Shape)]` states `Product` for a struct with named members; a skipped member is made with `Default`, and a flattened one is one field"
)]
pub trait Product: Sized {
type Fields;
const FIELDS: &'static [&'static str];
fn from_fields(fields: Self::Fields) -> Self;
fn into_fields(self) -> Self::Fields;
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not stated as a sum of its alternatives",
note = "`#[derive(Shape)]` states `Sum` for an enum of two to sixteen alternatives, each carrying one value or none"
)]
pub trait Sum: Sized {
type Alternatives;
const ALTERNATIVES: &'static [&'static str];
fn from_alternative(alternative: Self::Alternatives) -> Self;
fn into_alternative(self) -> Self::Alternatives;
}
macro_rules! sums {
($sum:ident, $width:tt; $(($variant:ident, $index:tt)),+) => {
#[doc = concat!("Holds the one alternative of ", stringify!($width), " a value carries.")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum $sum<$($variant),+> {
$(
#[doc = concat!("The alternative at index ", stringify!($index), ".")]
$variant($variant),
)+
}
};
}
for_tuples!(sums, 2..=16, named = Sum, each = []);
#[ext(name = ProductLawsExt)]
pub impl<This, Fields> This
where
This: Product<Fields = Fields> + Clone,
Fields: Clone + PartialEq,
{
fn law_product_round_trip(&self) -> bool {
let fields = self.clone().into_fields();
This::from_fields(fields.clone()).into_fields() == fields
}
}
#[ext(name = SumLawsExt)]
pub impl<This> This
where
This: Sum + Clone + PartialEq,
{
fn law_sum_round_trip(&self) -> bool {
This::from_alternative(self.clone().into_alternative()) == *self
}
}