use std::error::Error;
pub type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
pub trait Context<T> {
fn context(self, msg: impl std::fmt::Display) -> Result<T>;
fn with_context<F, M>(self, f: F) -> Result<T>
where
F: FnOnce() -> M,
M: std::fmt::Display;
}
impl<T, E: std::fmt::Display> Context<T> for std::result::Result<T, E> {
fn context(self, msg: impl std::fmt::Display) -> Result<T> {
self.map_err(|e| format!("{msg}: {e}").into())
}
fn with_context<F, M>(self, f: F) -> Result<T>
where
F: FnOnce() -> M,
M: std::fmt::Display,
{
self.map_err(|e| format!("{}: {e}", f()).into())
}
}
impl<T> Context<T> for Option<T> {
fn context(self, msg: impl std::fmt::Display) -> Result<T> {
self.ok_or_else(|| format!("{msg}").into())
}
fn with_context<F, M>(self, f: F) -> Result<T>
where
F: FnOnce() -> M,
M: std::fmt::Display,
{
self.ok_or_else(|| format!("{}", f()).into())
}
}