summaryrefslogtreecommitdiff
path: root/ecs/src/event.rs
blob: 2934b8265b7a6cf7c3abf8858e2306601aa69b3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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<NewEvents>,
}

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<Uid, Uid>, 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<Uid, Uid>, 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<Uid>,
}

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);
    }
}