use std::cell::RefCell;
#[cfg(feature = "rc")]
use std::rc::Rc;
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 RcCallable<R, E> {
pub(super) function: Rc<RefCell<dyn FnMut() -> Result<R, E>>>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<R, E> Clone for RcCallable<R, E> {
#[inline]
fn clone(&self) -> Self {
Self {
function: Rc::clone(&self.function),
metadata: self.metadata.clone(),
}
}
}
impl<R, E> RcCallable<R, E> {
impl_common_new_methods!(
semantic_mut(Callable<R, E> + 'static),
|source| move || source.call(),
|function| Rc::new(RefCell::new(function)),
"callable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: Supplier<Result<R, E>> + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("callable");
}
impl<R, E> Callable<R, E> for RcCallable<R, E> {
#[inline]
fn call(&mut self) -> Result<R, E> {
let mut function = self.function.borrow_mut();
function()
}
}
impl_function_debug_display!(RcCallable<R, E>);