use std::ffi::OsString;
use std::fs::File;
use std::path::{Path, PathBuf};
use noodles_core::Region;
use noodles_fasta as fasta;
use rsomics_common::{Context, Result, RsomicsError};
pub(crate) struct Genome {
reader: fasta::io::IndexedReader<fasta::io::BufReader<File>>,
}
impl Genome {
pub(crate) fn open(path: &Path) -> Result<Self> {
let index_path = index_path(path);
let compressed = matches!(
path.extension().and_then(|extension| extension.to_str()),
Some("gz" | "bgz")
);
let builder = if index_path.exists() {
fasta::io::indexed_reader::Builder::default()
} else if compressed {
return Err(RsomicsError::InvalidInput(format!(
"compressed genome {} requires {} and its BGZF index",
path.display(),
index_path.display()
)));
} else {
let index = fasta::fs::index(path)
.rs_with_context(|| format!("indexing genome {}", path.display()))?;
fasta::io::indexed_reader::Builder::default().set_index(index)
};
let reader = builder
.build_from_path(path)
.rs_with_context(|| format!("opening indexed genome {}", path.display()))?;
Ok(Self { reader })
}
pub(crate) fn read_sequence(&mut self, name: &[u8]) -> Result<Vec<u8>> {
let region = Region::new(name.to_vec(), ..);
let record = self.reader.query(®ion).map_err(|error| {
RsomicsError::InvalidInput(format!(
"reading genome sequence {:?}: {error}",
String::from_utf8_lossy(name)
))
})?;
Ok(record.sequence().as_ref().to_vec())
}
}
fn index_path(path: &Path) -> PathBuf {
let mut value = OsString::from(path);
value.push(".fai");
PathBuf::from(value)
}
#[cfg(test)]
mod tests {
use std::io::Write;
use tempfile::NamedTempFile;
use super::*;
#[test]
fn builds_an_in_memory_index_when_fai_is_absent() {
let mut file = NamedTempFile::new().unwrap();
writeln!(file, ">chr1 description\nACGT\nACGT").unwrap();
file.flush().unwrap();
let mut genome = Genome::open(file.path()).unwrap();
assert_eq!(genome.read_sequence(b"chr1").unwrap(), b"ACGTACGT");
assert!(!index_path(file.path()).exists());
}
}