use crate::{
functions::macros::impl_function_debug_display,
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
tasks::callable_with::CallableWith,
};
type BoxCallableWithFn<T, R, E> = Box<dyn FnMut(&mut T) -> Result<R, E> + Send>;
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct BoxCallableWith<T, R, E> {
pub(super) function: BoxCallableWithFn<T, R, E>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<T, R, E> BoxCallableWith<T, R, E> {
impl_common_new_methods!(
semantic_mut(CallableWith<T, R, E> + Send + 'static),
|source| move |input: &mut T| source.call_with(input),
|function| Box::new(function),
"callable-with"
);
impl_common_name_methods!("callable-with");
#[inline]
pub fn map<U, M>(self, mut mapper: M) -> BoxCallableWith<T, U, E>
where
M: FnMut(R) -> U + Send + 'static,
T: 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let mut function = self.function;
BoxCallableWith::new_with_metadata(
move |input: &mut T| function(input).map(&mut mapper),
metadata,
)
}
#[inline]
pub fn map_err<E2, M>(self, mut mapper: M) -> BoxCallableWith<T, R, E2>
where
M: FnMut(E) -> E2 + Send + 'static,
T: 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let mut function = self.function;
BoxCallableWith::new_with_metadata(
move |input: &mut T| function(input).map_err(&mut mapper),
metadata,
)
}
#[inline]
pub fn and_then<U, N>(self, next: N) -> BoxCallableWith<T, U, E>
where
N: FnMut(R, &mut T) -> Result<U, E> + Send + 'static,
T: 'static,
R: 'static,
E: 'static,
{
let mut function = self.function;
let mut next = next;
BoxCallableWith::new(move |input: &mut T| {
let value = function(&mut *input)?;
next(value, input)
})
}
}
impl<T, R, E> CallableWith<T, R, E> for BoxCallableWith<T, R, E> {
#[inline(always)]
fn call_with(&mut self, input: &mut T) -> Result<R, E> {
(self.function)(input)
}
}
impl_function_debug_display!(BoxCallableWith<T, R, E>);