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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use core::{
    ops::{Index, IndexMut},
    slice,
};
use num::traits::NumAssign;

/// A column-major numeric matrix.
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(transparent)]
pub struct Matrix<T: Copy + NumAssign, const R: usize, const C: usize>(pub(crate) [[T; R]; C]);

impl<T: Copy + NumAssign, const R: usize, const C: usize> Matrix<T, R, C> {
    /// Creates a matrix from raw 2D array.
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 2, 2>::new([[1., 2.], [3., 4.]]);
    /// assert_eq!(*m.as_ref(), [1., 2., 3., 4.]);
    /// ```
    #[inline]
    pub fn new(data: [[T; R]; C]) -> Self {
        Self(data)
    }

    /// Creates a matrix from slice.
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 2, 2>::from_slice(&[1., 2., 3., 4.]);
    /// assert_eq!(*m.as_ref(), [1., 2., 3., 4.]);
    /// ```
    #[inline]
    pub fn from_slice(data: &[T]) -> Self {
        let mut result = Self::default();
        result.as_mut().clone_from_slice(data);
        result
    }

    /// Returns the number of columns in the matrix.
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 3, 2>::default();
    /// assert_eq!(m.columns(), 2);
    /// ```
    #[inline]
    pub fn columns(&self) -> usize {
        C
    }

    /// Returns the number of rows in the matrix.
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 3, 2>::default();
    /// assert_eq!(m.rows(), 3);
    /// ```
    #[inline]
    pub fn rows(&self) -> usize {
        R
    }
}

impl<T: Copy + NumAssign, const N: usize> Matrix<T, N, N> {
    /// Creates an identity matrix
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 3, 3>::identity();
    /// assert_eq!(*m.as_ref(), [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
    /// ```
    pub fn identity() -> Self {
        let mut m = Self::default();
        for i in 0..N {
            m.0[i][i] = T::one();
        }
        m
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> Default for Matrix<T, R, C> {
    /// Creates a zero matrix.
    ///
    /// # Examples
    /// ```
    /// # use munum::Matrix;
    /// let m = Matrix::<f32, 3, 3>::default();
    /// assert_eq!(*m.as_ref(), [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
    /// ```
    #[inline]
    fn default() -> Self {
        Self([[T::zero(); R]; C])
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> AsRef<[T]> for Matrix<T, R, C> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.0.as_ptr() as *const T, R * C) }
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> AsMut<[T]> for Matrix<T, R, C> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        unsafe { slice::from_raw_parts_mut(self.0.as_mut_ptr() as *mut T, R * C) }
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> Index<usize> for Matrix<T, R, C> {
    type Output = T;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[(index / R)  % C][index % R]
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> IndexMut<usize> for Matrix<T, R, C> {
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[(index / R)  % C][index % R]
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> Index<(usize, usize)>
    for Matrix<T, R, C>
{
    type Output = T;

    /// Indexing into the `Matrix` by (row, column).
    #[inline]
    fn index(&self, (row, col): (usize, usize)) -> &Self::Output {
        &self.0[col % C][row % R]
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> IndexMut<(usize, usize)>
    for Matrix<T, R, C>
{
    /// Mutably indexing into the `Matrix` by (row, column).
    #[inline]
    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut Self::Output {
        &mut self.0[col % C][row % R]
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> From<[[T; R]; C]> for Matrix<T, R, C> {
    #[inline]
    fn from(data: [[T; R]; C]) -> Self {
        Self::new(data)
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> From<&[T]> for Matrix<T, R, C> {
    #[inline]
    fn from(slice: &[T]) -> Self {
        Self::from_slice(slice)
    }
}

impl<T: Copy + NumAssign, const R: usize, const C: usize> From<Matrix<T, R, C>> for [[T; R]; C] {
    #[inline]
    fn from(m: Matrix<T, R, C>) -> Self {
        m.0
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use core::fmt;
    use core::marker::PhantomData;

    use super::Matrix;
    use num::traits::NumAssign;
    use serde::{
        de::{SeqAccess, Visitor},
        ser::SerializeSeq,
        Deserialize, Deserializer, Serialize, Serializer,
    };

    impl<T: Copy + NumAssign, const R: usize, const C: usize> Serialize for Matrix<T, R, C>
    where
        T: Serialize,
    {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut seq = serializer.serialize_seq(Some(R * C))?;
            for c in 0..C {
                for r in 0..R {
                    seq.serialize_element(&self.0[c][r])?;
                }
            }
            seq.end()
        }
    }

    struct MatrixArrayDeserializer<T: Copy + NumAssign, const R: usize, const C: usize>(
        PhantomData<[[T; R]; C]>,
    );

    impl<'de, T, const R: usize, const C: usize> Visitor<'de> for MatrixArrayDeserializer<T, R, C>
    where
        T: Deserialize<'de> + Copy + NumAssign,
    {
        type Value = [[T; R]; C];

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("T sequence.")
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut arr = [[T::zero(); R]; C];
            for c in 0..C {
                for r in 0..R {
                    if let Some(value) = seq.next_element()? {
                        arr[c][r] = value;
                    }
                }
            }
            Ok(arr)
        }
    }

    impl<'de, T: Copy + NumAssign, const R: usize, const C: usize> Deserialize<'de> for Matrix<T, R, C>
    where
        T: Deserialize<'de>,
    {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let arr = deserializer.deserialize_seq(MatrixArrayDeserializer(PhantomData))?;
            Ok(Matrix::new(arr))
        }
    }
}

#[cfg(feature = "serde")]
#[cfg(test)]
mod tests {
    use alloc::vec;
    use serde_json::{json, Value};

    use super::Matrix;

    #[test]
    fn test_serialize() {
        let mat = Matrix::<f32, 3, 3>::new([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]);
        let expected_json: Value = json!([1., 2., 3., 4., 5., 6., 7., 8., 9.]);

        let json: Value = serde_json::to_value(mat).unwrap();
        assert_eq!(json, expected_json);
    }

    #[test]
    fn test_deserialize() {
        let json: Value = json!([1., 2., 3., 4., 5., 6., 7., 8., 9.]);

        let mat: Matrix<f32, 3, 3> = serde_json::from_value(json).unwrap();

        assert_eq!(*mat.as_ref(), [1., 2., 3., 4., 5., 6., 7., 8., 9.]);
    }
}