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,
},
tasks::callable_with::CallableWith,
};
type ArcCallableWithFn<T, R, E> =
Arc<Mutex<dyn FnMut(&mut T) -> Result<R, E> + Send>>;
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct ArcCallableWith<T, R, E> {
pub(super) function: ArcCallableWithFn<T, R, E>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<T, R, E> Clone for ArcCallableWith<T, R, E> {
#[inline]
fn clone(&self) -> Self {
Self {
function: Arc::clone(&self.function),
metadata: self.metadata.clone(),
}
}
}
impl<T, R, E> ArcCallableWith<T, R, E> {
impl_common_new_methods!(
semantic_mut(CallableWith<T, R, E> + Send + 'static),
|source| move |input: &mut T| source.call_with(input),
|function| Arc::new(Mutex::new(function)),
"callable-with"
);
impl_common_name_methods!("callable-with");
}
impl<T, R, E> CallableWith<T, R, E> for ArcCallableWith<T, R, E> {
#[inline]
fn call_with(&mut self, input: &mut T) -> Result<R, E> {
let mut function = self.function.lock();
function(input)
}
}
impl_function_debug_display!(ArcCallableWith<T, R, E>);