1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#[macro_export]
macro_rules! matrix {
    ($($($e:expr),*);* $(;)?) => {{
        use $crate::math::matrix::Matrix;
        use $crate::math::vector::Vector;
        Matrix::from(Vector::from([
            $(
                Vector::from([$($e),*])
            ),*
        ]))
    }};
}

pub mod defined;
use super::vector::*;
pub use defined::*;
use derive_more::*;

#[derive(Debug, Clone, Eq, PartialEq, From)]
pub struct Matrix<T, const ROWS: usize, const COLUMNS: usize>(<Self as Deref>::Target);

use std::mem::{swap, MaybeUninit};
impl<T, const ROWS: usize, const COLUMNS: usize> Matrix<T, ROWS, COLUMNS> {
    ///Transpose the matrix.
    pub fn transpose(mut self) -> Matrix<T, COLUMNS, ROWS> {
        //Since Matrix is a 2d array, it has no meta data and is completely safe to allocate uninitilized.
        let mut output: Matrix<T, COLUMNS, ROWS> = unsafe { MaybeUninit::uninit().assume_init() };
        for row in 0..ROWS {
            unsafe {
                //Since row will never exceed the bounds of self, self should not check if row is within its bounds.
                let c = self.get_unchecked_mut(row);
                for column in 0..COLUMNS {
                    swap(
                        c.get_unchecked_mut(column),
                        output.get_unchecked_mut(column).get_unchecked_mut(row),
                    );
                }
            }
        }
        output
    }
    ///Return a slice containing the data of the matrix.
    pub fn as_slice(&self) -> &[f32] {
        unsafe { self.0.as_slice().align_to().1 }
    }
    ///Map every element in the matrix individually.
    pub fn map<F, R>(mut self, func: F) -> Matrix<R, ROWS, COLUMNS>
    where
        F: Fn(T) -> R,
    {
        //Since Matrix is a 2d array, it has no meta data and is completely safe to allocate uninitilized.
        let mut output: Matrix<R, ROWS, COLUMNS> = unsafe { MaybeUninit::uninit().assume_init() };
        for row in 0..ROWS {
            unsafe {
                //Since row will never exceed the bounds of self, self should not check if row is within its bounds.
                for column in 0..COLUMNS {
                    let mut old = MaybeUninit::uninit().assume_init();
                    //Swap the value in the matrix with and uninitialized value, such that the variable old now has the value from the matrix.
                    swap(
                        &mut old,
                        self.get_unchecked_mut(row).get_unchecked_mut(column),
                    );

                    //Run the function on the old value and put it into the matrix.
                    *output.get_unchecked_mut(row).get_unchecked_mut(column) = func(old);
                }
            }
        }
        output
    }
}

impl<T, const N: usize> Matrix<T, N, N> {
    ///Create an identity matrix.
    pub fn identity() -> Self
    where
        T: From<u8>,
    {
        let mut output: Self = unsafe { MaybeUninit::zeroed().assume_init() };
        for n in 0..N {
            unsafe { *output.get_unchecked_mut(n).get_unchecked_mut(n) = 1.into() };
        }
        output
    }
}

impl<T, const COLUMNS: usize> Matrix<T, 1, COLUMNS> {
    ///Cast the matrix to a vector.
    pub fn to_vec(self) -> Vector<T, COLUMNS> {
        self.into_iter().next().unwrap()
    }
}

impl<T> Matrix<T, 1, 1> {
    ///Cast the matrix to a scalar.
    pub fn to_single(self) -> T {
        self.into_iter().next().unwrap().to_single()
    }
}

impl<T, const ROWS: usize, const COLUMNS: usize> IntoIterator for Matrix<T, ROWS, COLUMNS> {
    type Item = <<Self as Deref>::Target as IntoIterator>::Item;
    type IntoIter = <<Self as Deref>::Target as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

use ::core::ops::*;

impl<T, const ROWS: usize, const COLUMNS: usize> Deref for Matrix<T, ROWS, COLUMNS> {
    type Target = Vector<Vector<T, COLUMNS>, ROWS>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T, const ROWS: usize, const COLUMNS: usize> DerefMut for Matrix<T, ROWS, COLUMNS> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, R, const ROWS: usize, const COMMON: usize, const COLUMNS: usize>
    Mul<Matrix<T, COMMON, COLUMNS>> for Matrix<T, ROWS, COMMON>
where
    T: Clone,
    Vector<T, COMMON>: Mul<Output = Option<R>>,
{
    type Output = Matrix<R, ROWS, COLUMNS>;

    fn mul(self, rhs: Matrix<T, COMMON, COLUMNS>) -> Self::Output {
        use core::iter::repeat;
        let rhs = rhs
            .transpose()
            .into_iter()
            .flat_map(|x| repeat(x).take(COMMON));
        let lhs = self.into_iter().cycle();
        let product = lhs.zip(rhs).map(|(x, y)| x * y).enumerate();

        unsafe {
            let mut output: Matrix<R, COLUMNS, ROWS> = MaybeUninit::uninit().assume_init();
            let data = output.align_to_mut::<R>().1;
            for (i, v) in product {
                data[i] = v.unwrap();
            }
            output.transpose()
        }
    }
}

impl<T, R, const ROWS: usize, const COLUMNS: usize> Mul<Matrix<T, ROWS, COLUMNS>>
    for Vector<T, ROWS>
where
    T: Clone,
    Vector<T, ROWS>: Mul<Output = Option<R>>,
{
    type Output = Vector<R, COLUMNS>;

    fn mul(self, rhs: Matrix<T, ROWS, COLUMNS>) -> Self::Output {
        use core::iter::repeat;
        let rhs = rhs.transpose().into_iter();
        let lhs = repeat(self);
        let product = lhs.zip(rhs).map(|(x, y)| x * y).enumerate();

        unsafe {
            let mut output: Self::Output = MaybeUninit::uninit().assume_init();
            let data = output.align_to_mut::<R>().1;
            for (i, v) in product {
                data[i] = v.unwrap();
            }
            output
        }
    }
}

impl<T, R, const ROWS: usize, const COLUMNS: usize> Mul<Vector<T, COLUMNS>>
    for Matrix<T, ROWS, COLUMNS>
where
    T: Clone,
    Vector<T, COLUMNS>: Mul<Output = Option<R>>,
{
    type Output = Vector<R, ROWS>;

    fn mul(self, rhs: Vector<T, COLUMNS>) -> Self::Output {
        use core::iter::repeat;
        let rhs = repeat(rhs);
        let lhs = self.into_iter();
        let product = lhs.zip(rhs).map(|(x, y)| x * y).enumerate();

        unsafe {
            let mut output: Self::Output = MaybeUninit::uninit().assume_init();
            let data = output.align_to_mut::<R>().1;
            for (i, v) in product {
                data[i] = v.unwrap();
            }
            output
        }
    }
}