use crate::{
functions::macros::impl_function_debug_display,
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::supplier::Supplier,
tasks::callable::Callable,
};
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct LocalBoxCallable<R, E> {
pub(super) function: Box<dyn FnMut() -> Result<R, E>>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<R, E> LocalBoxCallable<R, E> {
impl_common_new_methods!(
semantic_mut(Callable<R, E> + 'static),
|source| move || source.call(),
|function| Box::new(function),
"local 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!("local callable");
#[inline]
pub fn map<U, M>(self, mut mapper: M) -> LocalBoxCallable<U, E>
where
M: FnMut(R) -> U + 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let mut function = self.function;
LocalBoxCallable::new_with_metadata(
move || function().map(&mut mapper),
metadata,
)
}
#[inline]
pub fn map_err<E2, M>(self, mut mapper: M) -> LocalBoxCallable<R, E2>
where
M: FnMut(E) -> E2 + 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let mut function = self.function;
LocalBoxCallable::new_with_metadata(
move || function().map_err(&mut mapper),
metadata,
)
}
#[inline]
pub fn and_then<U, N>(self, mut next: N) -> LocalBoxCallable<U, E>
where
N: FnMut(R) -> Result<U, E> + 'static,
R: 'static,
E: 'static,
{
let mut function = self.function;
LocalBoxCallable::new(move || {
let value = function()?;
next(value)
})
}
}
impl<R, E> Callable<R, E> for LocalBoxCallable<R, E> {
#[inline(always)]
fn call(&mut self) -> Result<R, E> {
(self.function)()
}
}
impl_function_debug_display!(LocalBoxCallable<R, E>);