oxiblas-matrix 0.2.2

Matrix types and views for OxiBLAS
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Copy-on-Write matrix type.
//!
//! `CowMat<T>` provides efficient matrix sharing with copy-on-write semantics.
//! Multiple matrices can share the same underlying data until a mutation is needed,
//! at which point the data is cloned.
//!
//! # Use Cases
//!
//! - Passing matrices through multiple computation stages where most don't mutate
//! - Caching intermediate results that may or may not be modified
//! - Reducing memory allocations in algorithms that conditionally modify matrices
//!
//! # Example
//!
//! ```
//! use oxiblas_matrix::CowMat;
//!
//! // Create a matrix
//! let a: CowMat<f64> = CowMat::zeros(3, 3);
//!
//! // Clone is cheap - shares the underlying data
//! let b = a.clone();
//! assert!(a.is_shared()); // Now shared with b
//!
//! // Reading doesn't trigger a copy
//! let _val = a[(0, 0)];
//!
//! // Writing to b triggers a copy of the data
//! let mut b = b;
//! b.make_mut()[(0, 0)] = 1.0;
//! assert!(!b.is_shared()); // b now has its own copy
//! ```

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use crate::mat::Mat;
use crate::mat_mut::MatMut;
use crate::mat_ref::MatRef;
#[cfg(not(feature = "std"))]
use alloc::sync::Arc;
use core::ops::{Index, IndexMut};
use oxiblas_core::memory::{AlignedVec, DEFAULT_ALIGN};
use oxiblas_core::scalar::Scalar;
#[cfg(feature = "std")]
use std::sync::Arc;

/// Shared matrix data with reference counting.
struct SharedMatData<T: Scalar> {
    /// Underlying data storage.
    data: AlignedVec<T, DEFAULT_ALIGN>,
    /// Number of rows.
    nrows: usize,
    /// Number of columns.
    ncols: usize,
    /// Stride between consecutive rows.
    row_stride: usize,
}

/// A Copy-on-Write matrix.
///
/// This type wraps matrix data in an `Arc`, allowing multiple `CowMat` instances
/// to share the same underlying data. When a mutation is needed, the data is
/// cloned if it's shared with other instances.
///
/// # Performance Characteristics
///
/// - **Clone**: O(1) - just increments reference count
/// - **Read access**: O(1) - direct pointer access
/// - **Write access**: O(1) if unique, O(n*m) if shared (triggers copy)
/// - **Memory**: Shared until mutation
pub struct CowMat<T: Scalar> {
    /// Shared data wrapped in Arc.
    inner: Arc<SharedMatData<T>>,
}

