use crate::handlers::Action;
use crate::ids::Id;
use crate::linkage::recipient::ActionRecipient;
use anyhow::Error;
use std::collections::HashMap;
#[derive(Debug)]
pub struct Distributor<T> {
recipients: HashMap<Id, Box<dyn ActionRecipient<T>>>,
}
impl<T> Default for Distributor<T> {
fn default() -> Self {
Self {
recipients: HashMap::new(),
}
}
}
impl<T> Distributor<T> {
pub fn new() -> Self {
Self::default()
}
}
impl<T> Distributor<T>
where
T: Action + Clone,
{
pub fn insert(&mut self, recipient: Box<dyn ActionRecipient<T>>) {
let id = recipient.id_ref().to_owned();
self.recipients.insert(id, recipient);
}
pub fn remove(&mut self, id: &Id) -> Option<Box<dyn ActionRecipient<T>>> {
self.recipients.remove(id)
}
pub async fn act_all(&mut self, action: T) -> Result<(), Error> {
self.recipients
.values_mut()
.map(|recipient| recipient.act(action.clone()))
.find(Result::is_err)
.transpose()
.map(drop)
}
pub fn len(&self) -> usize {
self.recipients.len()
}
pub fn is_empty(&self) -> bool {
self.recipients.is_empty()
}
}