#![deny(clippy::all)]
#![deny(clippy::integer_arithmetic)]
#![allow(clippy::needless_doctest_main)]
#![deny(missing_docs)]
use std::any::TypeId;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Result};
use std::panic::Location;
pub mod prelude {
pub mod v1 {
pub use super::super::ChainErrorDown as _;
pub use super::super::ResultTrait as _;
pub use super::super::{ChainError, ChainResult};
pub use crate::{derive_err_kind, derive_str_context};
}
}
pub struct ChainError<T> {
occurrence: Option<String>,
kind: T,
error_cause: Option<Box<dyn Error + 'static + Send + Sync>>,
}
pub type ChainResult<O, E> = std::result::Result<O, ChainError<E>>;
impl<T: 'static + Display + Debug> ChainError<T> {
#[inline]
pub fn new(
kind: T,
error_cause: Option<Box<dyn Error + 'static + Send + Sync>>,
occurrence: Option<String>,
) -> Self {
Self {
occurrence,
kind,
error_cause,
}
}
pub fn root_cause(&self) -> Option<&(dyn Error + 'static)> {
self.iter().last()
}
#[inline]
pub fn find_cause<U: Error + 'static>(&self) -> Option<&U> {
self.iter().filter_map(Error::downcast_ref::<U>).next()
}
#[inline]
pub fn find_chain_cause<U: Error + 'static>(&self) -> Option<&ChainError<U>> {
self.iter()
.filter_map(Error::downcast_ref::<ChainError<U>>)
.next()
}
#[inline]
pub fn find_kind_or_cause<U: Error + 'static>(&self) -> Option<&U> {
self.iter()
.filter_map(|e| {
e.downcast_ref::<ChainError<U>>()
.map(|e| e.kind())
.or_else(|| e.downcast_ref::<U>())
})
.next()
}
#[inline]
pub fn kind(&self) -> &T {
&self.kind
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &(dyn Error + 'static)> {
ErrorIter {
current: Some(self),
}
}
}
pub trait ResultTrait<O, E: Into<Box<dyn Error + 'static + Send + Sync>>> {
fn context<T: 'static + Display + Debug>(
self,
kind: T,
) -> std::result::Result<O, ChainError<T>>;
fn map_context<T: 'static + Display + Debug, F: FnOnce(&E) -> T>(
self,
op: F,
) -> std::result::Result<O, ChainError<T>>;
}
impl<O, E: Into<Box<dyn Error + 'static + Send + Sync>>> ResultTrait<O, E>
for std::result::Result<O, E>
{
#[track_caller]
fn context<T: 'static + Display + Debug>(
self,
kind: T,
) -> std::result::Result<O, ChainError<T>> {
match self {
Ok(t) => Ok(t),
Err(error_cause) => Err(ChainError::new(
kind,
Some(error_cause.into()),
Some(Location::caller().to_string()),
)),
}
}
#[track_caller]
fn map_context<T: 'static + Display + Debug, F: FnOnce(&E) -> T>(
self,
op: F,
) -> std::result::Result<O, ChainError<T>> {
match self {
Ok(t) => Ok(t),
Err(error_cause) => {
let kind = op(&error_cause);
Err(ChainError::new(
kind,
Some(error_cause.into()),
Some(Location::caller().to_string()),
))
}
}
}
}
pub struct ErrorIter<'a> {
current: Option<&'a (dyn Error + 'static)>,
}
impl<'a> Iterator for ErrorIter<'a> {
type Item = &'a (dyn Error + 'static);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let current = self.current;
self.current = self.current.and_then(Error::source);
current
}
}
impl<T: 'static + Display + Debug> std::ops::Deref for ChainError<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.kind
}
}
pub trait ChainErrorDown {
fn is_chain<T: 'static + Display + Debug>(&self) -> bool;
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>>;
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>>;
fn downcast_inner_ref<T: 'static + Error>(&self) -> Option<&T>;
fn downcast_inner_mut<T: 'static + Error>(&mut self) -> Option<&mut T>;
}
impl<U: 'static + Display + Debug> ChainErrorDown for ChainError<U> {
#[inline]
fn is_chain<T: 'static + Display + Debug>(&self) -> bool {
TypeId::of::<T>() == TypeId::of::<U>()
}
#[inline]
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>> {
if self.is_chain::<T>() {
#[allow(clippy::cast_ptr_alignment)]
unsafe {
#[allow(trivial_casts)]
Some(&*(self as *const dyn Error as *const &ChainError<T>))
}
} else {
None
}
}
#[inline]
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>> {
if self.is_chain::<T>() {
#[allow(clippy::cast_ptr_alignment)]
unsafe {
#[allow(trivial_casts)]
Some(&mut *(self as *mut dyn Error as *mut &mut ChainError<T>))
}
} else {
None
}
}
#[inline]
fn downcast_inner_ref<T: 'static + Error>(&self) -> Option<&T> {
if self.is_chain::<T>() {
#[allow(clippy::cast_ptr_alignment)]
unsafe {
#[allow(trivial_casts)]
Some(&(*(self as *const dyn Error as *const &ChainError<T>)).kind)
}
} else {
None
}
}
#[inline]
fn downcast_inner_mut<T: 'static + Error>(&mut self) -> Option<&mut T> {
if self.is_chain::<T>() {
#[allow(clippy::cast_ptr_alignment)]
unsafe {
#[allow(trivial_casts)]
Some(&mut (*(self as *mut dyn Error as *mut &mut ChainError<T>)).kind)
}
} else {
None
}
}
}
impl ChainErrorDown for dyn Error + 'static {
#[inline]
fn is_chain<T: 'static + Display + Debug>(&self) -> bool {
self.is::<ChainError<T>>()
}
#[inline]
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>> {
self.downcast_ref::<ChainError<T>>()
}
#[inline]
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>> {
self.downcast_mut::<ChainError<T>>()
}
#[inline]
fn downcast_inner_ref<T: 'static + Error>(&self) -> Option<&T> {
self.downcast_ref::<T>()
.or_else(|| self.downcast_ref::<ChainError<T>>().map(|e| e.kind()))
}
#[inline]
fn downcast_inner_mut<T: 'static + Error>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
return self.downcast_mut::<T>();
}
self.downcast_mut::<ChainError<T>>()
.and_then(|e| e.downcast_inner_mut::<T>())
}
}
impl ChainErrorDown for dyn Error + 'static + Send {
#[inline]
fn is_chain<T: 'static + Display + Debug>(&self) -> bool {
self.is::<ChainError<T>>()
}
#[inline]
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>> {
self.downcast_ref::<ChainError<T>>()
}
#[inline]
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>> {
self.downcast_mut::<ChainError<T>>()
}
#[inline]
fn downcast_inner_ref<T: 'static + Error>(&self) -> Option<&T> {
self.downcast_ref::<T>()
.or_else(|| self.downcast_ref::<ChainError<T>>().map(|e| e.kind()))
}
#[inline]
fn downcast_inner_mut<T: 'static + Error>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
return self.downcast_mut::<T>();
}
self.downcast_mut::<ChainError<T>>()
.and_then(|e| e.downcast_inner_mut::<T>())
}
}
impl ChainErrorDown for dyn Error + 'static + Send + Sync {
#[inline]
fn is_chain<T: 'static + Display + Debug>(&self) -> bool {
self.is::<ChainError<T>>()
}
#[inline]
fn downcast_chain_ref<T: 'static + Display + Debug>(&self) -> Option<&ChainError<T>> {
self.downcast_ref::<ChainError<T>>()
}
#[inline]
fn downcast_chain_mut<T: 'static + Display + Debug>(&mut self) -> Option<&mut ChainError<T>> {
self.downcast_mut::<ChainError<T>>()
}
#[inline]
fn downcast_inner_ref<T: 'static + Error>(&self) -> Option<&T> {
self.downcast_ref::<T>()
.or_else(|| self.downcast_ref::<ChainError<T>>().map(|e| e.kind()))
}
#[inline]
fn downcast_inner_mut<T: 'static + Error>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
return self.downcast_mut::<T>();
}
self.downcast_mut::<ChainError<T>>()
.and_then(|e| e.downcast_inner_mut::<T>())
}
}
impl<T: 'static + Display + Debug> Error for ChainError<T> {
#[inline]
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.error_cause
.as_ref()
.map(|e| e.as_ref() as &(dyn Error + 'static))
}
}
impl<T: 'static + Display + Debug> Error for &mut ChainError<T> {
#[inline]
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.error_cause
.as_ref()
.map(|e| e.as_ref() as &(dyn Error + 'static))
}
}
impl<T: 'static + Display + Debug> Display for ChainError<T> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{}", self.kind)?;
#[cfg(feature = "display-cause")]
{
if let Some(e) = self.source() {
writeln!(f, "\nCaused by:")?;
Display::fmt(&e, f)?;
}
}
Ok(())
}
}
impl<T: 'static + Display + Debug> Debug for ChainError<T> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
if f.alternate() {
let mut f = f.debug_struct(&format!("ChainError<{}>", std::any::type_name::<T>()));
let f = f
.field("occurrence", &self.occurrence)
.field("kind", &self.kind)
.field("source", &self.source());
f.finish()
} else {
if let Some(ref o) = self.occurrence {
write!(f, "{}: ", o)?;
}
if TypeId::of::<String>() == TypeId::of::<T>()
|| TypeId::of::<&str>() == TypeId::of::<T>()
{
Display::fmt(&self.kind, f)?;
} else {
Debug::fmt(&self.kind, f)?;
}
if let Some(e) = self.source() {
writeln!(f, "\nCaused by:")?;
Debug::fmt(&e, f)?;
}
Ok(())
}
}
}
pub trait ChainErrorFrom<T>: Sized {
fn chain_error_from(from: T, line_filename: Option<String>) -> ChainError<Self>;
}
pub trait IntoChainError<T>: Sized {
fn into_chain_error(self, line_filename: Option<String>) -> ChainError<T>;
}
impl<T, U> IntoChainError<U> for T
where
U: ChainErrorFrom<T>,
{
#[inline]
fn into_chain_error(self, line_filename: Option<String>) -> ChainError<U> {
U::chain_error_from(self, line_filename)
}
}
impl<T, U> ChainErrorFrom<T> for U
where
T: Into<U>,
U: 'static + Display + Debug,
{
#[inline]
fn chain_error_from(t: T, line_filename: Option<String>) -> ChainError<Self> {
let e: U = t.into();
ChainError::new(e, None, line_filename)
}
}
#[macro_export]
macro_rules! derive_str_context {
($e:ident) => {
#[derive(Clone)]
pub struct $e(pub String);
impl ::std::fmt::Display for $e {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl ::std::fmt::Debug for $e {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}({})", stringify!($e), self.0)
}
}
impl ::std::error::Error for $e {}
};
}
#[macro_export]
macro_rules! derive_err_kind {
($e:ident, $k:ident) => {
pub struct $e($crate::ChainError<$k>);
impl $e {
pub fn kind(&self) -> &$k {
self.0.kind()
}
}
impl From<$k> for $e {
fn from(e: $k) -> Self {
$e($crate::ChainError::new(e, None, None))
}
}
impl From<ChainError<$k>> for $e {
fn from(e: $crate::ChainError<$k>) -> Self {
$e(e)
}
}
impl From<&$e> for $k
where
$k: Clone,
{
fn from(e: &$e) -> Self {
e.kind().clone()
}
}
impl std::error::Error for $e {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.0.source()
}
}
impl std::fmt::Display for $e {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl std::fmt::Debug for $e {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.0, f)
}
}
};
}