use std::path::Path;
use noodles_bcf as bcf;
use noodles_bgzf as bgzf;
use noodles_vcf as vcf;
use tokio::{
fs::File,
io::{self, AsyncBufReadExt, AsyncRead, BufReader},
};
use super::Reader;
use crate::variant::io::{CompressionMethod, Format};
#[derive(Default)]
pub struct Builder {
compression_method: Option<Option<CompressionMethod>>,
format: Option<Format>,
}
impl Builder {
pub fn set_compression_method(mut self, compression: Option<CompressionMethod>) -> Self {
self.compression_method = Some(compression);
self
}
pub fn set_format(mut self, format: Format) -> Self {
self.format = Some(format);
self
}
pub async fn build_from_path<P>(self, src: P) -> io::Result<Reader<File>>
where
P: AsRef<Path>,
{
let file = File::open(src).await?;
self.build_from_reader(file).await
}
pub async fn build_from_reader<R>(self, reader: R) -> io::Result<Reader<R>>
where
R: AsyncRead + Unpin,
{
use super::Inner;
use crate::variant::io::reader::builder::{detect_compression_method, detect_format};
let mut reader = BufReader::new(reader);
let compression_method = match self.compression_method {
Some(compression_method) => compression_method,
None => {
let mut src = reader.fill_buf().await?;
detect_compression_method(&mut src)?
}
};
let format = match self.format {
Some(format) => format,
None => {
let mut src = reader.fill_buf().await?;
detect_format(&mut src, compression_method)?
}
};
let inner = match (format, compression_method) {
(Format::Vcf, None) => Inner::Vcf(vcf::r#async::io::Reader::new(reader)),
(Format::Vcf, Some(CompressionMethod::Bgzf)) => Inner::VcfGz(
vcf::r#async::io::Reader::new(bgzf::r#async::io::Reader::new(reader)),
),
(Format::Bcf, None) => Inner::BcfRaw(bcf::r#async::io::Reader::from(reader)),
(Format::Bcf, Some(CompressionMethod::Bgzf)) => {
Inner::Bcf(bcf::r#async::io::Reader::new(reader))
}
};
Ok(Reader(inner))
}
}