scirs2-io 0.4.2

Input/Output utilities module for SciRS2 (scirs2-io)
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
//! Format-specific validation utilities
//!
//! This module provides validators for specific file formats used in scientific computing.

use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;

use super::{FormatValidatorRegistry, ValidationSource};
use crate::error::{IoError, Result};

/// Common scientific data format types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataFormat {
    /// Comma-Separated Values
    CSV,
    /// Tab-Separated Values
    TSV,
    /// JavaScript Object Notation
    JSON,
    /// MATLAB .mat file
    MATLAB,
    /// Attribute-Relation File Format (ARFF)
    ARFF,
    /// HDF5 format
    HDF5,
    /// NetCDF format
    NetCDF,
    /// PNG image format
    PNG,
    /// JPEG image format
    JPEG,
    /// TIFF image format
    TIFF,
    /// WAV audio format
    WAV,
}

impl DataFormat {
    /// Get a string representation of the format
    pub fn as_str(&self) -> &'static str {
        match self {
            DataFormat::CSV => "CSV",
            DataFormat::TSV => "TSV",
            DataFormat::JSON => "JSON",
            DataFormat::MATLAB => "MATLAB",
            DataFormat::ARFF => "ARFF",
            DataFormat::HDF5 => "HDF5",
            DataFormat::NetCDF => "NetCDF",
            DataFormat::PNG => "PNG",
            DataFormat::JPEG => "JPEG",
            DataFormat::TIFF => "TIFF",
            DataFormat::WAV => "WAV",
        }
    }

    /// Parse format name from a string
    pub fn from_str(name: &str) -> Option<Self> {
        match name.to_uppercase().as_str() {
            "CSV" => Some(DataFormat::CSV),
            "TSV" => Some(DataFormat::TSV),
            "JSON" => Some(DataFormat::JSON),
            "MAT" | "MATLAB" => Some(DataFormat::MATLAB),
            "ARFF" => Some(DataFormat::ARFF),
            "HDF5" | "H5" => Some(DataFormat::HDF5),
            "NETCDF" | "NC" => Some(DataFormat::NetCDF),
            "PNG" => Some(DataFormat::PNG),
            "JPEG" | "JPG" => Some(DataFormat::JPEG),
            "TIFF" | "TIF" => Some(DataFormat::TIFF),
            "WAV" => Some(DataFormat::WAV),
            _ => None,
        }
    }
}

