#![allow(unused_imports)]
use super::*;
pub struct BoxCallable<R, E> {
pub(super) function: Box<dyn FnMut() -> Result<R, E>>,
pub(super) name: Option<String>,
}
impl<R, E> BoxCallable<R, E> {
impl_common_new_methods!(
(FnMut() -> Result<R, E> + 'static),
|function| Box::new(function),
"callable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: Supplier<Result<R, E>> + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("callable");
#[inline]
pub fn map<U, M>(self, mut mapper: M) -> BoxCallable<U, E>
where
M: FnMut(R) -> U + 'static,
R: 'static,
E: 'static,
{
let name = self.name;
let mut function = self.function;
BoxCallable::new_with_optional_name(move || function().map(&mut mapper), name)
}
#[inline]
pub fn map_err<E2, M>(self, mut mapper: M) -> BoxCallable<R, E2>
where
M: FnMut(E) -> E2 + 'static,
R: 'static,
E: 'static,
{
let name = self.name;
let mut function = self.function;
BoxCallable::new_with_optional_name(move || function().map_err(&mut mapper), name)
}
#[inline]
pub fn and_then<U, N>(self, next: N) -> BoxCallable<U, E>
where
N: FnMut(R) -> Result<U, E> + 'static,
R: 'static,
E: 'static,
{
let name = self.name;
let mut function = self.function;
let mut next = next;
BoxCallable::new_with_optional_name(
move || {
let value = function()?;
next(value)
},
name,
)
}
}
impl<R, E> Callable<R, E> for BoxCallable<R, E> {
#[inline]
fn call(&mut self) -> Result<R, E> {
(self.function)()
}
impl_box_conversions!(
BoxCallable<R, E>,
RcCallable,
FnMut() -> Result<R, E>,
BoxCallableOnce
);
#[inline]
fn into_runnable(self) -> BoxRunnable<E>
where
Self: Sized + 'static,
{
let name = self.name;
let mut function = self.function;
BoxRunnable::new_with_optional_name(move || function().map(|_| ()), name)
}
}