use std::sync::Arc;
use parking_lot::Mutex;
use crate::{
macros::{
impl_arc_conversions,
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::{
macros::impl_supplier_debug_display,
supplier::Supplier,
},
tasks::runnable::{
BoxRunnable,
RcRunnable,
Runnable,
},
};
pub struct ArcRunnable<E> {
pub(super) function: Arc<Mutex<dyn FnMut() -> Result<(), E> + Send>>,
pub(super) name: Option<String>,
}
impl<E> Clone for ArcRunnable<E> {
#[inline]
fn clone(&self) -> Self {
Self {
function: Arc::clone(&self.function),
name: self.name.clone(),
}
}
}
impl<E> ArcRunnable<E> {
impl_common_new_methods!(
(FnMut() -> Result<(), E> + Send + 'static),
|function| Arc::new(Mutex::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");
}
impl<E> Runnable<E> for ArcRunnable<E> {
#[inline]
fn run(&mut self) -> Result<(), E> {
(self.function.lock())()
}
impl_arc_conversions!(
ArcRunnable<E>,
BoxRunnable,
RcRunnable,
FnMut() -> Result<(), E>
);
}
impl_supplier_debug_display!(ArcRunnable<E>);