/// Get a registry with all scientific data format validators
#[allow(dead_code)]
pub fn get_scientific_format_validators() -> FormatValidatorRegistry {
    let mut registry = FormatValidatorRegistry::new();

    // Add format validators

    // PNG validator
    registry.add_validator("PNG", |data| {
        data.len() >= 8 && data[0..8] == [137, 80, 78, 71, 13, 10, 26, 10]
    });

    // JPEG validator
    registry.add_validator("JPEG", |data| {
        data.len() >= 3 && data[0..3] == [0xFF, 0xD8, 0xFF]
    });

    // TIFF validator
    registry.add_validator("TIFF", |data| {
        data.len() >= 4
            && (
                data[0..4] == [0x49, 0x49, 0x2A, 0x00] || // Little endian
            data[0..4] == [0x4D, 0x4D, 0x00, 0x2A]
                // Big endian
            )
    });

    // WAV validator
    registry.add_validator("WAV", |data| {
        data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WAVE"
    });

    // JSON validator
    registry.add_validator("JSON", |data| {
        if data.is_empty() {
            return false;
        }

        // Find the first non-whitespace character
        for (i, &byte) in data.iter().enumerate() {
            if !byte.is_ascii_whitespace() {
                // Check if it's { or [
                return byte == b'{' || byte == b'[' ||
                       // Or allow "key": value format in case it's a fragment
                       (byte == b'"' && data.len() > i + 2 && data[i+1..].contains(&b':'));
            }
        }

        false
    });

    // CSV validator
    registry.add_validator("CSV", |data| {
        // Basic validation: contains commas and has consistent structure
        if data.is_empty() || !data.contains(&b',') {
            return false;
        }

        // Check for newlines (files should have more than one line)
        if !data.contains(&b'\n') && !data.contains(&b'\r') {
            return false;
        }

        // Check for structure consistency by counting commas in first few lines
        let mut lines = data.split(|&b| b == b'\n');

        // Get the first line (skipping empty lines)
        let first_line = lines.find(|line| !line.is_empty()).unwrap_or(&[]);

        // Count commas in first line
        let comma_count = first_line.iter().filter(|&&b| b == b',').count();

        // Check that other lines have similar comma counts
        // (allow some variation for quoted fields)
        for line in lines.take(5) {
            if line.is_empty() {
                continue;
            }

            let line_comma_count = line.iter().filter(|&&b| b == b',').count();

            // Allow some variation, but not too much
            if (line_comma_count as isize - comma_count as isize).abs() > 2 {
                return false;
            }
        }

        true
    });

    // TSV validator
    registry.add_validator("TSV", |data| {
        // Similar to CSV but with tabs
        if data.is_empty() || !data.contains(&b'\t') {
            return false;
        }

        if !data.contains(&b'\n') && !data.contains(&b'\r') {
            return false;
        }

        // Check for structure consistency
        let mut lines = data.split(|&b| b == b'\n');

        let first_line = lines.find(|line| !line.is_empty()).unwrap_or(&[]);

        let tab_count = first_line.iter().filter(|&&b| b == b'\t').count();

        for line in lines.take(5) {
            if line.is_empty() {
                continue;
            }

            let line_tab_count = line.iter().filter(|&&b| b == b'\t').count();

            if (line_tab_count as isize - tab_count as isize).abs() > 2 {
                return false;
            }
        }

        true
    });

    // MATLAB .mat file validator
    registry.add_validator("MATLAB", |data| {
        // Check for MATLAB Level 5 MAT-file format
        if data.len() >= 128
            && (data[0..4] == [0x00, 0x01, 0x00, 0x00] || // Header for MATLAB versions < 7.3
            data[0..4] == [0x00, 0x01, 0x4D, 0x49])
        // Header for compressed MATLAB >= 7.3
        {
            // Check for "MATLAB" text in header
            return data[124..128].windows(6).any(|window| window == b"MATLAB");
        }

        false
    });

    // ARFF validator
    registry.add_validator("ARFF", |data| {
        if data.is_empty() {
            return false;
        }

        // Convert to string for easier parsing
        let mut buffer = Vec::new();
        buffer.extend_from_slice(data);

        // Try to parse as UTF-8, fall back to Latin-1
        let content = String::from_utf8(buffer).unwrap_or_else(|_| {
            // Fall back to Latin-1 encoding
            data.iter().map(|&b| b as char).collect()
        });

        // Check for ARFF header
        content.to_uppercase().contains("@RELATION")
            && content.to_uppercase().contains("@ATTRIBUTE")
            && content.to_uppercase().contains("@DATA")
    });

    // HDF5 validator
    registry.add_validator("HDF5", |data| {
        data.len() >= 8 && data[0..8] == [137, 72, 68, 70, 13, 10, 26, 10]
    });

    // NetCDF validator (basic signature check)
    registry.add_validator("NetCDF", |data| {
        data.len() >= 4 && &data[0..4] == b"CDF\x01" || &data[0..4] == b"CDF\x02"
    });

    registry
}

/// Validate a file against a specific format
#[allow(dead_code)]
pub fn validate_format<P: AsRef<Path>>(path: P, format: DataFormat) -> Result<bool> {
    let _path = path.as_ref();

    // Open file
    let file =
        File::open(_path).map_err(|e| IoError::FileError(format!("Failed to open file: {e}")))?;

    // Read first 8192 bytes for format detection
    let mut buffer = Vec::with_capacity(8192);
    file.take(8192)
        .read_to_end(&mut buffer)
        .map_err(|e| IoError::FileError(format!("Failed to read file: {e}")))?;

    // Get validators
    let registry = get_scientific_format_validators();

    // Find validator for the format
    for validator in registry.validators {
        if validator.format_name.eq_ignore_ascii_case(format.as_str()) {
            return Ok(validator.validate(&buffer));
        }
    }

    Err(IoError::ValidationError(format!(
        "No validator found for format: {}",
        format.as_str()
    )))
}

/// Detect the format of a file
#[allow(dead_code)]
pub fn detect_file_format<P: AsRef<Path>>(path: P) -> Result<Option<String>> {
    let _path = path.as_ref();

    // Use registry to validate format
    let registry = get_scientific_format_validators();
    registry.validate_format(ValidationSource::FilePath(_path))
}

/// Structure for validation result details
#[derive(Debug, Clone)]
pub struct FormatValidationResult {
    /// Whether the validation passed
    pub valid: bool,
    /// The format that was validated
    pub format: String,
    /// Path to the validated file
    pub file_path: String,
    /// Additional validation details
    pub details: Option<String>,
}

