rsomics_seq/operations/
convert.rs1use std::io::Write;
2
3use clap::ValueEnum;
4use rsomics_common::{Result, RsomicsError};
5use rsomics_seqio::{Format, Record, Writer};
6use serde::Serialize;
7
8use crate::input::scan_records;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
12#[serde(rename_all = "lowercase")]
13pub enum ConvertFormat {
14 Fasta,
16 Fastq,
18}
19
20impl ConvertFormat {
21 fn seqio(self) -> Format {
22 match self {
23 Self::Fasta => Format::Fasta,
24 Self::Fastq => Format::Fastq,
25 }
26 }
27
28 fn as_str(self) -> &'static str {
29 match self {
30 Self::Fasta => "FASTA",
31 Self::Fastq => "FASTQ",
32 }
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
38pub struct ConvertReport {
39 pub input: String,
41 pub input_format: &'static str,
43 pub output_format: &'static str,
45 pub records: u64,
47}
48
49pub fn convert_sequences(
59 input: &str,
60 target: ConvertFormat,
61 output: &mut dyn Write,
62) -> Result<ConvertReport> {
63 let target_format = target.seqio();
64 let mut writer = Writer::new(output, target_format);
65 let mut records = 0u64;
66 let input_format = scan_records(input, |record| {
67 if target_format == Format::Fastq && record.qual.is_none() {
68 return Err(RsomicsError::InvalidInput(
69 "cannot convert FASTA to FASTQ without quality scores".into(),
70 ));
71 }
72 let converted = Record {
73 id: record.id,
74 seq: record.seq,
75 qual: if target_format == Format::Fastq {
76 record.qual
77 } else {
78 None
79 },
80 };
81 writer.write_record(converted)?;
82 records = records.checked_add(1).ok_or_else(|| {
83 RsomicsError::InvalidInput("record count exceeds u64 capacity".into())
84 })?;
85 Ok(())
86 })?;
87 writer.finish()?;
88
89 Ok(ConvertReport {
90 input: input.to_owned(),
91 input_format: format_name(input_format),
92 output_format: target.as_str(),
93 records,
94 })
95}
96
97fn format_name(format: Format) -> &'static str {
98 match format {
99 Format::Fasta => "FASTA",
100 Format::Fastq => "FASTQ",
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn fasta_to_fastq_never_invents_quality() {
110 let input = tempfile::NamedTempFile::new().unwrap();
111 std::fs::write(input.path(), b">one\nACGT\n").unwrap();
112 let mut output = Vec::new();
113 let error = convert_sequences(
114 input.path().to_str().unwrap(),
115 ConvertFormat::Fastq,
116 &mut output,
117 )
118 .unwrap_err();
119 assert!(error.to_string().contains("without quality"));
120 assert!(output.is_empty());
121 }
122}