//! Who is being transcribed right now. At most `max` people at once (settings `voice.maxSpeakers`); //! someone who starts while the limit is reached is not heard until their next start after the //! others free a place. use std::collections::HashSet; pub struct SpeakerGate { max: usize, active: HashSet, } impl SpeakerGate { pub fn new(max: usize) -> Self { Self { max, active: HashSet::new() } } /// `id` started speaking. True if their audio goes to the STT. pub fn start(&mut self, id: u64) -> bool { if self.active.contains(&id) { return true; } if self.active.len() >= self.max { return false; } self.active.insert(id); true } /// `id` stopped (or left). True if they were being transcribed. pub fn end(&mut self, id: u64) -> bool { self.active.remove(&id) } pub fn is_active(&self, id: u64) -> bool { self.active.contains(&id) } pub fn count(&self) -> usize { self.active.len() } pub fn clear(&mut self) { self.active.clear(); } } #[cfg(test)] mod tests { use super::*; #[test] fn hears_up_to_the_limit_and_lets_the_next_in_when_someone_stops() { let mut g = SpeakerGate::new(2); assert!(g.start(1) && g.start(2)); assert!(!g.start(3)); assert!(!g.is_active(3)); assert!(g.end(1)); assert!(g.start(3)); assert_eq!(g.count(), 2); } #[test] fn already_heard_stays_heard_and_ending_a_stranger_is_a_no_op() { let mut g = SpeakerGate::new(1); assert!(g.start(1) && g.start(1)); assert!(!g.end(9)); assert!(g.end(1)); assert!(!g.end(1)); } }