use std::cell::RefCell;
use std::rc::Rc;
use super::execute::run_computation;
use super::node::NodeKind;
use super::runtime::{self, with_rt, RawId};
use super::scope::Scope;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Effect {
pub(crate) id: RawId,
}
impl std::fmt::Debug for Effect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Effect({}, gen {})",
self.id.key.index, self.id.key.generation
)
}
}
impl Effect {
pub(crate) fn new(
scope: Scope,
label: Option<&'static str>,
f: impl FnMut() + 'static,
) -> Effect {
let id = with_rt(|rt| {
rt.check_thread(scope.id);
let key = rt.create_node(
Some(scope.id.key),
NodeKind::Effect {
run: Rc::new(RefCell::new(f)),
},
);
if let Some(node) = rt.graph.get_mut(key) {
node.label = label;
}
RawId { key, rt: rt.rt_id }
});
run_computation(id.key);
Effect { id }
}
pub fn is_alive(self) -> bool {
with_rt(|rt| rt.rt_id == self.id.rt && rt.graph.contains(self.id.key))
}
pub fn dispose(self) {
runtime::dispose_node(self.id);
}
}