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
//! The [`MessageHandler`] trait plus the internal registry types.
use TypeId;
use crateMessage;
/// A subscriber that reacts to messages drained from a
/// [`MessageBus`](crate::MessageBus).
///
/// Handlers receive `&dyn Message`. They are usually registered with a type filter via
/// [`MessageBus::register_handler`](crate::MessageBus::register_handler) — passing
/// `Some(TypeId::of::<T>())` restricts the handler to messages of type `T`, while passing
/// `None` registers a generic handler that fires for every message.
///
/// Inside [`call`](MessageHandler::call), use `msg.as_any().downcast_ref::<T>()` to
/// access the concrete message.
///
/// Implementations must be `Send + Sync` because the bus shares its handler registry
/// across threads; `call` itself takes `&self`, so handlers cannot mutate their own state
/// directly — wrap mutable state in an [`Arc<Mutex<_>>`](std::sync::Mutex),
/// [`AtomicUsize`](std::sync::atomic::AtomicUsize), or similar.
///
/// # Examples
///
/// A handler that counts incoming `Ping` messages:
///
/// ```
/// use std::any::Any;
/// use std::sync::Arc;
/// use std::sync::atomic::{AtomicUsize, Ordering};
/// use barker::{Message, MessageHandler};
///
/// #[derive(Debug)]
/// struct Ping;
/// impl Message for Ping {
/// fn as_any(&self) -> &dyn Any { self }
/// fn as_any_mut(&mut self) -> &mut dyn Any { self }
/// }
///
/// struct Counter(Arc<AtomicUsize>);
/// impl MessageHandler for Counter {
/// fn call(&self, msg: &dyn Message) {
/// if msg.as_any().downcast_ref::<Ping>().is_some() {
/// self.0.fetch_add(1, Ordering::SeqCst);
/// }
/// }
/// }
/// ```
// Internal registry entry: a handler plus its routing filter.
pub
// Routing filter for a registered handler.
pub