From 51a4c91cffb98f303e18cb6c451c8937f9ec16e3 Mon Sep 17 00:00:00 2001 From: Gert Hulselmans Date: Wed, 23 Oct 2024 15:40:02 +0200 Subject: [PATCH] fix: return error when bgzf_open fails to open a file * 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. --- src/bgzf/mod.rs | 16 ++++++++++++++-- src/errors.rs | 2 ++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/bgzf/mod.rs b/src/bgzf/mod.rs index 06d6ee7a1..cc0a259fa 100644 --- a/src/bgzf/mod.rs +++ b/src/bgzf/mod.rs @@ -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. @@ -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" diff --git a/src/errors.rs b/src/errors.rs index 2e89854f0..1fdc8f273 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -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")]