Skip to main content

rsomics_seq/operations/
validate.rs

1use std::io::Write;
2
3use rsomics_common::{Result, RsomicsError};
4use rsomics_seqio::Format;
5use serde::Serialize;
6
7use crate::input::scan_records;
8
9/// Successful result of a strict complete-stream validation.
10#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
11pub struct ValidationReport {
12    /// Input path as supplied by the caller, or `-` for stdin.
13    pub input: String,
14    /// Detected input format.
15    pub format: &'static str,
16    /// Number of records scanned.
17    pub records: u64,
18    /// Stable validity marker. Parser errors return an error instead.
19    pub valid: bool,
20}
21
22/// Strictly parses every FASTA/FASTQ record in one stream.
23///
24/// # Errors
25///
26/// Returns the first format, decompression, I/O, or count-overflow error.
27pub fn validate_sequences(input: &str) -> Result<ValidationReport> {
28    let mut records = 0u64;
29    let format = scan_records(input, |_| {
30        records = records.checked_add(1).ok_or_else(|| {
31            RsomicsError::InvalidInput("record count exceeds u64 capacity".into())
32        })?;
33        Ok(())
34    })?;
35    Ok(ValidationReport {
36        input: input.to_owned(),
37        format: match format {
38            Format::Fasta => "FASTA",
39            Format::Fastq => "FASTQ",
40        },
41        records,
42        valid: true,
43    })
44}
45
46/// Writes the stable validation TSV report.
47///
48/// # Errors
49///
50/// Returns an I/O error if the report cannot be written or flushed.
51pub fn write_validation_tsv(report: &ValidationReport, output: &mut dyn Write) -> Result<()> {
52    writeln!(output, "input\tformat\trecords\tvalid").map_err(RsomicsError::Io)?;
53    writeln!(
54        output,
55        "{}\t{}\t{}\t{}",
56        report.input, report.format, report.records, report.valid
57    )
58    .map_err(RsomicsError::Io)?;
59    output.flush().map_err(RsomicsError::Io)
60}