use crate::shapes::shape::{ShapeArgs, ShapeSpec};
use crate::shapes::{DynShape, Shape, ShapeValue};
use core::ops::Mul;
use typenum::{Prod, U1, Unsigned};
pub trait ElementCount {
type Count: typenum::Unsigned;
}
impl ElementCount for crate::shapes::Nil {
type Count = U1;
}
impl<H, T> ElementCount for crate::shapes::DimCons<H, T>
where
H: crate::shapes::ConcreteStaticExtent,
T: crate::shapes::Shape + ElementCount,
H::Nat: Mul<<T as ElementCount>::Count>,
Prod<H::Nat, <T as ElementCount>::Count>: Unsigned,
{
type Count = Prod<H::Nat, <T as ElementCount>::Count>;
}
#[diagnostic::on_unimplemented(
message = "Cannot reshape: source has {Self} elements but the target shape has {Rhs} elements",
label = "element count changes here",
note = "reshape must preserve the total number of elements"
)]
pub trait SameCount<Rhs> {}
impl<N> SameCount<N> for N {}
#[diagnostic::on_unimplemented(
message = "Cannot reshape from `{Self}` to `{Target}`",
label = "element count mismatch for reshape",
note = "reshape requires the total number of elements to remain constant"
)]
pub trait ReshapeShape<Target: Shape>: Shape {}
impl<S1, S2> ReshapeShape<S2> for S1
where
S1: Shape + ElementCount,
S2: Shape + ElementCount,
<S1 as ElementCount>::Count: SameCount<<S2 as ElementCount>::Count>,
{
}
pub trait TryReshape<Target: Shape>: Shape {}
impl<S1: DynShape, S2: DynShape> TryReshape<S2> for S1 {}
pub trait ReshapeSpec<Source: Shape>: ShapeSpec {}
impl<Source, Target> ReshapeSpec<Source> for ShapeValue<Target>
where
Source: Shape + ReshapeShape<Target>,
Target: Shape + DynShape,
{
}
impl<Source, Target> ReshapeSpec<Source> for ShapeArgs<Target>
where
Source: DynShape,
Target: Shape + DynShape,
{
}
impl<Source, const N: usize> ReshapeSpec<Source> for [usize; N] where Source: DynShape {}
impl<Source> ReshapeSpec<Source> for alloc::vec::Vec<usize> where Source: DynShape {}
impl<Source> ReshapeSpec<Source> for &[usize] where Source: DynShape {}
#[cfg(test)]
mod tests {
use super::*;
use typenum::{U2, U4, U8};
fn assert_reshape_eq<S1, S2: Shape>()
where
S1: Shape + ReshapeShape<S2>,
{
}
#[test]
fn reshape_same_rank_same_numel() {
type S1 = crate::shapes::DimCons<U2, crate::shapes::DimCons<U8, crate::shapes::Nil>>;
type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
assert_reshape_eq::<S1, S2>();
}
#[test]
fn reshape_different_rank_same_numel() {
type S1 = crate::shapes::DimCons<
U2,
crate::shapes::DimCons<U2, crate::shapes::DimCons<U4, crate::shapes::Nil>>,
>;
type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
assert_reshape_eq::<S1, S2>();
}
}