use crate::lock::Lock; use crate::pair::Pair; use crate::uid::{Kind as UidKind, Uid}; use crate::util::VecExt; use crate::World; pub mod component; #[derive(Debug, Clone)] #[non_exhaustive] pub struct Emitted<'a> { pub event: Uid, pub match_ids: &'a [Uid], } #[derive(Debug)] pub struct Submitter<'world> { new_events: &'world Lock, } impl<'world> Submitter<'world> { /// Submits a event to be handled later. /// /// # Panics /// Will panic if unable to acquire a read-write lock to the event store. pub fn submit_event(&self, event: &Pair, match_id: Uid) { let mut new_events_lock = self .new_events .write_nonblock() .expect("Failed to acquire read-write lock to new events"); new_events_lock.push_event_match(event, match_id); } pub(crate) fn new(world: &'world World) -> Self { Self { new_events: &world.data.new_events } } } #[derive(Debug, Default)] pub(crate) struct NewEvents { events: Vec<(Uid, Matches)>, } impl NewEvents { pub fn push_event_match(&mut self, event: &Pair, match_id: Uid) { let event_id = event.id(); assert_eq!(event_id.kind(), UidKind::Pair); if let Ok(event_index) = self .events .binary_search_by_key(&event_id, |(other_event_id, _)| *other_event_id) { let Some((_, matches)) = self.events.get_mut(event_index) else { unreachable!(); }; matches.sorted_push(match_id); return; } self.events.insert_at_partition_point_by_key( (event_id, Matches { match_ids: Vec::from([match_id]) }), |(other_event_id, _)| *other_event_id, ); } pub fn take(&mut self) -> Vec<(Uid, Matches)> { std::mem::take(&mut self.events) } } #[derive(Debug)] pub(crate) struct Matches { pub match_ids: Vec, } impl Matches { fn sorted_push(&mut self, match_id: Uid) { if self.match_ids.binary_search(&match_id).is_ok() { return; } self.match_ids .insert_at_partition_point_by_key(match_id, |other_match_id| *other_match_id); } }