use std::sync::Arc;
use tokio::sync::broadcast;
pub struct Lobby<T: Clone + Send + 'static> {
tx: broadcast::Sender<T>,
validator: Arc<dyn Fn(&T) -> bool + Send + Sync>,
}
impl<T: Clone + Send + 'static> Clone for Lobby<T> {
fn clone(&self) -> Self {
Self {
tx: self.tx.clone(),
validator: self.validator.clone(),
}
}
}
impl<T: Clone + Send + 'static> Lobby<T> {
pub fn new(capacity: usize) -> Self {
let (tx, _) = broadcast::channel(capacity);
Self {
tx,
validator: Arc::new(|_| true),
}
}
pub fn with_validator(mut self, f: impl Fn(&T) -> bool + Send + Sync + 'static) -> Self {
self.validator = Arc::new(f);
self
}
pub fn subscribe(&self) -> broadcast::Receiver<T> {
self.tx.subscribe()
}
pub fn send(&self, msg: T) -> bool {
if (self.validator)(&msg) {
let _ = self.tx.send(msg);
true
} else {
false
}
}
}