/// Perform comprehensive format validation on a file
///
/// This function performs format-specific validation beyond
/// just the basic format detection.
#[allow(dead_code)]
pub fn validate_file_format<P: AsRef<Path>>(
    path: P,
    format: DataFormat,
) -> Result<FormatValidationResult> {
    let path = path.as_ref();

    // First check basic format signature
    let basic_valid = validate_format(path, format)?;

    if !basic_valid {
        return Ok(FormatValidationResult {
            valid: false,
            format: format.as_str().to_string(),
            file_path: path.to_string_lossy().to_string(),
            details: Some("File does not have the correct format signature".to_string()),
        });
    }

    // For some formats, perform more detailed validation
    match format {
        DataFormat::CSV => validate_csv_format(path),
        DataFormat::JSON => validate_json_format(path),
        DataFormat::ARFF => validate_arff_format(path),
        DataFormat::WAV => validate_wav_format(path),
        _ => {
            // For other formats, basic validation is sufficient for now
            Ok(FormatValidationResult {
                valid: true,
                format: format.as_str().to_string(),
                file_path: path.to_string_lossy().to_string(),
                details: None,
            })
        }
    }
}

/// Validate CSV file structure in detail
#[allow(dead_code)]
fn validate_csv_format<P: AsRef<Path>>(path: P) -> Result<FormatValidationResult> {
    let _path = path.as_ref();

    // Open file
    let file =
        File::open(_path).map_err(|e| IoError::FileError(format!("Failed to open file: {e}")))?;

    let mut reader = BufReader::new(file);
    let mut content = Vec::new();
    reader
        .read_to_end(&mut content)
        .map_err(|e| IoError::FileError(format!("Failed to read file: {e}")))?;

    if content.is_empty() {
        return Ok(FormatValidationResult {
            valid: false,
            format: "CSV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some("File is empty".to_string()),
        });
    }

    // Check for consistent number of fields
    let mut lines = content
        .split(|&b| b == b'\n' || b == b'\r')
        .filter(|line| !line.is_empty());

    // Get field count from first line
    let first_line = match lines.next() {
        Some(line) => line,
        None => {
            return Ok(FormatValidationResult {
                valid: false,
                format: "CSV".to_string(),
                file_path: path.as_ref().to_string_lossy().to_string(),
                details: Some("File has no content".to_string()),
            });
        }
    };

    // Count fields in first line (accounting for quoted fields)
    let first_field_count = count_csv_fields(first_line);

    // Check remaining lines for consistency
    let mut inconsistent_lines = Vec::new();

    for (i, line) in lines.enumerate() {
        let field_count = count_csv_fields(line);
        let line_number = i + 2;

        if field_count != first_field_count {
            inconsistent_lines.push(line_number);
        }
    }

    if inconsistent_lines.is_empty() {
        Ok(FormatValidationResult {
            valid: true,
            format: "CSV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(format!(
                "CSV file with {} fields per line",
                first_field_count
            )),
        })
    } else {
        // Report up to 5 inconsistent lines
        let inconsistent_report = if inconsistent_lines.len() <= 5 {
            format!(
                "Lines with inconsistent field counts: {}",
                inconsistent_lines
                    .iter()
                    .map(|n| n.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        } else {
            format!(
                "Lines with inconsistent field counts: {} (and {} more)",
                inconsistent_lines
                    .iter()
                    .take(5)
                    .map(|n| n.to_string())
                    .collect::<Vec<_>>()
                    .join(", "),
                inconsistent_lines.len() - 5
            )
        };

        Ok(FormatValidationResult {
            valid: false,
            format: "CSV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(format!(
                "Inconsistent field counts. First line has {} fields. {}",
                first_field_count, inconsistent_report
            )),
        })
    }
}

/// Count fields in a CSV line, accounting for quoted fields
#[allow(dead_code)]
fn count_csv_fields(line: &[u8]) -> usize {
    let mut count = 1; // Start at 1 because field count = comma count + 1
    let mut in_quotes = false;

    for &b in line {
        match b {
            b'"' => {
                // Toggle quote state
                in_quotes = !in_quotes;
            }
            b','
                // Only count commas outside quotes
                if !in_quotes => {
                    count += 1;
                }
            _ => {}
        }
    }

    count
}

