use std::sync::Arc;
use parking_lot::Mutex;
use crate::{
functions::macros::impl_function_debug_display,
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::supplier::Supplier,
tasks::callable::Callable,
};
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct ArcCallable<R, E> {
pub(super) function: Arc<Mutex<dyn FnMut() -> Result<R, E> + Send>>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<R, E> Clone for ArcCallable<R, E> {
#[inline]
fn clone(&self) -> Self {
Self {
function: Arc::clone(&self.function),
metadata: self.metadata.clone(),
}
}
}
impl<R, E> ArcCallable<R, E> {
impl_common_new_methods!(
semantic_mut(Callable<R, E> + Send + 'static),
|source| move || source.call(),
|function| Arc::new(Mutex::new(function)),
"callable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: Supplier<Result<R, E>> + Send + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("callable");
}
impl<R, E> Callable<R, E> for ArcCallable<R, E> {
#[inline]
fn call(&mut self) -> Result<R, E> {
let mut function = self.function.lock();
function()
}
}
impl_function_debug_display!(ArcCallable<R, E>);