diff --git a/src/lib.rs b/src/lib.rs index aefb46c..af8d2f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -482,24 +482,24 @@ impl Sub for Matrix { /// of specialization system is implemented. /// You can track this issue [here](https://github.com/rust-lang/rust/issues/42721). pub trait MatrixInto { - /// Method for converting a matrix into a matrix of type [`Matrix`] + /// Method for converting a matrix into a matrix of type [`Matrix`]. + /// # Example + /// ``` + /// use matrix_basic::Matrix; + /// use matrix_basic::MatrixInto; + /// + /// let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap(); + /// let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); + /// let c: Matrix = a.matrix_into(); // Type annotation is needed here + /// + /// assert_eq!(c, b); + /// ``` fn matrix_into(self) -> Matrix; } /// Blanket implementation of [`MatrixInto`] for converting [`Matrix`] to [`Matrix`] whenever -/// `T` implements [`From(S)`]. -/// # Example -/// ``` -/// use matrix_basic::Matrix; -/// use matrix_basic::MatrixInto; -/// -/// let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap(); -/// let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); -/// let c: Matrix = a.matrix_into(); -/// -/// assert_eq!(c, b); -/// ``` -impl, S: ToMatrix> MatrixInto for Matrix { +/// `S` implements [`Into(T)`]. Look at [`matrix_into`](Self::matrix_into()). +impl> MatrixInto for Matrix { fn matrix_into(self) -> Matrix { let mut out = Vec::new(); for row in self.entries { @@ -512,3 +512,30 @@ impl, S: ToMatrix> MatrixInto for Matrix { Matrix { entries: out } } } + +/// Sister trait of [`MatrixInto`]. Basically does the same thing, just with a +/// different syntax. +pub trait MatrixFrom { + /// Method for getting a matrix from another matrix of type [`Matrix`]. + /// # Example + /// ``` + /// use matrix_basic::Matrix; + /// use matrix_basic::MatrixFrom; + /// + /// let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap(); + /// let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); + /// let c = Matrix::::matrix_from(a); // Type annotation is needed here + /// + /// assert_eq!(c, b); + /// ``` + fn matrix_from(input: T) -> Self; +} + +/// Blanket implementation of [`MatrixFrom`] for [`Matrix`] whenever `T` (which is actually some)[`Matrix`] implements +/// [`MatrixInto`]. +impl, S: ToMatrix> MatrixFrom for Matrix { + fn matrix_from(input: T) -> Self { + let out: Matrix = input.matrix_into(); + out + } +} diff --git a/src/tests.rs b/src/tests.rs index c609c4c..4163282 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -72,5 +72,9 @@ fn conversion_test() { let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); use crate::MatrixInto; - assert_eq!(a.matrix_into(), b); + assert_eq!(a.clone().matrix_into(), b); + + use crate::MatrixFrom; + let c = Matrix::::matrix_from(a); + assert_eq!(c, b); }