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_once::{
BoxCallableOnce,
CallableOnce,
},
};
pub trait RunnableOnce<E> {
fn run(self) -> Result<(), E>;
fn into_box(self) -> BoxRunnableOnce<E>
where
Self: Sized + 'static,
{
BoxRunnableOnce::new(move || self.run())
}
fn into_fn(self) -> impl FnOnce() -> Result<(), E>
where
Self: Sized + 'static,
{
move || self.run()
}
fn to_box(&self) -> BoxRunnableOnce<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) -> BoxCallableOnce<(), E>
where
Self: Sized + 'static,
{
BoxCallableOnce::new(move || self.run())
}
}
pub struct BoxRunnableOnce<E> {
function: Box<dyn FnOnce() -> Result<(), E>>,
name: Option<String>,
}
impl<E> BoxRunnableOnce<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) -> BoxRunnableOnce<E>
where
N: RunnableOnce<E> + 'static,
E: 'static,
{
let name = self.name;
let function = self.function;
BoxRunnableOnce::new_with_optional_name(
move || {
function()?;
next.run()
},
name,
)
}
#[inline]
pub fn then_callable<R, C>(self, callable: C) -> BoxCallableOnce<R, E>
where
C: CallableOnce<R, E> + 'static,
R: 'static,
E: 'static,
{
let name = self.name;
let function = self.function;
BoxCallableOnce::new_with_optional_name(
move || {
function()?;
callable.call()
},
name,
)
}
}
impl<E> RunnableOnce<E> for BoxRunnableOnce<E> {
#[inline]
fn run(self) -> Result<(), E> {
(self.function)()
}
impl_box_once_conversions!(BoxRunnableOnce<E>, RunnableOnce, FnOnce() -> Result<(), E>);
#[inline]
fn into_callable(self) -> BoxCallableOnce<(), E>
where
Self: Sized + 'static,
{
let name = self.name;
let function = self.function;
BoxCallableOnce::new_with_optional_name(function, name)
}
}
impl<E> SupplierOnce<Result<(), E>> for BoxRunnableOnce<E> {
#[inline]
fn get(self) -> Result<(), E> {
self.run()
}
}
impl_closure_once_trait!(
RunnableOnce<E>,
run,
BoxRunnableOnce,
FnOnce() -> Result<(), E>
);
impl_supplier_debug_display!(BoxRunnableOnce<E>);