use crate::{htslib, utils};
#[derive(Debug)]
pub struct BcfBuildError {
pub msg: String,
}
pub enum Type {
Tbx,
Csi(u32),
}
impl Type {
fn min_shift(&self) -> i32 {
match self {
Self::Tbx => 0,
Self::Csi(x) => *x as i32,
}
}
}
impl BcfBuildError {
pub fn error_message(error: i32) -> &'static str {
match error {
-1 => "indexing failed",
-2 => "opening @fn failed",
-3 => "format not indexable",
-4 => "failed to create and/or save the index",
_ => "unknown error",
}
}
}
impl std::error::Error for BcfBuildError {}
impl std::fmt::Display for BcfBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "BcfBuildError{{msg: {}}}", self.msg)
}
}
pub fn build<P: AsRef<std::path::Path>>(
bcf_path: P,
idx_path: Option<P>,
n_threads: u32,
index_type: Type,
) -> Result<(), BcfBuildError> {
let min_shift = index_type.min_shift();
let idx_path_cstr = idx_path.and_then(|x| utils::path_to_cstring(&x));
let bcf_path = utils::path_to_cstring(&bcf_path).ok_or(BcfBuildError {
msg: format!(
"Failed to format bcf_path to cstring: {:?}",
bcf_path.as_ref().display()
),
})?;
let return_code = unsafe {
htslib::bcf_index_build3(
bcf_path.as_ptr(),
idx_path_cstr
.as_ref()
.map_or(std::ptr::null(), |p| p.as_ptr()),
min_shift,
n_threads as i32,
)
};
if return_code == 0 {
Ok(())
} else {
Err(BcfBuildError {
msg: format!(
"Failed to build bcf index. Error: {return_code:?}/{}",
BcfBuildError::error_message(return_code)
),
})
}
}