impl<T: Scalar> CowMat<T> {
    /// Creates a new COW matrix filled with zeros.
    pub fn zeros(nrows: usize, ncols: usize) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::zeros(nrows, ncols);
        Self::from_mat(mat)
    }

    /// Creates a new COW matrix filled with a specific value.
    pub fn filled(nrows: usize, ncols: usize, value: T) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::filled(nrows, ncols, value);
        Self::from_mat(mat)
    }

    /// Creates a new COW matrix from a flat slice in column-major order.
    pub fn from_slice(nrows: usize, ncols: usize, data: &[T]) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::from_slice(nrows, ncols, data);
        Self::from_mat(mat)
    }

    /// Creates a new COW matrix from row data.
    pub fn from_rows(rows: &[&[T]]) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::from_rows(rows);
        Self::from_mat(mat)
    }

    /// Creates an identity matrix.
    pub fn eye(n: usize) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::eye(n);
        Self::from_mat(mat)
    }

    /// Creates a diagonal matrix from a slice.
    pub fn diag(diagonal: &[T]) -> Self
    where
        T: bytemuck::Zeroable,
    {
        let mat = Mat::diag(diagonal);
        Self::from_mat(mat)
    }

    /// Creates a COW matrix from an owned Mat.
    ///
    /// Since `mat` is already uniquely owned, this takes ownership of its
    /// backing buffer directly (via `Mat::into_raw_parts`) instead of
    /// allocating a fresh buffer and copying every element -- an O(1) move
    /// rather than an O(nrows * ncols) copy.
    pub fn from_mat(mat: Mat<T>) -> Self {
        let (data, nrows, ncols, row_stride) = mat.into_raw_parts();

        CowMat {
            inner: Arc::new(SharedMatData {
                data,
                nrows,
                ncols,
                row_stride,
            }),
        }
    }

    /// Returns the number of rows.
    #[inline]
    pub fn nrows(&self) -> usize {
        self.inner.nrows
    }

    /// Returns the number of columns.
    #[inline]
    pub fn ncols(&self) -> usize {
        self.inner.ncols
    }

    /// Returns the shape as (nrows, ncols).
    #[inline]
    pub fn shape(&self) -> (usize, usize) {
        (self.inner.nrows, self.inner.ncols)
    }

    /// Returns the row stride.
    #[inline]
    pub fn row_stride(&self) -> usize {
        self.inner.row_stride
    }

    /// Returns true if the data is shared with other CowMat instances.
    #[inline]
    pub fn is_shared(&self) -> bool {
        Arc::strong_count(&self.inner) > 1
    }

    /// Returns true if this is the only reference to the data.
    #[inline]
    pub fn is_unique(&self) -> bool {
        Arc::strong_count(&self.inner) == 1
    }

    /// Returns the reference count.
    #[inline]
    pub fn ref_count(&self) -> usize {
        Arc::strong_count(&self.inner)
    }

    /// Returns an immutable view of the matrix.
    #[inline]
    pub fn as_ref(&self) -> MatRef<'_, T> {
        // SAFETY: `self.inner.data` holds initialized, aligned elements kept alive
        // by the shared `Arc` for the borrow's lifetime, and `row_stride >= nrows`,
        // so every in-bounds `(i, j)` offset is within the allocation.
        unsafe {
            MatRef::new(
                self.inner.data.as_ptr(),
                self.inner.nrows,
                self.inner.ncols,
                self.inner.row_stride,
            )
        }
    }

    /// Returns a pointer to the first element.
    #[inline]
    pub fn as_ptr(&self) -> *const T {
        self.inner.data.as_ptr()
    }

    /// Returns the element at (row, col).
    #[inline]
    pub fn get(&self, row: usize, col: usize) -> Option<&T> {
        if row < self.inner.nrows && col < self.inner.ncols {
            Some(&self.inner.data[row + col * self.inner.row_stride])
        } else {
            None
        }
    }

    /// Returns a submatrix view.
    #[inline]
    pub fn submatrix(
        &self,
        row_start: usize,
        col_start: usize,
        nrows: usize,
        ncols: usize,
    ) -> MatRef<'_, T> {
        self.as_ref().submatrix(row_start, col_start, nrows, ncols)
    }

    /// Returns a column view.
    #[inline]
    pub fn col(&self, j: usize) -> MatRef<'_, T> {
        assert!(j < self.inner.ncols, "Column index out of bounds");
        self.submatrix(0, j, self.inner.nrows, 1)
    }

    /// Returns a row view.
    #[inline]
    pub fn row(&self, i: usize) -> MatRef<'_, T> {
        assert!(i < self.inner.nrows, "Row index out of bounds");
        self.submatrix(i, 0, 1, self.inner.ncols)
    }

    /// Returns the diagonal as a vector.
    pub fn diagonal(&self) -> Vec<T> {
        let n = self.inner.nrows.min(self.inner.ncols);
        (0..n)
            .map(|i| self.inner.data[i + i * self.inner.row_stride])
            .collect()
    }

    /// Converts to an owned Mat, cloning if shared.
    pub fn into_owned(self) -> Mat<T>
    where
        T: bytemuck::Zeroable,
    {
        self.to_mat()
    }

    /// Creates a new owned Mat from this COW matrix.
    pub fn to_mat(&self) -> Mat<T>
    where
        T: bytemuck::Zeroable,
    {
        let mut mat = Mat::zeros(self.inner.nrows, self.inner.ncols);
        let mut mat_mut = mat.as_mut();
        let self_ref = self.as_ref();

        for j in 0..self.inner.ncols {
            for i in 0..self.inner.nrows {
                mat_mut[(i, j)] = self_ref[(i, j)];
            }
        }

        mat
    }

    /// Ensures unique ownership, cloning if necessary, and returns a mutable view.
    ///
    /// This is the key COW operation. If the data is shared, it will be cloned
    /// before returning a mutable reference.
    pub fn make_mut(&mut self) -> MatMut<'_, T> {
        // If we're not unique, we need to clone the data
        if !self.is_unique() {
            let cloned = SharedMatData {
                data: self.inner.data.clone(),
                nrows: self.inner.nrows,
                ncols: self.inner.ncols,
                row_stride: self.inner.row_stride,
            };
            self.inner = Arc::new(cloned);
        }

        // Now we're guaranteed to be unique, get mutable access
        // Safety: We just ensured we're the only owner
        let inner = Arc::get_mut(&mut self.inner).expect("Should be unique after clone");

        // SAFETY: `inner.data` holds `row_stride * ncols` initialized, aligned
        // elements and `row_stride >= nrows`, so every in-bounds `(i, j)`
        // offset is within the allocation and no two indices alias; the
        // `Arc::get_mut` above proves this handle is unique, and `&mut self`
        // keeps it alive and exclusive for the view's lifetime.
        unsafe {
            MatMut::new(
                inner.data.as_mut_ptr(),
                inner.nrows,
                inner.ncols,
                inner.row_stride,
            )
        }
    }

    /// Sets an element, cloning if the data is shared.
    pub fn set(&mut self, row: usize, col: usize, value: T) {
        assert!(
            row < self.inner.nrows && col < self.inner.ncols,
            "Index out of bounds"
        );
        self.make_mut()[(row, col)] = value;
    }

    /// Returns a mutable pointer, cloning if shared.
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.make_mut().as_mut_ptr()
    }
}

