Skip to main content

rayengine_core/
events.rs

1//! Typed game events with explicit tick lifetime and reused storage.
2
3/// An ordered, game-owned event queue. No hidden dispatch or subscriptions.
4///
5/// Producers call [`Self::send`], readers inspect [`Self::read`], and the game
6/// clears or drains the queue at an explicit phase boundary. Several readers
7/// can see the same events before clear. Preallocate for hot simulation paths.
8///
9/// ```
10/// use rayengine_core::events::Events;
11/// struct Hit { damage: u32 }
12/// let mut hits = Events::with_capacity(32);
13/// hits.send(Hit { damage: 12 });
14/// assert_eq!(hits.read().iter().map(|h| h.damage).sum::<u32>(), 12);
15/// // Consume once, retaining capacity for the next tick.
16/// assert_eq!(hits.drain().count(), 1);
17/// assert!(hits.read().is_empty());
18/// ```
19#[derive(Debug)]
20pub struct Events<T> {
21    items: Vec<T>,
22}
23
24impl<T> Default for Events<T> {
25    fn default() -> Self {
26        Self { items: Vec::new() }
27    }
28}
29
30impl<T> Events<T> {
31    /// Empty queue with reserved event capacity.
32    pub fn with_capacity(capacity: usize) -> Self {
33        Self {
34            items: Vec::with_capacity(capacity),
35        }
36    }
37    /// Appends a game event. Grows if reserved capacity is exceeded.
38    pub fn send(&mut self, event: T) {
39        self.items.push(event);
40    }
41    /// Events in production order. Reading does not consume them.
42    pub fn read(&self) -> &[T] {
43        &self.items
44    }
45    /// Consumes events in order, retaining the queue's storage.
46    pub fn drain(&mut self) -> std::vec::Drain<'_, T> {
47        self.items.drain(..)
48    }
49    /// Drops all events, retaining storage for the next phase/tick.
50    pub fn clear(&mut self) {
51        self.items.clear();
52    }
53    /// Reserved slots, useful when planning an allocation budget.
54    pub fn capacity(&self) -> usize {
55        self.items.capacity()
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn multiple_readers_see_ordered_events_until_the_explicit_boundary() {
65        let mut queue = Events::with_capacity(4);
66        queue.send(3);
67        queue.send(7);
68        assert_eq!(queue.read(), &[3, 7]);
69        assert_eq!(queue.read().iter().sum::<i32>(), 10);
70        assert_eq!(queue.drain().collect::<Vec<_>>(), vec![3, 7]);
71        assert!(queue.read().is_empty());
72        assert_eq!(queue.capacity(), 4);
73        queue.send(9);
74        queue.clear();
75        assert_eq!(queue.capacity(), 4);
76    }
77}