oxiblas-sparse 0.2.2

Sparse matrix support 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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Matrix Market format support.
//!
//! This module provides reading and writing of sparse matrices in
//! Matrix Market (MM) format, the standard exchange format used by
//! the SuiteSparse Matrix Collection (formerly Florida Matrix Collection).
//!
//! # Format Overview
//!
//! Matrix Market files consist of:
//! 1. A header line: `%%MatrixMarket matrix coordinate real general`
//! 2. Optional comment lines starting with `%`
//! 3. A size line: `nrows ncols nnz`
//! 4. Data lines: `row col value` (1-indexed)
//!
//! # Supported Types
//!
//! - **Coordinate format** (sparse): real, complex, pattern, integer
//! - **Array format** (dense): not yet implemented
//!
//! # Symmetry
//!
//! - **general**: No symmetry assumed
//! - **symmetric**: Only lower triangle stored, A = A^T
//! - **skew-symmetric**: Only lower triangle stored, A = -A^T
//! - **hermitian**: Only lower triangle stored, A = A^H (complex only)
//!
//! # Example
//!
//! ```
//! use oxiblas_sparse::csr::CsrMatrix;
//! use oxiblas_sparse::mtx::{read_matrix_market, write_matrix_market};
//!
//! // Never hardcode a path: build one from the OS temp directory plus a
//! // name unique to this process.
//! let path = std::env::temp_dir().join(format!("oxiblas-doctest-{}.mtx", std::process::id()));
//!
//! let original =
//!     CsrMatrix::<f64>::new(2, 2, vec![0, 1, 2], vec![0, 1], vec![1.0, 2.0]).unwrap();
//!
//! // Write a matrix to file
//! write_matrix_market(&original, &path, Some("My matrix"))?;
//!
//! // Read it back
//! let csr = read_matrix_market::<f64, _>(&path)?;
//! assert_eq!(csr.nrows(), 2);
//! assert_eq!(csr.nnz(), 2);
//!
//! std::fs::remove_file(&path)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::coo::CooMatrix;
use crate::csr::CsrMatrix;
use num_traits::ToPrimitive;
use oxiblas_core::scalar::{Field, Real, Scalar};
use std::io::{BufRead, BufReader, Write};
use std::path::Path;

/// Upper bound on how many entries a reader will pre-allocate from the
/// **untrusted** `nnz` field of a Matrix Market size line.
///
/// The size line is the first thing in the file and is not cross-checkable
/// against anything until the data lines have been read, so a ~30-byte file can
/// claim `usize::MAX` non-zeros. Reserving that claim verbatim turns the claim
/// into an immediate allocation failure (process abort), which is a
/// denial-of-service reachable from the public `read_matrix_market` API. Files
/// with more entries than this still load correctly — the vectors just grow.
///
/// 1 Mi entries is roughly 8 MiB per index vector on a 64-bit target, which
/// covers the overwhelming majority of SuiteSparse matrices in one shot.
const MAX_PREALLOC_ENTRIES: usize = 1 << 20;

/// Error type for Matrix Market operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MtxError {
    /// Invalid header format.
    InvalidHeader(String),
    /// Invalid data format.
    InvalidData(String),
    /// Unsupported matrix type.
    UnsupportedType(String),
    /// I/O error.
    IoError(String),
    /// Parse error.
    ParseError(String),
    /// Missing size line.
    MissingSizeLine,
    /// Index out of bounds.
    IndexOutOfBounds {
        /// Row index.
        row: usize,
        /// Column index.
        col: usize,
        /// Matrix rows.
        nrows: usize,
        /// Matrix columns.
        ncols: usize,
    },
}

impl core::fmt::Display for MtxError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidHeader(s) => write!(f, "Invalid Matrix Market header: {s}"),
            Self::InvalidData(s) => write!(f, "Invalid data: {s}"),
            Self::UnsupportedType(s) => write!(f, "Unsupported matrix type: {s}"),
            Self::IoError(s) => write!(f, "I/O error: {s}"),
            Self::ParseError(s) => write!(f, "Parse error: {s}"),
            Self::MissingSizeLine => write!(f, "Missing size line"),
            Self::IndexOutOfBounds {
                row,
                col,
                nrows,
                ncols,
            } => {
                write!(
                    f,
                    "Index ({row}, {col}) out of bounds for {nrows}×{ncols} matrix"
                )
            }
        }
    }
}

