#![no_std]
#![doc = env!("CARGO_PKG_DESCRIPTION")]
use core::{error::Error, fmt, iter};
pub trait ErrorExt {
fn with_source<Source>(
self,
source: Source,
) -> ErrorWithSource<Self, Source>
where
Self: Sized;
fn caused<Error>(self, error: Error) -> ErrorWithSource<Error, Self>
where
Self: Sized;
fn display_with_sources<I>(&self, infix: I) -> DisplayWithSources<&Self, I>
where
Self: Sized;
}
impl<This> ErrorExt for This
where
This: Error,
{
fn with_source<Source>(
self,
source: Source,
) -> ErrorWithSource<Self, Source>
where
Self: Sized,
{
ErrorWithSource {
this: self,
source,
}
}
fn caused<Error>(self, error: Error) -> ErrorWithSource<Error, Self>
where
Self: Sized,
{
ErrorWithSource {
this: error,
source: self,
}
}
fn display_with_sources<I>(&self, infix: I) -> DisplayWithSources<&Self, I>
where
Self: Sized,
{
DisplayWithSources {
error: self,
infix,
}
}
}
pub struct DisplayWithSources<E, I> {
pub error: E,
pub infix: I,
}
impl<E, I> fmt::Display for DisplayWithSources<E, I>
where
E: Error,
I: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.error)?;
let mut source = self.error.source();
source
.into_iter()
.chain(iter::from_fn(|| {
source = source.and_then(Error::source);
source
}))
.try_for_each(|source| write!(f, "{}{source}", self.infix))
}
}
#[derive(Debug)]
pub struct ErrorWithSource<This, Source> {
pub this: This,
pub source: Source,
}
impl<This, Source> Error for ErrorWithSource<This, Source>
where
This: fmt::Display + fmt::Debug,
Source: Error + 'static,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
fn cause(&self) -> Option<&dyn Error> {
Some(&self.source)
}
}
impl<This, Source> fmt::Display for ErrorWithSource<This, Source>
where
This: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.this.fmt(f)
}
}