use crate::{
functions::macros::impl_function_debug_display,
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::supplier_once::SupplierOnce,
tasks::callable_once::CallableOnce,
};
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct BoxCallableOnce<R, E> {
pub(super) function: Box<dyn FnOnce() -> Result<R, E> + Send>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<R, E> BoxCallableOnce<R, E> {
impl_common_new_methods!(
semantic(CallableOnce<R, E> + Send + 'static),
|source| move || source.call_once(),
|function| Box::new(function),
"callable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: SupplierOnce<Result<R, E>> + Send + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("callable");
#[inline]
pub fn map<U, M>(self, mapper: M) -> BoxCallableOnce<U, E>
where
M: FnOnce(R) -> U + Send + 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let function = self.function;
BoxCallableOnce::new_with_metadata(
move || function().map(mapper),
metadata,
)
}
#[inline]
pub fn map_err<E2, M>(self, mapper: M) -> BoxCallableOnce<R, E2>
where
M: FnOnce(E) -> E2 + Send + 'static,
R: 'static,
E: 'static,
{
let metadata = self.metadata;
let function = self.function;
BoxCallableOnce::new_with_metadata(
move || function().map_err(mapper),
metadata,
)
}
#[inline]
pub fn and_then<U, N>(self, next: N) -> BoxCallableOnce<U, E>
where
N: FnOnce(R) -> Result<U, E> + Send + 'static,
R: 'static,
E: 'static,
{
let function = self.function;
BoxCallableOnce::new(move || function().and_then(next))
}
}
impl<R, E> CallableOnce<R, E> for BoxCallableOnce<R, E> {
#[inline(always)]
fn call_once(self) -> Result<R, E> {
(self.function)()
}
}
impl<R, E> SupplierOnce<Result<R, E>> for BoxCallableOnce<R, E> {
#[inline(always)]
fn get(self) -> Result<R, E> {
self.call_once()
}
}
impl_function_debug_display!(BoxCallableOnce<R, E>);