pub trait ResultExt<A, E> {
fn then<F, B>(self, f: F) -> Result<B, E>
where
F: FnOnce() -> Result<B, E>;
fn remap<F, B>(self, f: F) -> Result<B, E>
where
Self: Sized,
F: FnOnce() -> B,
{
self.then(|| f().into_ok())
}
fn void(self) -> Result<(), E>
where
Self: Sized,
{
self.remap(|| ())
}
fn then_err<F, H>(self, f: F) -> Result<A, H>
where
F: FnOnce() -> Result<A, H>;
fn remap_err<F, H>(self, f: F) -> Result<A, H>
where
Self: Sized,
F: FnOnce() -> H,
{
self.then_err(|| f().into_err())
}
#[allow(clippy::result_unit_err)]
fn void_err(self) -> Result<A, ()>
where
Self: Sized,
{
self.remap_err(|| ())
}
fn inspect<F>(self, f: F) -> Result<A, E>
where
F: FnOnce(&A);
fn inspect_err<F>(self, f: F) -> Result<A, E>
where
F: FnOnce(&E);
fn swap(self) -> Result<E, A>;
fn recover<F>(self, f: F) -> Result<A, E>
where
F: FnOnce(E) -> A,
Self: Sized,
{
self.recover_with(|e| f(e).into_ok())
}
fn recover_with<F, H>(self, f: F) -> Result<A, H>
where
F: FnOnce(E) -> Result<A, H>;
}
impl<A, E> ResultExt<A, E> for Result<A, E> {
fn then<F, B>(self, f: F) -> Result<B, E>
where
F: FnOnce() -> Result<B, E>,
{
self.and_then(|_| f())
}
fn then_err<F, H>(self, f: F) -> Result<A, H>
where
F: FnOnce() -> Result<A, H>,
{
self.or_else(|_| f())
}
fn inspect<F>(self, f: F) -> Result<A, E>
where
F: FnOnce(&A),
{
self.map(|a| {
f(&a);
a
})
}
fn inspect_err<F>(self, f: F) -> Result<A, E>
where
F: FnOnce(&E),
{
self.map_err(|e| {
f(&e);
e
})
}
fn swap(self) -> Result<E, A> {
match self {
Ok(o) => Err(o),
Err(e) => Ok(e),
}
}
fn recover_with<F, H>(self, f: F) -> Result<A, H>
where
F: FnOnce(E) -> Result<A, H>,
{
self.map_or_else(f, A::into_ok)
}
}
pub trait Merge<T> {
fn merge(self) -> T;
}
impl<A, E, T> Merge<T> for Result<A, E>
where
T: From<A> + From<E>,
{
fn merge(self) -> T {
self.map_or_else(T::from, T::from)
}
}
pub trait IntoOk<O> {
fn into_ok<E>(self) -> Result<O, E>;
}
impl<O> IntoOk<O> for O {
fn into_ok<E>(self) -> Result<O, E> {
Ok(self)
}
}
pub trait IntoErr<E> {
fn into_err<O>(self) -> Result<O, E>;
}
impl<E> IntoErr<E> for E {
fn into_err<O>(self) -> Result<O, E> {
Err(self)
}
}