impl std::error::Error for MtxError {}

/// Matrix Market object type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MtxObject {
    /// Matrix.
    Matrix,
    /// Vector.
    Vector,
}

/// Matrix Market format type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MtxFormat {
    /// Coordinate (sparse) format.
    Coordinate,
    /// Array (dense) format.
    Array,
}

/// Matrix Market field type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MtxField {
    /// Real values.
    Real,
    /// Complex values.
    Complex,
    /// Pattern only (structure, no values).
    Pattern,
    /// Integer values.
    Integer,
}

/// Matrix Market symmetry type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MtxSymmetry {
    /// General (no symmetry).
    General,
    /// Symmetric: A = A^T.
    Symmetric,
    /// Skew-symmetric: A = -A^T.
    SkewSymmetric,
    /// Hermitian: A = A^H.
    Hermitian,
}

/// Matrix Market header information.
#[derive(Debug, Clone)]
pub struct MtxHeader {
    /// Object type (matrix or vector).
    pub object: MtxObject,
    /// Format type (coordinate or array).
    pub format: MtxFormat,
    /// Field type (real, complex, pattern, integer).
    pub field: MtxField,
    /// Symmetry type.
    pub symmetry: MtxSymmetry,
    /// Number of rows.
    pub nrows: usize,
    /// Number of columns.
    pub ncols: usize,
    /// Number of stored entries (for coordinate format).
    pub nnz: usize,
    /// Comment lines (without leading %).
    pub comments: Vec<String>,
}

/// Parses a Matrix Market header line.
fn parse_header_line(
    line: &str,
) -> Result<(MtxObject, MtxFormat, MtxField, MtxSymmetry), MtxError> {
    let line = line.to_lowercase();

    if !line.starts_with("%%matrixmarket") {
        return Err(MtxError::InvalidHeader(
            "Header must start with %%MatrixMarket".to_string(),
        ));
    }

    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 5 {
        return Err(MtxError::InvalidHeader(
            "Header must have 5 parts".to_string(),
        ));
    }

    let object = match parts[1] {
        "matrix" => MtxObject::Matrix,
        "vector" => MtxObject::Vector,
        other => {
            return Err(MtxError::UnsupportedType(format!(
                "Unknown object type: {other}"
            )));
        }
    };

    let format = match parts[2] {
        "coordinate" => MtxFormat::Coordinate,
        "array" => MtxFormat::Array,
        other => {
            return Err(MtxError::UnsupportedType(format!(
                "Unknown format: {other}"
            )));
        }
    };

    let field = match parts[3] {
        "real" => MtxField::Real,
        "double" => MtxField::Real,
        "complex" => MtxField::Complex,
        "pattern" => MtxField::Pattern,
        "integer" => MtxField::Integer,
        other => {
            return Err(MtxError::UnsupportedType(format!(
                "Unknown field type: {other}"
            )));
        }
    };

    let symmetry = match parts[4] {
        "general" => MtxSymmetry::General,
        "symmetric" => MtxSymmetry::Symmetric,
        "skew-symmetric" => MtxSymmetry::SkewSymmetric,
        "hermitian" => MtxSymmetry::Hermitian,
        other => {
            return Err(MtxError::UnsupportedType(format!(
                "Unknown symmetry: {other}"
            )));
        }
    };

    Ok((object, format, field, symmetry))
}

