mightrix 0.4.4

A library to treat continous memory as a matrix.
Documentation
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use crate::{
    ColumnPrio, ColumnPrioMatrix, IntermittentSlice, IntermittentSliceMut, IterIntermittentSlices,
    IterMutIntermittentSlices, IterSlices, IterSlicesMut, RowPrio, RowPrioMatrix,
};
use std::{fmt::Debug, marker::PhantomData, mem::MaybeUninit};

/// Stacktrix allows a stack based array to be used as a Matrix.
///
/// A Stacktrix matrix operates on a a stack based array. The number of rows is indicated by R the number
/// of columns by C, S indicates the entire size this is necessary since const expressions are
/// still nightly only. MemoryPriority indicates how the underlying memory is interpreted. (see
/// [`ColumnPrio`], [`RowPrio`])
#[derive(Debug, Clone, Copy)]
pub struct Stacktrix<const S: usize, const R: usize, const C: usize, MemoryPrio, T> {
    inner: [T; S],
    _prio: PhantomData<MemoryPrio>,
}

impl<const S: usize, const R: usize, const C: usize, MemoryPriority, T>
    Stacktrix<S, R, C, MemoryPriority, T>
where
    T: Copy + Sized,
{
    /// Constructs a Stacktrix from an array with memory interpretation given by MemoryPriority.
    ///
    /// # Panics
    ///
    /// The function will panic if the given slice is not equal to the size of the to be created
    /// matrix R * C or if S != R * C.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio };
    /// let reftrix = Stacktrix::<6, 3, 2, ColumnPrio, u8>::with_values([1,2,3,4,5,6]);
    /// ```
    pub const fn with_values(inner_values: [T; S]) -> Self {
        assert!(S == R * C);
        Self {
            inner: inner_values,
            _prio: PhantomData,
        }
    }
    /// Constructs a Stacktrix from a slice with a [`ColumnPrio`] memory interpretation.
    ///
    /// # Panics
    ///
    /// The function will panic if the given slice is not equal to the size of the to be created
    /// matrix R * C or if S != R * C.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let reftrix = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&data[..]);
    /// ```
    pub fn from_values(inner_values: &[T]) -> Self {
        assert!(inner_values.len() == R * C);
        assert!(S == R * C);
        let mut inner: [MaybeUninit<T>; S] = unsafe { [MaybeUninit::uninit().assume_init(); S] };
        // Safety:
        // inner and inner_values are valid pointers and do not overlap.
        unsafe {
            std::ptr::copy_nonoverlapping(inner_values.as_ptr(), inner.as_mut_ptr().cast::<T>(), S)
        };
        // Safety:
        // T and MaybeUninit<T> have the same size.
        // All elements in inner have been initialized.
        Self {
            inner: unsafe { (&inner as *const _ as *const [T; S]).read() },
            _prio: PhantomData,
        }
    }
}

impl<const S: usize, const R: usize, const C: usize, T> ColumnPrioMatrix<T>
    for Stacktrix<S, R, C, ColumnPrio, T>
