Skip to content

Commit

Permalink
fix: return error when bgzf_open fails to open a file
Browse files Browse the repository at this point in the history
  * Before `rust_htslib::bgzf:Reader` and `rust_htslib::bgzf:Writer`
    would never fail when opening a file that could not be opened
    and it would allow writing to `rust_htslib::bgzf:Writer` without
    returning any error messages.
  • Loading branch information
ghuls committed Oct 23, 2024
1 parent 4b3cbcb commit 51a4c91
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/bgzf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,13 @@ impl Reader {
let mode = ffi::CString::new("r").unwrap();
let cpath = ffi::CString::new(path).unwrap();
let inner = unsafe { htslib::bgzf_open(cpath.as_ptr(), mode.as_ptr()) };
Ok(Self { inner })
if inner != std::ptr::null_mut() {
Ok(Self { inner })
} else {
Err(Error::FileOpen {
path: String::from_utf8(path.to_vec()).unwrap(),
})
}
}

/// Set the thread pool to use for parallel decompression.
Expand Down Expand Up @@ -211,7 +217,13 @@ impl Writer {
let mode = Self::get_open_mode(level)?;
let cpath = ffi::CString::new(path).unwrap();
let inner = unsafe { htslib::bgzf_open(cpath.as_ptr(), mode.as_ptr()) };
Ok(Self { inner, tpool: None })
if inner != std::ptr::null_mut() {
Ok(Self { inner, tpool: None })
} else {
Err(Error::FileOpen {
path: String::from_utf8(path.to_vec()).unwrap(),
})
}
}

/// Internal function to convert compression level to "mode"
Expand Down
2 changes: 2 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub enum Error {
// General errors
#[error("file not found: {path}")]
FileNotFound { path: PathBuf },
#[error("file could not be opened: {path}")]
FileOpen { path: String },
#[error("invalid (non-unicode) characters in path")]
NonUnicodePath,
#[error("failed to fetch region")]
Expand Down

0 comments on commit 51a4c91

Please sign in to comment.