Wrap code more clearly in cfg blocks

new-scheduler
Pascal Hertleif 5 years ago
parent 8ce3e78952
commit 99ddfb3f93

@ -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<T> VerboseErrorExt for Result<T, io::Error> {
impl<T> VerboseErrorExt for Result<T, std::io::Error> {
#[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()))
}
}
#[derive(Debug)]
struct VerboseError {
source: io::Error,
message: String,
}
#[cfg(feature = "verbose-errors")]
mod verbose {
use std::{error::Error as StdError, fmt, io};
impl VerboseError {
fn wrap(source: io::Error, message: impl Into<String>) -> io::Error {
io::Error::new(
source.kind(),
VerboseError {
source,
message: message.into(),
},
)
#[derive(Debug)]
pub(crate) struct Error {
source: io::Error,
message: String,
}
}
impl fmt::Display for VerboseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
impl Error {
pub(crate) fn wrap(source: io::Error, message: impl Into<String>) -> io::Error {
io::Error::new(
source.kind(),
Error {
source,
message: message.into(),
},
)
}
}
}
impl Error for VerboseError {
fn description(&self) -> &str {
self.source.description()
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
impl StdError for Error {
fn description(&self) -> &str {
self.source.description()
}
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.source)
}
}
}

@ -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.

Loading…
Cancel
Save