use core::fmt::Display;
use crate::error::{Error, Result};
pub trait Context<T> {
fn context(self, ctx: impl Display) -> Result<T>;
fn with_context<F, D>(self, f: F) -> Result<T>
where
F: FnOnce() -> D,
D: Display;
}
impl<T, E: Display> Context<T> for core::result::Result<T, E> {
fn context(self, ctx: impl Display) -> Result<T> {
self.map_err(|e| Error::action(format!("{ctx}: {e}")))
}
fn with_context<F, D>(self, f: F) -> Result<T>
where
F: FnOnce() -> D,
D: Display,
{
self.map_err(|e| Error::action(format!("{}: {e}", f())))
}
}
impl<T> Context<T> for Option<T> {
fn context(self, ctx: impl Display) -> Result<T> {
self.ok_or_else(|| Error::action(ctx.to_string()))
}
fn with_context<F, D>(self, f: F) -> Result<T>
where
F: FnOnce() -> D,
D: Display,
{
self.ok_or_else(|| Error::action(f().to_string()))
}
}