impl<T: Scalar> Clone for CowMat<T> {
    /// Clone is O(1) - just increments the reference count.
    #[inline]
    fn clone(&self) -> Self {
        CowMat {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T: Scalar> Index<(usize, usize)> for CowMat<T> {
    type Output = T;

    #[inline]
    fn index(&self, (row, col): (usize, usize)) -> &Self::Output {
        assert!(
            row < self.inner.nrows && col < self.inner.ncols,
            "Index out of bounds"
        );
        &self.inner.data[row + col * self.inner.row_stride]
    }
}

impl<T: Scalar> IndexMut<(usize, usize)> for CowMat<T> {
    /// Mutable indexing triggers copy-on-write if the data is shared.
    #[inline]
    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut Self::Output {
        assert!(
            row < self.inner.nrows && col < self.inner.ncols,
            "Index out of bounds"
        );

        // Ensure we have unique ownership
        if !self.is_unique() {
            let cloned = SharedMatData {
                data: self.inner.data.clone(),
                nrows: self.inner.nrows,
                ncols: self.inner.ncols,
                row_stride: self.inner.row_stride,
            };
            self.inner = Arc::new(cloned);
        }

        let inner = Arc::get_mut(&mut self.inner).expect("Should be unique");
        let idx = row + col * inner.row_stride;
        &mut inner.data[idx]
    }
}

impl<T: Scalar + bytemuck::Zeroable> From<Mat<T>> for CowMat<T> {
    fn from(mat: Mat<T>) -> Self {
        CowMat::from_mat(mat)
    }
}

impl<T: Scalar + core::fmt::Debug> core::fmt::Debug for CowMat<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CowMat")
            .field("nrows", &self.inner.nrows)
            .field("ncols", &self.inner.ncols)
            .field("ref_count", &self.ref_count())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cow_basic() {
        let a: CowMat<f64> = CowMat::zeros(3, 3);
        assert_eq!(a.nrows(), 3);
        assert_eq!(a.ncols(), 3);
        assert!(!a.is_shared());
        assert_eq!(a.ref_count(), 1);
    }

    #[test]
    fn test_cow_clone_shares_data() {
        let a: CowMat<f64> = CowMat::zeros(3, 3);
        let b = a.clone();

        assert!(a.is_shared());
        assert!(b.is_shared());
        assert_eq!(a.ref_count(), 2);
        assert_eq!(b.ref_count(), 2);

        // Data pointers should be the same
        assert_eq!(a.as_ptr(), b.as_ptr());
    }

    #[test]
    fn test_cow_read_no_copy() {
        let a: CowMat<f64> = CowMat::filled(3, 3, 1.0);
        let b = a.clone();

        // Reading shouldn't trigger a copy
        let _val = a[(0, 0)];
        let _val = b[(1, 1)];

        assert!(a.is_shared());
        assert_eq!(a.as_ptr(), b.as_ptr());
    }

    #[test]
    fn test_cow_write_triggers_copy() {
        let a: CowMat<f64> = CowMat::filled(3, 3, 1.0);
        let mut b = a.clone();

        let a_ptr = a.as_ptr();
        let b_ptr_before = b.as_ptr();
        assert_eq!(a_ptr, b_ptr_before);

        // Writing to b should trigger a copy
        b[(0, 0)] = 2.0;

        let b_ptr_after = b.as_ptr();
        assert_ne!(a_ptr, b_ptr_after); // b now has its own data

        // a should still have original value
        assert_eq!(a[(0, 0)], 1.0);
        // b should have new value
        assert_eq!(b[(0, 0)], 2.0);

        // a is no longer shared (b has its own copy)
        assert!(!a.is_shared());
        assert!(!b.is_shared());
    }

    #[test]
    fn test_cow_make_mut() {
        let a: CowMat<f64> = CowMat::zeros(3, 3);
        let mut b = a.clone();

        assert!(b.is_shared());

        {
            let mut mut_view = b.make_mut();
            mut_view[(0, 0)] = 5.0;
        }

        assert!(!b.is_shared());
        assert_eq!(b[(0, 0)], 5.0);
        assert_eq!(a[(0, 0)], 0.0);
    }

    #[test]
    fn test_cow_from_mat() {
        let mat: Mat<f64> = Mat::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]]);