/// Reads a Matrix Market file header.
///
/// Returns the header information and the reader positioned after comments.
pub fn read_header<R: BufRead>(reader: &mut R) -> Result<MtxHeader, MtxError> {
    let mut line = String::new();

    // Read header line
    reader
        .read_line(&mut line)
        .map_err(|e| MtxError::IoError(e.to_string()))?;

    let (object, format, field, symmetry) = parse_header_line(line.trim())?;

    // Read comments
    let mut comments = Vec::new();
    loop {
        line.clear();
        reader
            .read_line(&mut line)
            .map_err(|e| MtxError::IoError(e.to_string()))?;

        if line.is_empty() {
            return Err(MtxError::MissingSizeLine);
        }

        let trimmed = line.trim();
        if trimmed.starts_with('%') {
            comments.push(trimmed[1..].trim().to_string());
        } else {
            // This is the size line
            break;
        }
    }

    // Parse size line
    let size_parts: Vec<&str> = line.split_whitespace().collect();

    let (nrows, ncols, nnz) = match format {
        MtxFormat::Coordinate => {
            if size_parts.len() < 3 {
                return Err(MtxError::InvalidData(
                    "Coordinate size line must have 3 values".to_string(),
                ));
            }
            let nrows = size_parts[0]
                .parse::<usize>()
                .map_err(|_| MtxError::ParseError("Invalid nrows".to_string()))?;
            let ncols = size_parts[1]
                .parse::<usize>()
                .map_err(|_| MtxError::ParseError("Invalid ncols".to_string()))?;
            let nnz = size_parts[2]
                .parse::<usize>()
                .map_err(|_| MtxError::ParseError("Invalid nnz".to_string()))?;
            // A coordinate matrix cannot declare more stored entries than it
            // has cells. Rejecting here stops a hand-crafted ~30-byte file
            // (`3 3 18446744073709551615`) from driving downstream
            // reservations, and it is the header field callers trust most.
            // `saturating_mul` is deliberate: if `nrows * ncols` overflows
            // `usize` the true bound is above any representable `nnz`, so the
            // saturated value is still a sound upper bound.
            let max_nnz = nrows.saturating_mul(ncols);
            if nnz > max_nnz {
                return Err(MtxError::InvalidData(format!(
                    "nnz ({nnz}) exceeds the number of cells in a {nrows}x{ncols} \
                     matrix ({max_nnz})"
                )));
            }
            (nrows, ncols, nnz)
        }
        MtxFormat::Array => {
            if size_parts.len() < 2 {
                return Err(MtxError::InvalidData(
                    "Array size line must have 2 values".to_string(),
                ));
            }
            let nrows = size_parts[0]
                .parse::<usize>()
                .map_err(|_| MtxError::ParseError("Invalid nrows".to_string()))?;
            let ncols = size_parts[1]
                .parse::<usize>()
                .map_err(|_| MtxError::ParseError("Invalid ncols".to_string()))?;
            // Array (dense) format has one entry per cell. `nrows` and `ncols`
            // come straight out of an untrusted file, so a plain `*` would
            // panic in debug and silently wrap to a bogus `nnz` (e.g. 0) in
            // release for a size line such as `4294967296 4294967296`.
            let nnz = nrows.checked_mul(ncols).ok_or_else(|| {
                MtxError::InvalidData(format!("array dimensions overflow usize: {nrows}x{ncols}"))
            })?;
            (nrows, ncols, nnz)
        }
    };

    Ok(MtxHeader {
        object,
        format,
        field,
        symmetry,
        nrows,
        ncols,
        nnz,
        comments,
    })
}

/// Reads a Matrix Market file and returns a CSR matrix.
///
/// # Arguments
///
/// * `path` - Path to the Matrix Market file
///
/// # Errors
///
/// Returns an error if:
/// - The file cannot be read
/// - The format is not supported
/// - The data is invalid
pub fn read_matrix_market<T: Scalar<Real = T> + Clone + Field + Real, P: AsRef<Path>>(
    path: P,
) -> Result<CsrMatrix<T>, MtxError> {
    let file = std::fs::File::open(path).map_err(|e| MtxError::IoError(e.to_string()))?;

    let mut reader = BufReader::new(file);
    read_matrix_market_from_reader(&mut reader)
}

