use crate::{
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::{
macros::impl_supplier_debug_display,
supplier::Supplier,
},
tasks::runnable::Runnable,
};
use crate::tasks::callable::BoxCallable;
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct BoxRunnable<E> {
pub(super) function: Box<dyn FnMut() -> Result<(), E> + Send>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<E> BoxRunnable<E> {
impl_common_new_methods!(
semantic_mut(Runnable<E> + Send + 'static),
|source| move || source.run(),
|function| Box::new(function),
"runnable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: Supplier<Result<(), E>> + Send + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("runnable");
#[inline]
pub fn and_then<N>(self, next: N) -> BoxRunnable<E>
where
N: Runnable<E> + Send + 'static,
E: 'static,
{
let mut function = self.function;
let mut next = next;
BoxRunnable::new(move || {
function()?;
next.run()
})
}
#[inline]
pub fn then_callable<R, C>(self, callable: C) -> BoxCallable<R, E>
where
C: crate::tasks::callable::Callable<R, E> + Send + 'static,
R: 'static,
E: 'static,
{
let mut function = self.function;
let mut callable = callable;
BoxCallable::new(move || {
function()?;
callable.call()
})
}
}
impl<E> Runnable<E> for BoxRunnable<E> {
#[inline(always)]
fn run(&mut self) -> Result<(), E> {
(self.function)()
}
}
#[cfg(feature = "once")]
impl<E> crate::suppliers::supplier_once::SupplierOnce<Result<(), E>>
for BoxRunnable<E>
{
#[inline(always)]
fn get(mut self) -> Result<(), E> {
self.run()
}
}
impl_supplier_debug_display!(BoxRunnable<E>);