keyed_emitter/lib.rs
1//! String-keyed event emitter with typed payloads and synchronous dispatch.
2//!
3//! An [`EventEmitter`] maps event names to listeners. Each listener is a closure
4//! that takes `&T` for one payload type `T`. [`EventEmitter::emit`] borrows a
5//! payload, invokes every listener on that event whose registered type equals
6//! the payload type, and returns how many callbacks ran. Listeners registered
7//! for a different type are skipped and keep their call budget.
8//!
9//! Every callback runs on the caller's thread before `emit` returns, in
10//! registration order. The crate has no dependencies.
11//!
12//! # Example
13//!
14//! ```
15//! use keyed_emitter::EventEmitter;
16//! use std::sync::{Arc, Mutex};
17//!
18//! let seen = Arc::new(Mutex::new(Vec::new()));
19//! let sink = Arc::clone(&seen);
20//!
21//! let mut emitter = EventEmitter::new();
22//! emitter.on::<u32, _>("tick", move |n| sink.lock().unwrap().push(*n));
23//!
24//! assert_eq!(emitter.emit("tick", &7u32), 1);
25//! assert_eq!(emitter.emit("tick", &"wrong type"), 0);
26//! assert_eq!(*seen.lock().unwrap(), vec![7]);
27//! ```
28//!
29//! # Payload types
30//!
31//! `T` needs `'static` and nothing else. Payloads that are not `Clone`, not
32//! `Send`, and not serializable all work, because the emitter hands the
33//! listener a shared borrow and never copies or stores the value.
34//!
35//! # Budgets
36//!
37//! [`EventEmitter::once`] and [`EventEmitter::on_limited`] give a listener a
38//! call budget. The budget is charged only when the callback runs, so a
39//! mismatched emit leaves it untouched. A listener whose budget reaches zero is
40//! removed within the `emit` call that exhausted it.
41//!
42//! # Panics
43//!
44//! No method of this crate panics on any input. Allocation failure, a panic
45//! raised by a user callback, or a panic raised by a callback capture's
46//! destructor during listener pruning can cross `emit`. A callback panic
47//! unwinds out of `emit` with the emitter left coherent. The budget is charged
48//! before the callback runs, so a `once` listener that panicked does not fire
49//! again. Exhausted entries are pruned before that panic is re-raised.
50//!
51//! # Sharing across threads
52//!
53//! `EventEmitter` is `Send` and not `Sync`. Registration and dispatch take
54//! `&mut self`, so sharing means wrapping it in a `Mutex`. A
55//! `static OnceLock<Mutex<_>>` gives a process-wide emitter:
56//!
57//! ```
58//! use keyed_emitter::EventEmitter;
59//! use std::sync::{Mutex, OnceLock};
60//!
61//! static EVENTS: OnceLock<Mutex<EventEmitter>> = OnceLock::new();
62//!
63//! fn events() -> &'static Mutex<EventEmitter> {
64//! EVENTS.get_or_init(|| Mutex::new(EventEmitter::new()))
65//! }
66//!
67//! struct Signal {
68//! code: u16,
69//! }
70//!
71//! events().lock().unwrap().on::<Signal, _>("signal", |s| {
72//! assert_eq!(s.code, 200);
73//! });
74//!
75//! let fired = std::thread::spawn(|| {
76//! events().lock().unwrap().emit("signal", &Signal { code: 200 })
77//! })
78//! .join()
79//! .unwrap();
80//! assert_eq!(fired, 1);
81//! ```
82//!
83//! Calling back into the same `Mutex` from inside a callback locks a mutex the
84//! current thread already holds. That is a self-deadlock. Record what you need
85//! in the callback and act on it after `emit` returns.
86
87//! # Deprecated
88//!
89//! This crate is deprecated as of 0.1.1. It will receive no new features.
90//! Existing published versions remain on crates.io. For a few handlers, a
91//! hand-rolled `HashMap<K, Vec<Box<dyn Fn>>>` is straightforward. For a
92//! fuller API, search crates.io for established event-emitter crates.
93#![forbid(unsafe_code)]
94#![warn(missing_docs)]
95
96use std::any::{Any, TypeId};
97use std::collections::HashMap;
98use std::fmt;
99use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
100
101#[cfg(doctest)]
102#[doc = include_str!("../README.md")]
103struct ReadmeDoctests;
104
105/// Handle for one registered listener, returned by every registration method.
106///
107/// Ids are unique within one [`EventEmitter`] for its lifetime and are never
108/// reused by that instance. Two different instances can mint the same id.
109#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
110#[deprecated(
111 since = "0.1.1",
112 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
113)]
114pub struct ListenerId(u64);
115
116type Callback = Box<dyn FnMut(&dyn Any) + Send>;
117
118struct Listener {
119 id: u64,
120 type_id: TypeId,
121 remaining: Option<u64>,
122 callback: Callback,
123}
124
125impl Listener {
126 fn is_live(&self) -> bool {
127 self.remaining != Some(0)
128 }
129}
130
131/// Registry of listeners keyed by event name.
132///
133/// See the [crate documentation](crate) for the dispatch rules.
134#[derive(Default)]
135#[deprecated(
136 since = "0.1.1",
137 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
138)]
139pub struct EventEmitter {
140 listeners: HashMap<String, Vec<Listener>>,
141 next_id: u64,
142}
143
144#[allow(deprecated)]
145impl fmt::Debug for EventEmitter {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 let live: usize = self
148 .listeners
149 .values()
150 .map(|list| list.iter().filter(|l| l.is_live()).count())
151 .sum();
152 f.debug_struct("EventEmitter")
153 .field("events", &self.listeners.len())
154 .field("listeners", &live)
155 .finish()
156 }
157}
158
159#[allow(deprecated)]
160impl EventEmitter {
161 /// Creates an empty emitter.
162 #[deprecated(
163 since = "0.1.1",
164 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
165 )]
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 /// Registers `callback` for `event` with no call limit.
171 ///
172 /// The callback runs on every `emit` of `event` whose payload type is `T`.
173 #[deprecated(
174 since = "0.1.1",
175 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
176 )]
177 pub fn on<T, F>(&mut self, event: &str, callback: F) -> ListenerId
178 where
179 T: 'static,
180 F: FnMut(&T) + Send + 'static,
181 {
182 self.register(event, None, callback)
183 }
184
185 /// Registers `callback` for `event` to run at most one time.
186 ///
187 /// Equivalent to `on_limited(event, 1, callback)`.
188 #[deprecated(
189 since = "0.1.1",
190 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
191 )]
192 pub fn once<T, F>(&mut self, event: &str, callback: F) -> ListenerId
193 where
194 T: 'static,
195 F: FnMut(&T) + Send + 'static,
196 {
197 self.register(event, Some(1), callback)
198 }
199
200 /// Registers `callback` for `event` to run at most `limit` times.
201 ///
202 /// Only matching emits charge the budget. The listener is removed within
203 /// the `emit` call that brings the budget to zero. With `limit == 0`
204 /// nothing is stored, and the returned id refers to no listener.
205 #[deprecated(
206 since = "0.1.1",
207 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
208 )]
209 pub fn on_limited<T, F>(&mut self, event: &str, limit: u64, callback: F) -> ListenerId
210 where
211 T: 'static,
212 F: FnMut(&T) + Send + 'static,
213 {
214 if limit == 0 {
215 return self.mint_id();
216 }
217 self.register(event, Some(limit), callback)
218 }
219
220 /// Removes the listener with `id`.
221 ///
222 /// Returns `true` when a live listener was removed. Returns `false` when
223 /// the id is unknown, already removed, or already exhausted. Calling it
224 /// twice with the same id returns `true` at most once.
225 #[deprecated(
226 since = "0.1.1",
227 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
228 )]
229 pub fn remove_listener(&mut self, id: ListenerId) -> bool {
230 let mut removed = false;
231 self.listeners.retain(|_, list| {
232 if let Some(pos) = list.iter().position(|l| l.id == id.0) {
233 removed = list[pos].is_live();
234 let doomed = list.remove(pos);
235 // Drop under catch_unwind. A panicking destructor stays inside
236 // this method.
237 let _ = catch_unwind(AssertUnwindSafe(|| {
238 drop(doomed);
239 }));
240 }
241 !list.is_empty()
242 });
243 removed
244 }
245
246 /// Invokes every listener on `event` registered for payload type `T`.
247 ///
248 /// Listeners run in registration order on the current thread, and every
249 /// one of them has returned when this method returns. Listeners registered
250 /// for another type are skipped and keep their budget.
251 /// Returns the number of callbacks invoked, which is `0` for an unknown
252 /// event, an event with no listeners, or an event whose listeners all
253 /// mismatch.
254 #[deprecated(
255 since = "0.1.1",
256 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
257 )]
258 pub fn emit<T: 'static>(&mut self, event: &str, payload: &T) -> usize {
259 let Some(list) = self.listeners.get_mut(event) else {
260 return 0;
261 };
262 list.retain(Listener::is_live);
263 if list.is_empty() {
264 self.listeners.remove(event);
265 return 0;
266 }
267 let target = TypeId::of::<T>();
268 let mut invoked = 0;
269 let mut panic_payload = None;
270 for listener in list.iter_mut() {
271 if listener.type_id != target || !listener.is_live() {
272 continue;
273 }
274 if let Some(remaining) = listener.remaining.as_mut() {
275 *remaining -= 1;
276 }
277 // Charge first. Catch the user panic so the prune below still
278 // runs, then re-raise.
279 match catch_unwind(AssertUnwindSafe(|| {
280 (listener.callback)(payload);
281 })) {
282 Ok(()) => invoked += 1,
283 Err(panic_err) => {
284 panic_payload = Some(panic_err);
285 break;
286 }
287 }
288 }
289 list.retain(Listener::is_live);
290 if list.is_empty() {
291 self.listeners.remove(event);
292 }
293 if let Some(panic_err) = panic_payload {
294 resume_unwind(panic_err);
295 }
296 invoked
297 }
298
299 /// Returns the number of live listeners registered under `event`, across
300 /// all payload types.
301 #[deprecated(
302 since = "0.1.1",
303 note = "keyed-emitter is deprecated. For a few handlers use HashMap<K, Vec<Box<dyn Fn>>>; for a fuller API see event-emitter crates on crates.io."
304 )]
305 pub fn listener_count(&self, event: &str) -> usize {
306 self.listeners
307 .get(event)
308 .map_or(0, |list| list.iter().filter(|l| l.is_live()).count())
309 }
310
311 fn mint_id(&mut self) -> ListenerId {
312 self.next_id += 1;
313 ListenerId(self.next_id)
314 }
315
316 fn register<T, F>(&mut self, event: &str, remaining: Option<u64>, mut callback: F) -> ListenerId
317 where
318 T: 'static,
319 F: FnMut(&T) + Send + 'static,
320 {
321 let id = self.mint_id();
322 let wrapped = move |any: &dyn Any| {
323 if let Some(value) = any.downcast_ref::<T>() {
324 callback(value);
325 }
326 };
327 self.listeners
328 .entry(event.to_owned())
329 .or_default()
330 .push(Listener {
331 id: id.0,
332 type_id: TypeId::of::<T>(),
333 remaining,
334 callback: Box::new(wrapped),
335 });
336 id
337 }
338}