use std::collections::HashMap;
use crate::ids::ComponentTag;
#[derive(Default)]
pub struct EventSource {
subscriptions: HashMap<String, Vec<ComponentTag>>,
}
impl EventSource {
pub fn new() -> Self {
Self::default()
}
pub fn subscribe(&mut self, event_kind: &str, tag: ComponentTag) {
let entry = self
.subscriptions
.entry(event_kind.to_string())
.or_default();
if !entry.contains(&tag) {
entry.push(tag);
}
}
pub fn unsubscribe(&mut self, event_kind: &str, tag: ComponentTag) {
if let Some(entry) = self.subscriptions.get_mut(event_kind) {
entry.retain(|t| *t != tag);
if entry.is_empty() {
self.subscriptions.remove(event_kind);
}
}
}
pub fn subscribers(&self, event_kind: &str) -> &[ComponentTag] {
self.subscriptions
.get(event_kind)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn len(&self) -> usize {
self.subscriptions.len()
}
pub fn is_empty(&self) -> bool {
self.subscriptions.is_empty()
}
}