use std::cell::RefCell;
#[cfg(feature = "rc")]
use std::rc::Rc;
use crate::{
macros::{
impl_common_name_methods,
impl_common_new_methods,
},
suppliers::{
macros::impl_supplier_debug_display,
supplier::Supplier,
},
tasks::runnable::Runnable,
};
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct RcRunnable<E> {
pub(super) function: Rc<RefCell<dyn FnMut() -> Result<(), E>>>,
pub(super) metadata: crate::internal::CallbackMetadata,
}
impl<E> Clone for RcRunnable<E> {
#[inline]
fn clone(&self) -> Self {
Self {
function: Rc::clone(&self.function),
metadata: self.metadata.clone(),
}
}
}
impl<E> RcRunnable<E> {
impl_common_new_methods!(
semantic_mut(Runnable<E> + 'static),
|source| move || source.run(),
|function| Rc::new(RefCell::new(function)),
"runnable"
);
#[inline]
pub fn from_supplier<S>(supplier: S) -> Self
where
S: Supplier<Result<(), E>> + 'static,
{
Self::new(move || supplier.get())
}
impl_common_name_methods!("runnable");
}
impl<E> Runnable<E> for RcRunnable<E> {
#[inline]
fn run(&mut self) -> Result<(), E> {
let mut function = self.function.borrow_mut();
function()
}
}
impl_supplier_debug_display!(RcRunnable<E>);