incin_core/shapes/
reshape.rs1use crate::shapes::shape::{ShapeArgs, ShapeSpec};
3use crate::shapes::{DynShape, Shape, ShapeValue};
4use core::ops::Mul;
5use typenum::{Prod, U1, Unsigned};
6
7pub trait ElementCount {
9 type Count: typenum::Unsigned;
11}
12
13impl ElementCount for crate::shapes::Nil {
14 type Count = U1;
15}
16
17impl<H, T> ElementCount for crate::shapes::DimCons<H, T>
20where
21 H: crate::shapes::ConcreteStaticExtent,
22 T: crate::shapes::Shape + ElementCount,
23 H::Nat: Mul<<T as ElementCount>::Count>,
24 Prod<H::Nat, <T as ElementCount>::Count>: Unsigned,
25{
26 type Count = Prod<H::Nat, <T as ElementCount>::Count>;
27}
28
29#[diagnostic::on_unimplemented(
39 message = "Cannot reshape: source has {Self} elements but the target shape has {Rhs} elements",
40 label = "element count changes here",
41 note = "reshape must preserve the total number of elements"
42)]
43pub trait SameCount<Rhs> {}
44impl<N> SameCount<N> for N {}
45
46#[diagnostic::on_unimplemented(
48 message = "Cannot reshape from `{Self}` to `{Target}`",
49 label = "element count mismatch for reshape",
50 note = "reshape requires the total number of elements to remain constant"
51)]
52pub trait ReshapeShape<Target: Shape>: Shape {}
54
55impl<S1, S2> ReshapeShape<S2> for S1
57where
58 S1: Shape + ElementCount,
59 S2: Shape + ElementCount,
60 <S1 as ElementCount>::Count: SameCount<<S2 as ElementCount>::Count>,
61{
62}
63
64pub trait TryReshape<Target: Shape>: Shape {}
66
67impl<S1: DynShape, S2: DynShape> TryReshape<S2> for S1 {}
69
70pub trait ReshapeSpec<Source: Shape>: ShapeSpec {}
76
77impl<Source, Target> ReshapeSpec<Source> for ShapeValue<Target>
78where
79 Source: Shape + ReshapeShape<Target>,
80 Target: Shape + DynShape,
81{
82}
83
84impl<Source, Target> ReshapeSpec<Source> for ShapeArgs<Target>
85where
86 Source: DynShape,
87 Target: Shape + DynShape,
88{
89}
90
91impl<Source, const N: usize> ReshapeSpec<Source> for [usize; N] where Source: DynShape {}
92
93impl<Source> ReshapeSpec<Source> for alloc::vec::Vec<usize> where Source: DynShape {}
94
95impl<Source> ReshapeSpec<Source> for &[usize] where Source: DynShape {}
96
97#[cfg(test)]
98mod tests {
100 use super::*;
101 use typenum::{U2, U4, U8};
102
103 fn assert_reshape_eq<S1, S2: Shape>()
105 where
106 S1: Shape + ReshapeShape<S2>,
107 {
108 }
109
110 #[test]
111 fn reshape_same_rank_same_numel() {
113 type S1 = crate::shapes::DimCons<U2, crate::shapes::DimCons<U8, crate::shapes::Nil>>;
115 type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
117 assert_reshape_eq::<S1, S2>();
118 }
119
120 #[test]
121 fn reshape_different_rank_same_numel() {
123 type S1 = crate::shapes::DimCons<
125 U2,
126 crate::shapes::DimCons<U2, crate::shapes::DimCons<U4, crate::shapes::Nil>>,
127 >;
128 type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
130 assert_reshape_eq::<S1, S2>();
131 }
132}