ek-event 0.1.2

Self-contained event engine in Rust, a faithful semantic replication of enkeep_trade's event engine. No dependency on enkeep_trade.
Documentation
//! `Event` 结构体(对齐原版 `Event(type, data)`)。

use std::any::Any;
use std::sync::Arc;

/// 事件载荷:任意可跨线程共享对象,ek-event 自身不解释内容。
pub type EventData = Arc<dyn Any + Send + Sync>;

/// 事件:分发按 `event_type` 精确匹配,`data` 直传 handler。
pub struct Event {
    /// 事件类型串,如 `"eTick."` / `"eTick.600000"` / [`crate::EVENT_TIMER`]。
    pub event_type: String,
    /// 载荷;无载荷事件(如 TIMER)默认 [`EventData`] 指向 ()。
    pub data: EventData,
}

impl Event {
    /// 构造无载荷事件(如 `Event::new("eTimer")`)。
    pub fn new(event_type: impl Into<String>) -> Self {
        Self::with_data(event_type, Arc::new(()))
    }

    /// 构造带载荷事件。载荷用 `std::sync::Arc::new(your_struct)` 包一层。
    pub fn with_data(event_type: impl Into<String>, data: EventData) -> Self {
        Self {
            event_type: event_type.into(),
            data,
        }
    }
}

impl std::fmt::Debug for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Event")
            .field("event_type", &self.event_type)
            .field("data", &"<Arc<dyn Any>>")
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn downcast_works() {
        let e = Event::with_data("eTick.", Arc::new(42u32));
        let v = e.data.downcast_ref::<u32>().unwrap();
        assert_eq!(*v, 42);
    }
}