From 323ba0b88c2ee88de618b0b7bfca99fc2925bb3e Mon Sep 17 00:00:00 2001 From: Josh Mitchell Date: Tue, 10 Nov 2020 19:49:58 +1100 Subject: [PATCH] Clarified error message when read_num_atoms() fails during read() --- src/errors.rs | 24 +++++++++++++++++++++--- src/lib.rs | 8 ++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 55165f8..c03a07a 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -7,22 +7,35 @@ use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq)] pub enum Error { /// An error code from the C API - CApiError { code: ErrorCode, task: ErrorTask }, + CApiError { + code: ErrorCode, + task: ErrorTask, + }, /// Passed in a frame of the wrong size - WrongSizeFrame { expected: usize, found: usize }, + WrongSizeFrame { + expected: usize, + found: usize, + }, /// C API failed to open a file (No return code provided) - CouldNotOpen { path: PathBuf, mode: FileMode }, + CouldNotOpen { + path: PathBuf, + mode: FileMode, + }, /// A path could not be converted to &OsStr, probably because it is invalid unicode InvalidOsStr, /// A path could not be converted to &CStr because it had a null byte NullInStr(std::ffi::NulError), + CouldNotCheckNAtoms(Box), } impl Error { /// Get the error code returned by the C API, if any pub fn code(&self) -> Option { + use std::error::Error as _; if let Error::CApiError { code, .. } = self { Some(*code) + } else if let Some(e) = self.source() { + e.downcast_ref::().and_then(Self::code) } else { None } @@ -63,6 +76,7 @@ impl std::error::Error for Error { use Error::*; match &self { NullInStr(err) => Some(err), + CouldNotCheckNAtoms(err) => Some(err.as_ref()), _ => None, } } @@ -114,6 +128,10 @@ impl std::fmt::Display for Error { } InvalidOsStr => write!(f, "Paths must be valid unicode on this platform"), NullInStr(_err) => write!(f, "Paths cannot include null bytes"), + CouldNotCheckNAtoms(_err) => write!( + f, + "Failed to check number of atoms in trajectory while reading a frame" + ), } } } diff --git a/src/lib.rs b/src/lib.rs index 8e8eff8..66b9f99 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -202,7 +202,9 @@ impl Trajectory for XTCTrajectory { fn read(&mut self, frame: &mut Frame) -> Result<()> { let mut step: i32 = 0; - let num_atoms = self.get_num_atoms()? as usize; + let num_atoms = self + .get_num_atoms() + .map_err(|e| Error::CouldNotCheckNAtoms(Box::new(e)))? as usize; if num_atoms != frame.coords.len() { return Err(Error::from((&*frame, num_atoms))); } @@ -303,7 +305,9 @@ impl Trajectory for TRRTrajectory { let mut step: i32 = 0; let mut lambda: f32 = 0.0; - let num_atoms = self.get_num_atoms()? as usize; + let num_atoms = self + .get_num_atoms() + .map_err(|e| Error::CouldNotCheckNAtoms(Box::new(e)))? as usize; if num_atoms != frame.coords.len() { return Err(Error::from((&*frame, num_atoms))); }