/// Validate JSON file structure in detail
#[allow(dead_code)]
fn validate_json_format<P: AsRef<Path>>(path: P) -> Result<FormatValidationResult> {
    let _path = path.as_ref();

    // Open and attempt to parse as JSON
    let file =
        File::open(_path).map_err(|e| IoError::FileError(format!("Failed to open file: {e}")))?;

    let reader = BufReader::new(file);

    match serde_json::from_reader::<_, serde_json::Value>(reader) {
        Ok(_) => Ok(FormatValidationResult {
            valid: true,
            format: "JSON".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some("Valid JSON structure".to_string()),
        }),
        Err(e) => Ok(FormatValidationResult {
            valid: false,
            format: "JSON".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(format!("Invalid JSON: {}", e)),
        }),
    }
}

/// Validate ARFF file structure in detail
#[allow(dead_code)]
fn validate_arff_format<P: AsRef<Path>>(path: P) -> Result<FormatValidationResult> {
    let _path = path.as_ref();

    // Open file
    let file =
        File::open(_path).map_err(|e| IoError::FileError(format!("Failed to open file: {e}")))?;

    let mut reader = BufReader::new(file);
    let mut content = String::new();
    reader
        .read_to_string(&mut content)
        .map_err(|e| IoError::FileError(format!("Failed to read file: {e}")))?;

    // Check for required sections
    let has_relation = content.to_uppercase().contains("@RELATION");
    let has_attribute = content.to_uppercase().contains("@ATTRIBUTE");
    let has_data = content.to_uppercase().contains("@DATA");

    let mut details = Vec::new();

    if !has_relation {
        details.push("Missing @RELATION section".to_string());
    }

    if !has_attribute {
        details.push("Missing @ATTRIBUTE section".to_string());
    }

    if !has_data {
        details.push("Missing @DATA section".to_string());
    }

    if details.is_empty() {
        // Count attributes
        let attribute_count = content
            .to_uppercase()
            .lines()
            .filter(|line| line.trim().starts_with("@ATTRIBUTE"))
            .count();

        Ok(FormatValidationResult {
            valid: true,
            format: "ARFF".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(format!(
                "Valid ARFF file with {} attributes",
                attribute_count
            )),
        })
    } else {
        Ok(FormatValidationResult {
            valid: false,
            format: "ARFF".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(details.join(", ")),
        })
    }
}

/// Validate WAV file structure in detail
#[allow(dead_code)]
fn validate_wav_format<P: AsRef<Path>>(path: P) -> Result<FormatValidationResult> {
    let _path = path.as_ref();

    // Open file
    let file =
        File::open(_path).map_err(|e| IoError::FileError(format!("Failed to open file: {e}")))?;

    let mut reader = BufReader::new(file);
    let mut header = [0u8; 44]; // Standard WAV header size

    // Try to read header
    if let Err(e) = reader.read_exact(&mut header) {
        return Ok(FormatValidationResult {
            valid: false,
            format: "WAV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some(format!("Failed to read WAV header: {}", e)),
        });
    }

    // Check for RIFF header
    if &header[0..4] != b"RIFF" {
        return Ok(FormatValidationResult {
            valid: false,
            format: "WAV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some("Missing RIFF header".to_string()),
        });
    }

    // Check for WAVE format
    if &header[8..12] != b"WAVE" {
        return Ok(FormatValidationResult {
            valid: false,
            format: "WAV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some("Missing WAVE format identifier".to_string()),
        });
    }

    // Check for fmt chunk
    if &header[12..16] != b"fmt " {
        return Ok(FormatValidationResult {
            valid: false,
            format: "WAV".to_string(),
            file_path: path.as_ref().to_string_lossy().to_string(),
            details: Some("Missing fmt chunk".to_string()),
        });
    }

    // Extract audio format (PCM = 1)
    let audio_format = header[20] as u16 | ((header[21] as u16) << 8);
    let channels = header[22] as u16 | ((header[23] as u16) << 8);
    let sample_rate = header[24] as u32
        | ((header[25] as u32) << 8)
        | ((header[26] as u32) << 16)
        | ((header[27] as u32) << 24);
    let bits_per_sample = header[34] as u16 | ((header[35] as u16) << 8);

    Ok(FormatValidationResult {
        valid: true,
        format: "WAV".to_string(),
        file_path: _path.to_string_lossy().to_string(),
        details: Some(format!(
            "Valid WAV file: {} channels, {}Hz, {}-bit, {}",
            channels,
            sample_rate,
            bits_per_sample,
            if audio_format == 1 { "PCM" } else { "non-PCM" }
        )),
    })
}