1use tenferro_tensor::{Rank, TensorScalar, TypedTensor};
14
15pub use sparse_ir_sve::matrix::{Mat, Mat3, mat};
16
17pub trait MatTyped<T: TensorScalar>: Sized {
19 fn into_typed(self) -> TypedTensor<T, Rank<2>>;
21
22 fn from_typed(t: &TypedTensor<T, Rank<2>>) -> Result<Self, tenferro_tensor::Error>;
28}
29
30impl<T: TensorScalar> MatTyped<T> for Mat<T> {
31 fn into_typed(self) -> TypedTensor<T, Rank<2>> {
32 let dims = self.dims();
33 TypedTensor::from_vec_col_major(dims, self.into_vec())
34 .expect("Mat invariant: buffer length equals nrows * ncols")
35 }
36
37 fn from_typed(t: &TypedTensor<T, Rank<2>>) -> Result<Self, tenferro_tensor::Error> {
38 let view = t.host_col_major_view()?;
39 Ok(Mat::from_vec_col_major(
40 *view.shape(),
41 view.as_slice().to_vec(),
42 ))
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn typed_roundtrip_is_zero_copy_layout() {
52 let a = Mat::from_fn([2, 2], |idx| (idx[0] + 2 * idx[1]) as f64);
53 let t = a.clone().into_typed();
54 assert_eq!(t.shape(), &[2, 2]);
55 assert_eq!(*t.get2(1, 0).unwrap(), 1.0);
56 assert_eq!(Mat::from_typed(&t).unwrap(), a);
57 }
58}