1use std::{any::Any, sync::Arc, time::SystemTime};
2
3use crate::{bus::Bus, node_id::NodeId, reg::BusType};
4
5#[derive(Clone)]
6pub struct BusEvent<M>
7where
8 M: Send + Sync + 'static,
9{
10 pub source: NodeId,
11 pub time: SystemTime,
12 pub msg: M,
13}
14
15pub type AnyMsg = Arc<Box<dyn Any + Send + Sync + 'static>>;
16pub type AnyBusEvent = BusEvent<AnyMsg>;
17
18impl<M: BusType> BusEvent<M> {
19 pub fn type_erase(self) -> AnyBusEvent {
20 AnyBusEvent {
21 source: self.source,
22 time: self.time,
23 msg: Arc::new(Box::new(self.msg)),
24 }
25 }
26
27 pub fn bus_send(self) {
28 Bus::get_default().send_event(self);
29 }
30}
31
32impl AnyBusEvent {
33 pub fn downcast_cloned<M: BusType>(&self) -> BusEvent<M> {
34 let msg = self
35 .msg
36 .as_ref()
37 .as_ref()
38 .downcast_ref::<M>()
39 .cloned()
40 .unwrap();
41
42 BusEvent {
43 source: self.source,
44 time: self.time,
45 msg,
46 }
47 }
48}