use std::{any::Any, cell::RefCell, rc::Rc};
use super::element::ErasedCx;
use crate::NodeId;
pub(crate) type BackListener = Rc<dyn Fn(&mut dyn Any, &dyn Any, &mut ErasedCx) -> bool>;
#[derive(Default)]
pub(crate) struct BackListeners {
next: u64,
pub(crate) list: Vec<(u64, NodeId, BackListener)>,
pub(crate) changed: bool,
}
impl BackListeners {
pub(crate) fn add(&mut self, host: NodeId, listener: BackListener) -> u64 {
self.next += 1;
self.changed |= self.list.is_empty();
self.list.push((self.next, host, listener));
self.next
}
pub(crate) fn remove(&mut self, id: u64) -> Option<BackListener> {
let i = self.list.iter().position(|(i, ..)| *i == id)?;
let (_, _, listener) = self.list.remove(i);
self.changed |= self.list.is_empty();
Some(listener)
}
pub(crate) fn remove_host(&mut self, host: NodeId) -> Vec<BackListener> {
let mut gone = Vec::new();
self.list.retain(|(_, h, l)| {
let keep = *h != host;
if !keep {
gone.push(l.clone());
}
keep
});
self.changed |= !gone.is_empty() && self.list.is_empty();
gone
}
pub(crate) fn newest_first(&self) -> Vec<(NodeId, BackListener)> {
self.list
.iter()
.rev()
.map(|(_, h, l)| (*h, l.clone()))
.collect()
}
}
#[must_use = "a dropped subscription removes its listener: keep it in a field"]
pub struct BackSubscription {
listeners: std::rc::Weak<RefCell<BackListeners>>,
id: u64,
}
impl BackSubscription {
pub(crate) fn new(listeners: &Rc<RefCell<BackListeners>>, id: u64) -> Self {
Self {
listeners: Rc::downgrade(listeners),
id,
}
}
}
impl Drop for BackSubscription {
fn drop(&mut self) {
if let Some(listeners) = self.listeners.upgrade() {
let removed = listeners.borrow_mut().remove(self.id);
drop(removed);
}
}
}