where
    T: Copy + Default + Debug,
{
    /// Inserts a value at position row, col inside the matrix.
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// m.insert(3, 0, 0);
    /// assert_eq!(m.get(3,0), &0);
    /// ```
    fn insert(&mut self, row: usize, col: usize, value: T) {
        self.get_mut_column(col)[row] = value;
    }
    /// Get a immutable reference to a value in the matrix at location (x, y)
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// assert_eq!(m.get(0, 2), &3);
    /// ```
    fn get(&self, row: usize, col: usize) -> &T {
        &self.get_column(col)[row]
    }

    /// Get a mutable reference to a value in the matrix at location (x, y)
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    fn get_mut(&mut self, row: usize, col: usize) -> &mut T {
        &mut self.get_mut_column(col)[row]
    }

    /// Fills an entire column with the given data.
    ///
    /// # Panics
    ///
    /// If the column is out of bounds.
    ///
    /// If the data is not the size of a column.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// m.fill_col(1, &[7,7,7,7]);
    /// assert_eq!(m.get_column(1), &[7,7,7,7]);
    /// ```
    fn fill_col(&mut self, col: usize, data: &[T]) {
        assert_eq!(data.len(), R);
        let start = col * R;
        self.inner[start..start + R].copy_from_slice(data);
    }

    /// Fills an entire row with the given data.
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    ///
    /// If the data is not the size of a row.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// m.fill_row(1, &[7,7,7,7]);
    /// assert_eq!(m.get(1,0), &7);
    /// assert_eq!(m.get(1,1), &7);
    /// assert_eq!(m.get(1,2), &7);
    /// assert_eq!(m.get(1,3), &7);
    /// ```
    fn fill_row(&mut self, row: usize, data: &[T]) {
        assert_eq!(data.len(), C);
        for (dst, src) in self.get_mut_row(row).into_iter().zip(data.iter()) {
            *dst = *src;
        }
    }

    /// Retrieves a immutable slice that represents the column.
    ///
    /// # Panics
    ///
    /// If the column is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// assert_eq!(m.get_column(0), &[1,1,1,1]);
    /// ```
    fn get_column(&self, col: usize) -> &[T] {
        assert!(
            col < C,
            "Column: {} out of bounds {}, be carefull columns are 0 indexed.",
            col,
            C
        );
        let start = col * R;
        &self.inner[start..start + R]
    }

    /// Retrieves a mutable slice that represents the column.
    ///
    /// # Panics
    ///
    /// If the column is out of bounds.
    fn get_mut_column(&mut self, col: usize) -> &mut [T] {
        assert!(
            col < C,
            "Column: {} out of bounds {}, be carefull columns are 0 indexed.",
            col,
            C
        );
        let start = col * C;
        &mut self.inner[start..start + C]
    }

    /// Retrieves a [`IntermittentSlice`].
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    fn get_row(&self, row: usize) -> IntermittentSlice<'_, T> {
        assert!(
            row < R,
            "Row: {} out of bounds {}, be carefull rows are 0 indexed.",
            row,
            R
        );
        IntermittentSlice {
            start: &self.inner[row],
            slices: R,
            len: C,
        }
    }

    /// Retrieves a [`IntermittentSliceMut`].
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    fn get_mut_row(&mut self, row: usize) -> IntermittentSliceMut<'_, T> {
        assert!(
            row < R,
            "Row: {} out of bounds {}, be carefull rows are 0 indexed.",
            row,
            R
        );
        IntermittentSliceMut {
            start: &mut self.inner[row],
            slices: R,
            len: C,
        }
    }

    fn rows(&self) -> IterIntermittentSlices<'_, T> {
        IterIntermittentSlices {
            slice_index: 0,
            matrix_buffer: &self.inner,
            slices: R,
            len: C,
        }
    }
    fn rows_mut(&mut self) -> IterMutIntermittentSlices<'_, T> {
        IterMutIntermittentSlices {
            slice_index: 0,
            matrix_buffer: &mut self.inner,
            slices: R,
            len: C,
        }
    }
    fn cols(&self) -> IterSlices<'_, T> {
        IterSlices {
            matrix_buffer: &self.inner[..],
            len: R,
        }
    }

    fn cols_mut(&mut self) -> IterSlicesMut<'_, T> {
        IterSlicesMut {
            matrix_buffer: &mut self.inner[..],
            len: R,
        }
    }

    /// Applies a function on all elements of the matrix.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, ColumnPrio, ColumnPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut data[..]);
    /// m.apply_all(|el| *el *= 2);
    /// assert_eq!(m.get_column(0), &[2,2,2,2]);
    /// assert_eq!(m.get_column(1), &[4,4,4,4]);
    /// assert_eq!(m.get_column(2), &[6,6,6,6]);
    /// assert_eq!(m.get_column(3), &[8,8,8,8]);
    /// ```
    fn apply_all(&mut self, f: fn(&mut T)) {
        for el in self.inner.iter_mut() {
            f(el);
        }
    }

    /// Prints out the matrix, this is only usefull for numeric types.
    fn pretty_print(&self) {
        let strings: Vec<Vec<String>> = (0..4)
            .map(|i| {
                self.get_row(i)
                    .into_iter()
                    .map(|el| format!("{:02x?}", el))
                    .collect::<Vec<String>>()
            })
            .collect();
        for v in strings {
            for (i, s) in v.iter().enumerate() {
                print!("{}", s);
                if i != C - 1 {
                    print!("-")
                }
            }
            println!();
        }
    }
}

impl<const S: usize, const R: usize, const C: usize, T> RowPrioMatrix<T>
    for Stacktrix<S, R, C, RowPrio, T>
