#[allow(unused_imports)]
pub use anyhow::{Context, Result, anyhow, bail}; use std::fmt::Display;
#[macro_export]
macro_rules! err {
() => {
anyhow!("{:?} ", (file!(), line!()))
};
($err:ident) => {
anyhow!("{:?} {}", (file!(), line!()), anyhow!($err).chain().map(|e| e.to_string()).collect::<String>())
};
($msg:literal) => {
anyhow!("{:?} {}", (file!(), line!()), $msg)
};
($fmt:literal, $($args:tt)*) => {
anyhow!("{:?} {}", (file!(), line!()), format!($fmt, $($args)*))
};
($err:ident, $($args:tt)*) => {
anyhow!("{:?} {} {}", (file!(), line!()), format!($($args)*), anyhow!($err).chain().map(|e| e.to_string()).collect::<String>())
};
($err:expr) => {
anyhow!("{:?}", $err)
};
}
pub trait Cauz<C, T> {
fn cauz(self, cause: C) -> Result<T>; }
impl<C, T, E> Cauz<C, T> for core::result::Result<T, E>
where
C: Display + Send + Sync + 'static,
E: Into<anyhow::Error>,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<T> {
(self.map_err(|e| e.into() as anyhow::Error) as anyhow::Result<_>).with_context(|| cause)
}
}
impl<C, T> Cauz<C, T> for Option<T>
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<T> {
self.with_context(|| cause)
}
}
impl<C> Cauz<C, ()> for bool
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<()> {
self.then_some(()).with_context(|| cause)
}
}
pub trait Cauz2<C, T, E> {
fn cauz2(self, cause: C, op: impl Fn(String) -> E) -> Result<T, E>; }
impl<C, T, E, E0> Cauz2<C, T, E> for core::result::Result<T, E0>
where
C: Display + Send + Sync + 'static,
E0: Into<anyhow::Error>,
{
#[inline(always)]
fn cauz2(self, cause: C, op: impl Fn(String) -> E) -> Result<T, E> {
(self.map_err(|e0| e0.into() as anyhow::Error) as anyhow::Result<_>)
.with_context(|| cause)
.map_err(|e0| op(e0.chain().map(|e0| e0.to_string()).collect::<String>()))
}
}
impl<C, T, E> Cauz2<C, T, E> for Option<T>
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz2(self, cause: C, op: impl Fn(String) -> E) -> Result<T, E> {
self.with_context(|| cause).map_err(|e0| op(e0.chain().map(|e0| e0.to_string()).collect::<String>()))
}
}
impl<C, E> Cauz2<C, (), E> for bool
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz2(self, cause: C, op: impl Fn(String) -> E) -> Result<(), E> {
self.then_some(()).with_context(|| cause).map_err(|e0| op(e0.chain().map(|e0| e0.to_string()).collect::<String>()))
}
}