use crate::{Context, Error, ErrorKind, TrivialError};
mod sealed {
pub trait Sealed {}
impl<T, E: super::Error> Sealed for Result<T, E> {}
}
pub trait ResultExt: sealed::Sealed {
type Error: Error;
type Result: Sized;
fn capture<E, K>(error_kind: K, result: Result<Self::Result, E>) -> Self
where
E: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError;
fn convert<E, K>(error_kind: K, result: Result<Self::Result, E>) -> Self
where
E: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError;
fn with_context<C, F>(self, context: F) -> Self
where
C: Context,
F: FnOnce() -> C;
}
impl<T, E> ResultExt for Result<T, E>
where
E: Error,
{
type Error = E;
type Result = T;
#[track_caller]
#[inline]
fn capture<E2, K>(error_kind: K, result: Result<Self::Result, E2>) -> Self
where
E2: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError,
{
match result {
Ok(value) => Ok(value),
Err(err) => Err(Self::Error::new(error_kind.into()).with_context(|| err)),
}
}
#[track_caller]
#[inline]
fn convert<E2, K>(error_kind: K, result: Result<Self::Result, E2>) -> Self
where
E2: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError,
{
match result {
Ok(value) => Ok(value),
Err(_) => Err(Self::Error::new(error_kind.into())),
}
}
#[track_caller]
#[inline]
fn with_context<C, F>(self, context: F) -> Self
where
C: Context,
F: FnOnce() -> C,
{
match self {
Ok(value) => Ok(value),
Err(err) => Err(err.with_context(context)),
}
}
}