serenade_event/dispatcher.rs
1//! In-process synchronous event dispatcher.
2
3use std::sync::Arc;
4
5use crate::{Event, EventError, EventSubscriber};
6
7/// Dispatches events to subscribers sorted by priority (high first).
8///
9/// # Examples
10///
11/// ```
12/// use std::sync::{Arc, Mutex};
13/// use serenade_event::{
14/// assert_dispatched, Event, EventDispatcher, RecordingSubscriber,
15/// };
16///
17/// struct Ping;
18///
19/// impl Event for Ping {
20/// fn name(&self) -> &'static str {
21/// "demo.ping"
22/// }
23/// }
24///
25/// let names = Arc::new(Mutex::new(Vec::new()));
26/// let mut dispatcher = EventDispatcher::new();
27/// dispatcher.add(Arc::new(RecordingSubscriber::new("demo.ping", Arc::clone(&names))));
28/// dispatcher.dispatch(&Ping).expect("dispatch");
29/// assert_dispatched(&names.lock().expect("lock"), &["demo.ping"]);
30/// ```
31#[derive(Clone, Default)]
32pub struct EventDispatcher {
33 subscribers: Vec<Arc<dyn EventSubscriber>>,
34}
35
36impl EventDispatcher {
37 /// Creates an empty dispatcher.
38 #[must_use]
39 pub fn new() -> Self {
40 Self::default()
41 }
42
43 /// Adds a subscriber. Call [`Self::sort`] before dispatch if adding after construction.
44 pub fn add(&mut self, subscriber: Arc<dyn EventSubscriber>) {
45 self.subscribers.push(subscriber);
46 self.sort();
47 }
48
49 /// Sorts subscribers so higher priority runs first.
50 pub fn sort(&mut self) {
51 self.subscribers
52 .sort_by_key(|subscriber| std::cmp::Reverse(subscriber.priority()));
53 }
54
55 /// Dispatches `event` to every subscriber whose [`EventSubscriber::event_name`] matches.
56 ///
57 /// All matching subscribers run even if one fails. The first error is returned.
58 ///
59 /// # Errors
60 ///
61 /// Returns the first [`EventError`] from a subscriber.
62 pub fn dispatch(&self, event: &dyn Event) -> Result<(), EventError> {
63 let mut first_error = None;
64 for subscriber in &self.subscribers {
65 if subscriber.event_name() != event.name() {
66 continue;
67 }
68 if let Err(error) = subscriber.handle(event)
69 && first_error.is_none()
70 {
71 first_error = Some(error);
72 }
73 }
74 first_error.map_or(Ok(()), Err)
75 }
76
77 /// Number of registered subscribers.
78 #[must_use]
79 pub fn len(&self) -> usize {
80 self.subscribers.len()
81 }
82
83 /// Returns whether no subscribers are registered.
84 #[must_use]
85 pub fn is_empty(&self) -> bool {
86 self.subscribers.is_empty()
87 }
88}