mod_events/core.rs
1//! Core event system traits and types
2
3use std::any::{Any, TypeId};
4use std::fmt;
5
6/// Core trait that all events must implement
7///
8/// This trait provides the foundation for type-safe event dispatch.
9/// All event types must implement this trait to be used with the dispatcher.
10///
11/// # Example
12///
13/// ```rust
14/// use mod_events::Event;
15///
16/// #[derive(Debug, Clone)]
17/// struct UserRegistered {
18/// user_id: u64,
19/// email: String,
20/// }
21///
22/// impl Event for UserRegistered {
23/// fn as_any(&self) -> &dyn std::any::Any {
24/// self
25/// }
26/// }
27/// ```
28pub trait Event: Any + Send + Sync + fmt::Debug {
29 /// Returns the event as Any for downcasting
30 fn as_any(&self) -> &dyn Any;
31
32 /// Returns a unique identifier for this event type
33 fn type_id(&self) -> TypeId {
34 TypeId::of::<Self>()
35 }
36
37 /// Returns the event name for debugging
38 fn event_name(&self) -> &'static str {
39 std::any::type_name::<Self>()
40 }
41}
42
43/// Unique identifier for event listeners
44///
45/// This is returned when subscribing to events and can be used
46/// to unsubscribe specific listeners later.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct ListenerId {
49 pub(crate) id: usize,
50 pub(crate) type_id: TypeId,
51}
52
53impl ListenerId {
54 pub(crate) fn new(id: usize, type_id: TypeId) -> Self {
55 Self { id, type_id }
56 }
57}