where
    T: Copy + Default + Debug,
{
    /// Inserts a value at position (x, y) inside the matrix.
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix};
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// m.insert(3, 1, 0);
    /// assert_eq!(m.get(3,1), &0);
    /// ```
    fn insert(&mut self, row: usize, col: usize, value: T) {
        self.get_mut_row(row)[col] = value;
    }

    /// Get a immutable reference to a value in the matrix at location (x, y)
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix};
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// assert_eq!(m.get(0, 2), &1);
    /// ```
    fn get(&self, row: usize, col: usize) -> &T {
        &self.get_row(row)[col]
    }

    /// Get a mutable reference to a value in the matrix at location (x, y)
    ///
    /// # Panics
    ///
    /// If the location given is out of bounds in x or y the function panics.
    fn get_mut(&mut self, row: usize, col: usize) -> &mut T {
        &mut self.get_mut_row(row)[col]
    }

    /// Fills an entire column with the given data.
    ///
    /// # Panics
    ///
    /// If the column is out of bounds.
    ///
    /// If the data is not the size of a column.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix};
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// m.fill_col(1, &[7,7,7,7]);
    /// assert_eq!(m.get(0,1), &7);
    /// assert_eq!(m.get(1,1), &7);
    /// assert_eq!(m.get(2,1), &7);
    /// assert_eq!(m.get(3,1), &7);
    /// ```
    fn fill_col(&mut self, col: usize, data: &[T]) {
        assert_eq!(data.len(), R);
        for (dst, src) in self.get_mut_column(col).into_iter().zip(data.iter()) {
            *dst = *src;
        }
    }

    /// Fills an entire row with the given data.
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    ///
    /// If the data is not the size of a row.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// m.fill_row(1, &[7,7,7,7]);
    /// assert_eq!(m.get_row(1), &[7,7,7,7]);
    /// ```
    fn fill_row(&mut self, row: usize, data: &[T]) {
        assert_eq!(data.len(), C);
        let start = row * C;
        self.inner[start..start + C].copy_from_slice(data);
    }

    /// Retrieves a [`IntermittentSlice`].
    ///
    /// # Panics
    ///
    /// If the col is out of bounds.
    fn get_column(&self, col: usize) -> IntermittentSlice<'_, T> {
        assert!(
            col < C,
            "Column: {} out of bounds {}, be carefull columns are 0 indexed.",
            col,
            C
        );
        IntermittentSlice {
            start: &self.inner[col],
            slices: C,
            len: R,
        }
    }

    /// Retrieves a [`IntermittentSliceMut`].
    ///
    /// # Panics
    ///
    /// If the col is out of bounds.
    fn get_mut_column(&mut self, col: usize) -> IntermittentSliceMut<'_, T> {
        assert!(
            col < C,
            "Column: {} out of bounds {}, be carefull columns are 0 indexed.",
            col,
            C
        );
        IntermittentSliceMut {
            start: &mut self.inner[col],
            slices: C,
            len: R,
        }
    }

    /// Retrieves a immutable slice that represents the row.
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix};
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// assert_eq!(m.get_row(0), &[1,1,1,1]);
    /// ```
    fn get_row(&self, row: usize) -> &[T] {
        assert!(
            row < R,
            "Row: {} out of bounds {}, be carefull rows are 0 indexed.",
            row,
            R
        );
        let start = row * C;
        &self.inner[start..start + C]
    }

    /// Retrieves a mutable slice that represents the row.
    ///
    /// # Panics
    ///
    /// If the row is out of bounds.
    fn get_mut_row(&mut self, row: usize) -> &mut [T] {
        assert!(
            row < R,
            "Row: {} out of bounds {}, be carefull rows are 0 indexed.",
            row,
            R
        );
        let start = row * C;
        &mut self.inner[start..start + C]
    }

    fn rows(&self) -> IterSlices<'_, T> {
        IterSlices {
            matrix_buffer: &self.inner,
            len: C,
        }
    }
    fn rows_mut(&mut self) -> IterSlicesMut<'_, T> {
        IterSlicesMut {
            matrix_buffer: &mut self.inner,
            len: C,
        }
    }
    fn cols(&self) -> IterIntermittentSlices<'_, T> {
        IterIntermittentSlices {
            slice_index: 0,
            matrix_buffer: &self.inner[..],
            slices: C,
            len: R,
        }
    }

    fn cols_mut(&mut self) -> IterMutIntermittentSlices<'_, T> {
        IterMutIntermittentSlices {
            slice_index: 0,
            matrix_buffer: &mut self.inner[..],
            slices: C,
            len: R,
        }
    }

    /// Applies a function on all elements of the matrix.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mightrix::{ Stacktrix, RowPrio, RowPrioMatrix };
    /// let mut data = vec![1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4];
    /// let mut m = Stacktrix::<16, 4, 4, RowPrio, u8>::from_values(&mut data[..]);
    /// m.apply_all(|el| *el *= 2);
    /// assert_eq!(m.get_row(0), &[2,2,2,2]);
    /// assert_eq!(m.get_row(1), &[4,4,4,4]);
    /// assert_eq!(m.get_row(2), &[6,6,6,6]);
    /// assert_eq!(m.get_row(3), &[8,8,8,8]);
    /// ```
    fn apply_all(&mut self, f: fn(&mut T)) {
        for el in self.inner.iter_mut() {
            f(el);
        }
    }

    /// Prints out the matrix, this is only usefull for numeric types.
    fn pretty_print(&self) {
        let strings: Vec<String> = self.inner.iter().map(|el| format!("{:02x?}", el)).collect();
        let _column_width = strings.iter().map(|el| el.len()).max();
        let mut index = 0;
        for _ in 0..R {
            for i in 0..C {
                print!("{}", strings[index]);
                if i != C - 1 {
                    print!("-")
                }
                index += 1;
            }
            println!();
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{ColumnPrio, ColumnPrioMatrix, Stacktrix};
    #[test]
    fn iter_rows_owned() {
        let mut values = vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
        let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut values);
        for row in m.rows_mut() {
            for (i, el) in row.into_iter().enumerate() {
                *el += i as u8;
            }
        }
        assert_eq!(
            &m.inner[..],
            &[1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5, 5, 7, 7, 7, 7]
        );
    }

    #[test]
    fn iter_cols_owned() {
        let mut values = vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
        let mut m = Stacktrix::<16, 4, 4, ColumnPrio, u8>::from_values(&mut values);
        for col in m.cols_mut() {
            for (i, el) in col.into_iter().enumerate() {
                *el += i as u8;
            }
        }
        assert_eq!(
            &m.inner[..],
            &[1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
        );
    }
}