use crate::{
macros::{
impl_box_once_conversions,
impl_closure_once_trait,
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::macros::impl_supplier_debug_display,
suppliers::supplier_once::SupplierOnce,
tasks::callable::BoxCallable,
};
pub trait Runnable<E> {
fn run(self) -> Result<(), E>;
fn into_box(self) -> BoxRunnable<E>
where
Self: Sized + 'static,
{
BoxRunnable::new(move || self.run())
}
fn into_fn(self) -> impl FnOnce() -> Result<(), E>
where
Self: Sized + 'static,
{
move || self.run()
}
fn to_box(&self) -> BoxRunnable<E>
where
Self: Clone + Sized + 'static,
{
self.clone().into_box()
}
fn to_fn(&self) -> impl FnOnce() -> Result<(), E>
where
Self: Clone + Sized + 'static,
{
self.clone().into_fn()
}
fn into_callable(self) -> BoxCallable<(), E>
where
Self: Sized + 'static,
{
BoxCallable::new(move || self.run())
}
}
pub struct BoxRunnable<E> {
function: Box<dyn FnOnce() -> Result<(), E>>,
name: Option<String>,
}
impl<E> BoxRunnable<E> {
impl_common_new_methods!(
(FnOnce() -> Result<(), E> + 'static),
|function| Box::new(function),
"runnable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: SupplierOnce<Result<(), E>> + '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> + 'static,
E: 'static,
{
let name = self.name;
let function = self.function;
BoxRunnable::new_with_optional_name(
move || {
function()?;
next.run()
},
name,
)
}
#[inline]
pub fn then_callable<R, C>(self, callable: C) -> BoxCallable<R, E>
where
C: crate::tasks::callable::Callable<R, E> + 'static,
R: 'static,
E: 'static,
{
let name = self.name;
let function = self.function;
BoxCallable::new_with_optional_name(
move || {
function()?;
callable.call()
},
name,
)
}
}
impl<E> Runnable<E> for BoxRunnable<E> {
#[inline]
fn run(self) -> Result<(), E> {
(self.function)()
}
impl_box_once_conversions!(BoxRunnable<E>, Runnable, FnOnce() -> Result<(), E>);
#[inline]
fn into_callable(self) -> BoxCallable<(), E>
where
Self: Sized + 'static,
{
let name = self.name;
let function = self.function;
BoxCallable::new_with_optional_name(function, name)
}
}
impl<E> SupplierOnce<Result<(), E>> for BoxRunnable<E> {
#[inline]
fn get(self) -> Result<(), E> {
self.run()
}
}
impl_closure_once_trait!(
Runnable<E>,
run,
BoxRunnable,
FnOnce() -> Result<(), E>
);
impl_supplier_debug_display!(BoxRunnable<E>);