/// Reads a Matrix Market file from a reader.
pub fn read_matrix_market_from_reader<T: Scalar<Real = T> + Clone + Field + Real, R: BufRead>(
    reader: &mut R,
) -> Result<CsrMatrix<T>, MtxError> {
    let header = read_header(reader)?;

    if header.format != MtxFormat::Coordinate {
        return Err(MtxError::UnsupportedType(
            "Only coordinate format is supported".to_string(),
        ));
    }

    if header.field == MtxField::Complex {
        return Err(MtxError::UnsupportedType(
            "Complex matrices not supported for real type".to_string(),
        ));
    }

    // Read data entries.
    //
    // `header.nnz` is attacker-controlled: it is whatever the file's size line
    // claimed. Reserving it outright lets a tiny file request an astronomical
    // allocation and abort the process before a single data line is read, so
    // the reservation is capped at `MAX_PREALLOC_ENTRIES`. Honest files simply
    // let the `Vec`s grow; the cap only costs a few reallocations.
    let prealloc = header.nnz.min(MAX_PREALLOC_ENTRIES);
    let mut rows = Vec::with_capacity(prealloc);
    let mut cols = Vec::with_capacity(prealloc);
    let mut vals = Vec::with_capacity(prealloc);

    for line_result in reader.lines() {
        let line = line_result.map_err(|e| MtxError::IoError(e.to_string()))?;
        let trimmed = line.trim();

        if trimmed.is_empty() || trimmed.starts_with('%') {
            continue;
        }

        let parts: Vec<&str> = trimmed.split_whitespace().collect();

        if parts.len() < 2 {
            return Err(MtxError::InvalidData(format!(
                "Invalid data line: {trimmed}"
            )));
        }

        let row: usize = parts[0]
            .parse()
            .map_err(|_| MtxError::ParseError(format!("Invalid row: {}", parts[0])))?;
        let col: usize = parts[1]
            .parse()
            .map_err(|_| MtxError::ParseError(format!("Invalid col: {}", parts[1])))?;

        // Convert from 1-indexed to 0-indexed
        if row == 0 || col == 0 {
            return Err(MtxError::IndexOutOfBounds {
                row,
                col,
                nrows: header.nrows,
                ncols: header.ncols,
            });
        }
        let row = row - 1;
        let col = col - 1;

        if row >= header.nrows || col >= header.ncols {
            return Err(MtxError::IndexOutOfBounds {
                row: row + 1,
                col: col + 1,
                nrows: header.nrows,
                ncols: header.ncols,
            });
        }

        let val = if header.field == MtxField::Pattern {
            T::one()
        } else {
            if parts.len() < 3 {
                return Err(MtxError::InvalidData(format!(
                    "Missing value on line: {trimmed}"
                )));
            }
            parts[2]
                .parse::<f64>()
                .map_err(|_| MtxError::ParseError(format!("Invalid value: {}", parts[2])))
                .and_then(|v| {
                    T::from_f64(v)
                        .ok_or_else(|| MtxError::ParseError(format!("Cannot convert value: {v}")))
                })?
        };

        rows.push(row);
        cols.push(col);
        vals.push(val.clone());

        // Handle symmetry
        if row != col {
            match header.symmetry {
                MtxSymmetry::Symmetric => {
                    rows.push(col);
                    cols.push(row);
                    vals.push(val);
                }
                MtxSymmetry::SkewSymmetric => {
                    rows.push(col);
                    cols.push(row);
                    vals.push(T::zero() - val);
                }
                MtxSymmetry::Hermitian => {
                    // For real matrices, Hermitian = Symmetric
                    rows.push(col);
                    cols.push(row);
                    vals.push(val);
                }
                MtxSymmetry::General => {}
            }
        }
    }

    // Build COO and convert to CSR
    let coo = CooMatrix::new(header.nrows, header.ncols, rows, cols, vals)
        .map_err(|e| MtxError::InvalidData(format!("Failed to create COO matrix: {e:?}")))?;

    Ok(crate::convert::coo_to_csr(&coo))
}

/// Reads a Matrix Market file and returns a COO matrix.
pub fn read_matrix_market_coo<T: Scalar<Real = T> + Clone + Field + Real, P: AsRef<Path>>(
    path: P,
) -> Result<CooMatrix<T>, MtxError> {
    let csr: CsrMatrix<T> = read_matrix_market(path)?;
    Ok(crate::convert::csr_to_coo(&csr))
}

