use crate::{Context, Error, ErrorKind, TrivialError};
mod sealed {
pub trait Sealed {}
impl<E: super::Error> Sealed for Option<E> {}
}
pub trait OptionExt: sealed::Sealed {
type Error: Error;
fn capture<E, K>(error_kind: K, option: Option<E>) -> Self
where
E: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError;
fn convert<E, K>(error_kind: K, option: Option<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<E> OptionExt for Option<E>
where
E: Error,
{
type Error = E;
#[allow(clippy::manual_map)] #[track_caller]
#[inline]
fn capture<E2, K>(error_kind: K, option: Option<E2>) -> Self
where
E2: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError,
{
match option {
Some(err) => Some(Self::Error::new(error_kind.into()).with_context(|| err)),
None => None,
}
}
#[allow(clippy::manual_map)] #[track_caller]
#[inline]
fn convert<E2, K>(error_kind: K, option: Option<E2>) -> Self
where
E2: Context,
K: ErrorKind + Into<<Self::Error as Error>::Kind>,
Self::Error: TrivialError,
{
match option {
Some(_) => Some(Self::Error::new(error_kind.into())),
None => None,
}
}
#[allow(clippy::manual_map)] #[track_caller]
#[inline]
fn with_context<C, F>(self, context: F) -> Self
where
C: Context,
F: FnOnce() -> C,
{
match self {
None => None,
Some(err) => Some(err.with_context(context)),
}
}
}