diff --git a/src/io/utils.rs b/src/io/utils.rs index ba6285f..ebd2214 100644 --- a/src/io/utils.rs +++ b/src/io/utils.rs @@ -1,4 +1,3 @@ -use std::{error::Error, fmt, io}; use crate::utils::VerboseErrorExt; /// Wrap `std::io::Error` with additional message @@ -6,46 +5,48 @@ use crate::utils::VerboseErrorExt; /// *Note* Only active when `verbose-errors` feature is enabled for this crate! /// /// Keeps the original error kind and stores the original I/O error as `source`. -impl VerboseErrorExt for Result { +impl VerboseErrorExt for Result { + #[cfg(feature = "verbose-errors")] fn verbose_context(self, message: impl Fn() -> String) -> Self { - if cfg!(feature = "verbose-errors") { - self.map_err(|e| VerboseError::wrap(e, message())) - } else { - self + self.map_err(|e| verbose::Error::wrap(e, message())) + } +} + +#[cfg(feature = "verbose-errors")] +mod verbose { + use std::{error::Error as StdError, fmt, io}; + + #[derive(Debug)] + pub(crate) struct Error { + source: io::Error, + message: String, + } + + impl Error { + pub(crate) fn wrap(source: io::Error, message: impl Into) -> io::Error { + io::Error::new( + source.kind(), + Error { + source, + message: message.into(), + }, + ) + } + } + + impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.message) + } + } + + impl StdError for Error { + fn description(&self) -> &str { + self.source.description() + } + + fn source(&self) -> Option<&(dyn StdError + 'static)> { + Some(&self.source) } } } - -#[derive(Debug)] -struct VerboseError { - source: io::Error, - message: String, -} - -impl VerboseError { - fn wrap(source: io::Error, message: impl Into) -> io::Error { - io::Error::new( - source.kind(), - VerboseError { - source, - message: message.into(), - }, - ) - } -} - -impl fmt::Display for VerboseError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.message) - } -} - -impl Error for VerboseError { - fn description(&self) -> &str { - self.source.description() - } - - fn source(&self) -> Option<&(dyn Error + 'static)> { - Some(&self.source) - } -} diff --git a/src/utils.rs b/src/utils.rs index 00dc793..ce4a85c 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -56,8 +56,14 @@ pub fn random(n: u32) -> u32 { /// /// *Note for implementors:* The given closure must only be executed when /// `verbose-errors` feature is enabled for this crate! -pub(crate) trait VerboseErrorExt { +pub(crate) trait VerboseErrorExt: Sized { + #[cfg(feature = "verbose-errors")] fn verbose_context(self, message: impl Fn() -> String) -> Self; + + #[cfg(not(feature = "verbose-errors"))] + fn verbose_context(self, _: impl Fn() -> String) -> Self { + self + } } /// Defers evaluation of a block of code until the end of the scope.