From 4a99b4e0b040bde7616c4216fe6c22ea6f7fdff4 Mon Sep 17 00:00:00 2001 From: Josh Mitchell Date: Tue, 10 Nov 2020 17:51:41 +1100 Subject: [PATCH] Cleaned up errors a bit --- src/errors.rs | 87 +++++++++++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 38 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 2115bb3..e1dfd04 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -18,7 +18,7 @@ pub enum ErrorTask { Flush, /// A path was being converted to a CString ToCString, - /// Unknown task + /// Placeholder until a task can be provided UnknownTask, } @@ -74,12 +74,23 @@ impl Error { } } + /// Change the task of the error + /// + /// Unless the current task is `UnknownTask`, the current error will be + /// set as the source pub fn with_task(self, task: ErrorTask) -> Self { - Self { - kind: self.kind.clone(), - task, - source: Some(Box::new(self)), - } + let kind; + let source; + + if let ErrorTask::UnknownTask = self.task { + kind = self.kind; + source = None + } else { + kind = self.kind.clone(); + source = Some(Box::new(self)) + }; + + Self { kind, task, source } } /// Convert an error code and output value from a C call to a Result @@ -112,38 +123,6 @@ impl> From for Error { } } -impl From for ErrorKind { - fn from(err: std::ffi::NulError) -> Self { - Self::NullInStr(err) - } -} - -impl From<(&Path, FileMode)> for ErrorKind { - fn from(value: (&Path, FileMode)) -> Self { - let (path, mode) = value; - ErrorKind::CouldNotOpen { - path: path.to_owned(), - mode, - } - } -} - -impl From<(&Frame, usize)> for ErrorKind { - fn from(value: (&Frame, usize)) -> Self { - let (frame, num_atoms) = value; - ErrorKind::WrongSizeFrame { - expected: num_atoms, - found: frame.coords.len(), - } - } -} - -impl From for ErrorKind { - fn from(code: ErrorCode) -> Self { - ErrorKind::ErrorCode(code) - } -} - impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{task}: {kind}", task = self.task, kind = self.kind) @@ -178,6 +157,38 @@ pub enum ErrorKind { NullInStr(std::ffi::NulError), } +impl From for ErrorKind { + fn from(err: std::ffi::NulError) -> Self { + Self::NullInStr(err) + } +} + +impl From<(&Path, FileMode)> for ErrorKind { + fn from(value: (&Path, FileMode)) -> Self { + let (path, mode) = value; + ErrorKind::CouldNotOpen { + path: path.to_owned(), + mode, + } + } +} + +impl From<(&Frame, usize)> for ErrorKind { + fn from(value: (&Frame, usize)) -> Self { + let (frame, num_atoms) = value; + ErrorKind::WrongSizeFrame { + expected: num_atoms, + found: frame.coords.len(), + } + } +} + +impl From for ErrorKind { + fn from(code: ErrorCode) -> Self { + ErrorKind::ErrorCode(code) + } +} + impl std::fmt::Display for ErrorKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use ErrorKind::*;