        let cow: CowMat<f64> = CowMat::from_mat(mat);

        assert_eq!(cow.nrows(), 2);
        assert_eq!(cow.ncols(), 3);
        assert_eq!(cow[(0, 0)], 1.0);
        assert_eq!(cow[(1, 2)], 6.0);
    }

    // Regression test for finding #2: `CowMat::from_mat` used to allocate a
    // fresh zeroed buffer and copy the source `Mat` into it element by
    // element, even though `mat` was already uniquely owned and could just
    // be moved. A correct O(1) move must leave the backing pointer (and the
    // exact bit pattern of the padding elements) untouched.
    #[test]
    fn test_cow_from_mat_moves_buffer_without_copy() {
        let mut mat: Mat<f64> = Mat::from_rows(&[
            &[1.0, 2.0, 3.0],
            &[4.0, 5.0, 6.0],
            &[7.0, 8.0, 9.0],
            &[10.0, 11.0, 12.0],
        ]);
        // Stamp a sentinel into the row-stride padding region (rows beyond
        // `nrows` up to `row_stride`, if any) so that a "reallocate + copy
        // only the logical elements" implementation would be caught
        // silently dropping it, in addition to the pointer-identity check
        // below being the primary signal that no reallocation occurred.
        let row_stride = mat.row_stride();
        let nrows = mat.nrows();
        for pad_row in nrows..row_stride {
            mat.raw_data_mut()[pad_row] = -1.0;
        }

        let original_ptr = mat.as_ptr();
        let original_row_stride = mat.row_stride();

        let cow: CowMat<f64> = CowMat::from_mat(mat);

        // A genuine move keeps the exact same allocation: the CowMat's
        // backing pointer must be identical to the Mat's original pointer.
        assert_eq!(cow.as_ptr(), original_ptr);
        assert_eq!(cow.row_stride(), original_row_stride);
        assert_eq!(cow.nrows(), 4);
        assert_eq!(cow.ncols(), 3);
        assert_eq!(cow[(0, 0)], 1.0);
        assert_eq!(cow[(3, 2)], 12.0);

        // A fresh `AlignedVec::zeros` + element-by-element copy (the old,
        // buggy behavior) would have zeroed the padding region rather than
        // preserving it, since only the logical `nrows x ncols` elements
        // get copied. Reading the sentinel back proves the exact same
        // memory (padding included) survived the move untouched.
        if row_stride > nrows {
            let padding_val = unsafe { *cow.as_ptr().add(nrows) };
            assert_eq!(padding_val, -1.0);
        }
    }

    #[test]
    fn test_cow_to_mat() {
        let cow: CowMat<f64> = CowMat::from_rows(&[&[1.0, 2.0], &[3.0, 4.0]]);

        let mat = cow.to_mat();

        assert_eq!(mat.nrows(), 2);
        assert_eq!(mat.ncols(), 2);
        assert_eq!(mat[(0, 0)], 1.0);
        assert_eq!(mat[(1, 1)], 4.0);
    }

    #[test]
    fn test_cow_diagonal() {
        let cow: CowMat<f64> =
            CowMat::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0], &[7.0, 8.0, 9.0]]);

        let diag = cow.diagonal();
        assert_eq!(diag, vec![1.0, 5.0, 9.0]);
    }

    #[test]
    fn test_cow_submatrix() {
        let cow: CowMat<f64> =
            CowMat::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0], &[7.0, 8.0, 9.0]]);

        let sub = cow.submatrix(1, 1, 2, 2);
        assert_eq!(sub[(0, 0)], 5.0);
        assert_eq!(sub[(1, 1)], 9.0);
    }

    #[test]
    fn test_cow_eye() {
        let cow: CowMat<f64> = CowMat::eye(3);

        assert_eq!(cow[(0, 0)], 1.0);
        assert_eq!(cow[(1, 1)], 1.0);
        assert_eq!(cow[(2, 2)], 1.0);
        assert_eq!(cow[(0, 1)], 0.0);
    }

    #[test]
    fn test_cow_unique_no_copy_on_write() {
        let mut a: CowMat<f64> = CowMat::filled(3, 3, 1.0);

        let ptr_before = a.as_ptr();

        // Since we're unique, writing shouldn't allocate new memory
        a[(0, 0)] = 2.0;

        let ptr_after = a.as_ptr();
        assert_eq!(ptr_before, ptr_after); // Same memory
        assert_eq!(a[(0, 0)], 2.0);
    }

    #[test]
    fn test_cow_multiple_clones() {
        let a: CowMat<f64> = CowMat::zeros(2, 2);
        let b = a.clone();
        let c = a.clone();

        assert_eq!(a.ref_count(), 3);
        assert_eq!(b.ref_count(), 3);
        assert_eq!(c.ref_count(), 3);

        drop(b);

        assert_eq!(a.ref_count(), 2);
        assert_eq!(c.ref_count(), 2);
    }

    #[test]
    fn test_cow_set() {
        let a: CowMat<f64> = CowMat::zeros(2, 2);
        let mut b = a.clone();

        b.set(0, 0, 10.0);

        assert_eq!(a[(0, 0)], 0.0);
        assert_eq!(b[(0, 0)], 10.0);
    }
}