rust_htslib/bcf/
index.rs

1use crate::{htslib, utils};
2
3#[derive(Debug)]
4pub struct BcfBuildError {
5    pub msg: String,
6}
7
8/// Index type to build.
9pub enum Type {
10    /// Tabix index
11    Tbx,
12    /// CSI index, with given minimum shift
13    Csi(u32),
14}
15
16impl Type {
17    fn min_shift(&self) -> i32 {
18        match self {
19            Self::Tbx => 0,
20            Self::Csi(x) => *x as i32,
21        }
22    }
23}
24
25impl BcfBuildError {
26    pub fn error_message(error: i32) -> &'static str {
27        match error {
28            -1 => "indexing failed",
29            -2 => "opening @fn failed",
30            -3 => "format not indexable",
31            -4 => "failed to create and/or save the index",
32            _ => "unknown error",
33        }
34    }
35}
36impl std::error::Error for BcfBuildError {}
37
38impl std::fmt::Display for BcfBuildError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "BcfBuildError{{msg: {}}}", self.msg)
41    }
42}
43
44/// Build a bcf or vcf.gz index.
45/// Builds tbi or csi depending on index_type.
46///
47///```
48/// // Index a sorted bcf file with csi.
49/// let bcf_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/test_multi.bcf");
50/// rust_htslib::bcf::index::build(&bcf_path, Some(&"built_test.csi"), /*n_threads=*/ 4u32, rust_htslib::bcf::index::Type::Csi(14)).expect("Failed to build csi index for bcf file.");
51/// assert!(std::path::Path::new(&"built_test.csi").exists());
52///
53/// // Index a bgzip-compresed vcf file with tabix.
54/// let vcf_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/test_left.vcf.gz");
55/// rust_htslib::bcf::index::build(&vcf_path, Some(&"built_test_vcf.tbx"), /*n_threads=*/ 4u32, rust_htslib::bcf::index::Type::Tbx).expect("Failed to build tbx index for vcf file.");
56/// assert!(std::path::Path::new(&"built_test_vcf.tbx").exists());
57///
58/// // Cannot build a tbi index for a bcf file: returns an Err(BcfBuildError).
59/// assert!(std::panic::catch_unwind(|| rust_htslib::bcf::index::build(bcf_path, Some("built_test.tbi"), 4u32, rust_htslib::bcf::index::Type::Tbx).unwrap()).is_err());
60///
61/// // Cannot built a csi index for a vcf file: returns an Err(BcfBuildError).
62/// let vcf_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/test_various.vcf");
63/// assert!(std::panic::catch_unwind(|| rust_htslib::bcf::index::build(&vcf_path, Some(&"built_test_vcf.csi"), /*n_threads=*/ 4u32, rust_htslib::bcf::index::Type::Csi(14)).expect("Failed to build csi index for vcf file.")).is_err());
64///```
65///
66pub fn build<P: AsRef<std::path::Path>>(
67    bcf_path: P,
68    idx_path: Option<P>,
69    n_threads: u32,
70    index_type: Type,
71) -> Result<(), BcfBuildError> {
72    let min_shift = index_type.min_shift();
73    let idx_path_cstr = idx_path.and_then(|x| utils::path_to_cstring(&x));
74    let bcf_path = utils::path_to_cstring(&bcf_path).ok_or(BcfBuildError {
75        msg: format!(
76            "Failed to format bcf_path to cstring: {:?}",
77            bcf_path.as_ref().display()
78        ),
79    })?;
80    let return_code = unsafe {
81        htslib::bcf_index_build3(
82            bcf_path.as_ptr(),
83            idx_path_cstr
84                .as_ref()
85                .map_or(std::ptr::null(), |p| p.as_ptr()),
86            min_shift,
87            n_threads as i32,
88        )
89    };
90    if return_code == 0 {
91        Ok(())
92    } else {
93        Err(BcfBuildError {
94            msg: format!(
95                "Failed to build  bcf index. Error: {return_code:?}/{}",
96                BcfBuildError::error_message(return_code)
97            ),
98        })
99    }
100}