Skip to main content

ek_event/
event.rs

1//! `Event` 结构体(对齐原版 `Event(type, data)`)。
2
3use std::any::Any;
4use std::sync::Arc;
5
6/// 事件载荷:任意可跨线程共享对象,ek-event 自身不解释内容。
7pub type EventData = Arc<dyn Any + Send + Sync>;
8
9/// 事件:分发按 `event_type` 精确匹配,`data` 直传 handler。
10pub struct Event {
11    /// 事件类型串,如 `"eTick."` / `"eTick.600000"` / [`crate::EVENT_TIMER`]。
12    pub event_type: String,
13    /// 载荷;无载荷事件(如 TIMER)默认 [`EventData`] 指向 ()。
14    pub data: EventData,
15}
16
17impl Event {
18    /// 构造无载荷事件(如 `Event::new("eTimer")`)。
19    pub fn new(event_type: impl Into<String>) -> Self {
20        Self::with_data(event_type, Arc::new(()))
21    }
22
23    /// 构造带载荷事件。载荷用 `std::sync::Arc::new(your_struct)` 包一层。
24    pub fn with_data(event_type: impl Into<String>, data: EventData) -> Self {
25        Self {
26            event_type: event_type.into(),
27            data,
28        }
29    }
30}
31
32impl std::fmt::Debug for Event {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("Event")
35            .field("event_type", &self.event_type)
36            .field("data", &"<Arc<dyn Any>>")
37            .finish()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn downcast_works() {
47        let e = Event::with_data("eTick.", Arc::new(42u32));
48        let v = e.data.downcast_ref::<u32>().unwrap();
49        assert_eq!(*v, 42);
50    }
51}