/// Writes a CSR matrix to Matrix Market format.
///
/// # Arguments
///
/// * `csr` - The matrix to write
/// * `path` - Path to write to
/// * `comment` - Optional comment to include in the file
///
/// # Errors
///
/// Returns an error if the file cannot be written.
pub fn write_matrix_market<T: Scalar + Clone + Field + ToPrimitive, P: AsRef<Path>>(
    csr: &CsrMatrix<T>,
    path: P,
    comment: Option<&str>,
) -> Result<(), MtxError> {
    let file = std::fs::File::create(path).map_err(|e| MtxError::IoError(e.to_string()))?;

    let mut writer = std::io::BufWriter::new(file);
    write_matrix_market_to_writer(csr, &mut writer, comment)
}

/// Writes a CSR matrix to Matrix Market format using a writer.
pub fn write_matrix_market_to_writer<T: Scalar + Clone + Field + ToPrimitive, W: Write>(
    csr: &CsrMatrix<T>,
    writer: &mut W,
    comment: Option<&str>,
) -> Result<(), MtxError> {
    let eps = <T as Scalar>::epsilon();

    // Count actual non-zeros
    let mut nnz = 0;
    for (_, _, val) in csr.iter() {
        if Scalar::abs(val.clone()) > eps {
            nnz += 1;
        }
    }

    // Write header
    writeln!(writer, "%%MatrixMarket matrix coordinate real general")
        .map_err(|e| MtxError::IoError(e.to_string()))?;

    // Write comment if provided
    if let Some(c) = comment {
        for line in c.lines() {
            writeln!(writer, "% {line}").map_err(|e| MtxError::IoError(e.to_string()))?;
        }
    }

    // Write size line
    writeln!(writer, "{} {} {}", csr.nrows(), csr.ncols(), nnz)
        .map_err(|e| MtxError::IoError(e.to_string()))?;

    // Write data (1-indexed)
    for (row, col, val) in csr.iter() {
        if Scalar::abs(val.clone()) > eps {
            let f = val.to_f64().unwrap_or(0.0);
            writeln!(writer, "{} {} {}", row + 1, col + 1, f)
                .map_err(|e| MtxError::IoError(e.to_string()))?;
        }
    }

    Ok(())
}

/// Writes a symmetric CSR matrix to Matrix Market format.
///
/// Only writes the lower triangle, with symmetric flag.
pub fn write_matrix_market_symmetric<T: Scalar + Clone + Field + ToPrimitive, P: AsRef<Path>>(
    csr: &CsrMatrix<T>,
    path: P,
    comment: Option<&str>,
) -> Result<(), MtxError> {
    let file = std::fs::File::create(path).map_err(|e| MtxError::IoError(e.to_string()))?;

    let mut writer = std::io::BufWriter::new(file);
    let eps = <T as Scalar>::epsilon();

    // Count lower triangle non-zeros
    let mut nnz = 0;
    for (row, col, val) in csr.iter() {
        if row >= col && Scalar::abs(val.clone()) > eps {
            nnz += 1;
        }
    }

    // Write header
    writeln!(writer, "%%MatrixMarket matrix coordinate real symmetric")
        .map_err(|e| MtxError::IoError(e.to_string()))?;

    if let Some(c) = comment {
        for line in c.lines() {
            writeln!(writer, "% {line}").map_err(|e| MtxError::IoError(e.to_string()))?;
        }
    }

    writeln!(writer, "{} {} {}", csr.nrows(), csr.ncols(), nnz)
        .map_err(|e| MtxError::IoError(e.to_string()))?;

    // Write lower triangle only (1-indexed)
    for (row, col, val) in csr.iter() {
        if row >= col && Scalar::abs(val.clone()) > eps {
            let f = val.to_f64().unwrap_or(0.0);
            writeln!(writer, "{} {} {}", row + 1, col + 1, f)
                .map_err(|e| MtxError::IoError(e.to_string()))?;
        }
    }

    Ok(())
}

/// Reads Matrix Market format from a string.
pub fn read_matrix_market_str<T: Scalar<Real = T> + Clone + Field + Real>(
    s: &str,
) -> Result<CsrMatrix<T>, MtxError> {
    let mut reader = BufReader::new(s.as_bytes());
    read_matrix_market_from_reader(&mut reader)
}

/// Writes a CSR matrix to Matrix Market format as a string.
pub fn write_matrix_market_str<T: Scalar + Clone + Field + ToPrimitive>(
    csr: &CsrMatrix<T>,
    comment: Option<&str>,
) -> Result<String, MtxError> {
    let mut buf = Vec::new();
    write_matrix_market_to_writer(csr, &mut buf, comment)?;
    String::from_utf8(buf).map_err(|e| MtxError::IoError(e.to_string()))
}

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

    #[test]
    fn test_parse_header() {
        let (obj, fmt, field, sym) =
            parse_header_line("%%MatrixMarket matrix coordinate real general").unwrap();

        assert_eq!(obj, MtxObject::Matrix);
        assert_eq!(fmt, MtxFormat::Coordinate);
        assert_eq!(field, MtxField::Real);
        assert_eq!(sym, MtxSymmetry::General);
    }

    #[test]
    fn test_parse_header_symmetric() {
        let (_, _, _, sym) =
            parse_header_line("%%MatrixMarket matrix coordinate real symmetric").unwrap();

        assert_eq!(sym, MtxSymmetry::Symmetric);
    }

    #[test]
    fn test_read_simple_matrix() {
        let mtx = r#"%%MatrixMarket matrix coordinate real general
% A simple test matrix
3 3 5
1 1 1.0
1 3 2.0
2 2 3.0
3 1 4.0
3 3 5.0
"#;

        let csr: CsrMatrix<f64> = read_matrix_market_str(mtx).unwrap();

        assert_eq!(csr.nrows(), 3);
        assert_eq!(csr.ncols(), 3);
        assert_eq!(csr.nnz(), 5);

        assert_eq!(csr.get(0, 0), Some(&1.0));
        assert_eq!(csr.get(0, 2), Some(&2.0));
        assert_eq!(csr.get(1, 1), Some(&3.0));
        assert_eq!(csr.get(2, 0), Some(&4.0));
        assert_eq!(csr.get(2, 2), Some(&5.0));
    }

    #[test]
    fn test_read_symmetric_matrix() {
        let mtx = r#"%%MatrixMarket matrix coordinate real symmetric
3 3 4
1 1 1.0
2 1 2.0
2 2 3.0
3 3 4.0
"#;

        let csr: CsrMatrix<f64> = read_matrix_market_str(mtx).unwrap();

        assert_eq!(csr.nrows(), 3);
        assert_eq!(csr.ncols(), 3);

        // Symmetric entries
        assert_eq!(csr.get(0, 0), Some(&1.0));
        assert_eq!(csr.get(1, 0), Some(&2.0));
        assert_eq!(csr.get(0, 1), Some(&2.0)); // Symmetric fill-in
        assert_eq!(csr.get(1, 1), Some(&3.0));
        assert_eq!(csr.get(2, 2), Some(&4.0));
    }

    #[test]
    fn test_read_pattern_matrix() {
        let mtx = r#"%%MatrixMarket matrix coordinate pattern general
2 2 2
1 1
2 2
"#;

        let csr: CsrMatrix<f64> = read_matrix_market_str(mtx).unwrap();

        assert_eq!(csr.get(0, 0), Some(&1.0));
        assert_eq!(csr.get(1, 1), Some(&1.0));
    }

    #[test]
    fn test_write_read_roundtrip() {
        // Create a simple matrix
        let values = vec![1.0f64, 2.0, 3.0, 4.0, 5.0];
        let col_indices = vec![0, 2, 1, 0, 2];
        let row_ptrs = vec![0, 2, 3, 5];

        let csr = CsrMatrix::new(3, 3, row_ptrs, col_indices, values).unwrap();

        // Write to string
        let mtx_str = write_matrix_market_str(&csr, Some("Test matrix")).unwrap();

        // Read back
        let csr2: CsrMatrix<f64> = read_matrix_market_str(&mtx_str).unwrap();

        assert_eq!(csr.nrows(), csr2.nrows());
        assert_eq!(csr.ncols(), csr2.ncols());
        assert_eq!(csr.nnz(), csr2.nnz());

        for row in 0..3 {
            for col in 0..3 {
                let v1 = csr.get(row, col).cloned().unwrap_or(0.0);
                let v2 = csr2.get(row, col).cloned().unwrap_or(0.0);
                assert!((v1 - v2).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_header_parsing_error() {
        let result = parse_header_line("invalid header");
        assert!(result.is_err());
    }

    #[test]
    fn test_index_error() {
        let mtx = r#"%%MatrixMarket matrix coordinate real general
2 2 1
3 1 1.0
"#;

        let result: Result<CsrMatrix<f64>, _> = read_matrix_market_str(mtx);
        assert!(result.is_err());
    }

    // --- Regression: untrusted header fields must not drive allocations -----

    #[test]
    fn test_absurd_nnz_is_rejected_not_preallocated() {
        // A ~40-byte file claiming usize::MAX non-zeros used to reach three
        // `Vec::with_capacity(usize::MAX)` calls before a single data line was
        // read -> allocation failure -> process abort (a DoS reachable through
        // the public `read_matrix_market` API).
        let mtx = "%%MatrixMarket matrix coordinate real general\n3 3 18446744073709551615\n";

        let result: Result<CsrMatrix<f64>, _> = read_matrix_market_str(mtx);
        match result {
            Err(MtxError::InvalidData(msg)) => assert!(msg.contains("nnz")),
            Err(other) => panic!("expected InvalidData about nnz, got {other:?}"),
            Ok(_) => panic!("a 3x3 matrix claiming 2^64-1 non-zeros was accepted"),
        }
    }

    #[test]
    fn test_nnz_above_cell_count_is_rejected() {
        let mtx = "%%MatrixMarket matrix coordinate real general\n2 2 5\n";
        let result: Result<CsrMatrix<f64>, _> = read_matrix_market_str(mtx);
        assert!(matches!(result, Err(MtxError::InvalidData(_))));
    }

    #[test]
    fn test_large_but_legal_nnz_still_parses() {
        // The reservation cap must not change observable behavior: a header
        // claiming far more entries than the file actually contains still
        // parses the entries that are present.
        let mtx = "%%MatrixMarket matrix coordinate real general\n3 3 9\n1 1 1.0\n2 2 2.0\n";
        let csr: CsrMatrix<f64> = read_matrix_market_str(mtx).expect("valid file");
        assert_eq!(csr.nnz(), 2);
        assert_eq!(csr.get(0, 0), Some(&1.0));
        assert_eq!(csr.get(1, 1), Some(&2.0));
    }

    #[test]
    fn test_array_header_dimension_overflow_is_rejected() {
        // `read_header` is public API. Its Array branch computed `nrows * ncols`
        // with plain multiplication on two untrusted values: a debug-build panic
        // and a silent wrap to a bogus `nnz` in release.
        let mtx = "%%MatrixMarket matrix array real general\n4294967296 4294967296\n";
        let mut reader = std::io::Cursor::new(mtx.as_bytes());

        match read_header(&mut reader) {
            Err(MtxError::InvalidData(msg)) => assert!(msg.contains("overflow")),
            Err(other) => panic!("expected InvalidData about overflow, got {other:?}"),
            Ok(h) => panic!("overflowing array dimensions accepted: nnz={}", h.nnz),
        }
    }

    #[test]
    fn test_array_header_sane_dimensions_still_parse() {
        let mtx = "%%MatrixMarket matrix array real general\n4 5\n";
        let mut reader = std::io::Cursor::new(mtx.as_bytes());
        let header = read_header(&mut reader).expect("sane array header");
        assert_eq!((header.nrows, header.ncols, header.nnz), (4, 5, 20));
    }
}