1use tokio::sync::mpsc;
2
3use core::fmt;
4use std::{
5 any::{Any, TypeId},
6 sync::Arc,
7};
8
9use crate::{bus::Bus, event::BusEvent};
10
11#[derive(Clone)]
12pub struct TypeReg {
13 pub type_name: &'static str,
14 pub type_id: TypeId,
15 pub buffer_cap: usize,
16 pub bitcode_support: Option<(
17 fn(Arc<Box<dyn Any + Send + Sync + 'static>>) -> Vec<u8>,
19 fn(&[u8]) -> Result<Arc<Box<dyn Any + Send + Sync + 'static>>, bitcode::Error>,
21 )>,
22}
23
24pub struct TypeRegFn(pub fn() -> TypeReg);
25
26inventory::collect!(TypeRegFn);
27
28pub trait BusType: Clone + Send + Sync + 'static {
29 fn get_type_reg() -> TypeReg;
30}
31
32pub trait BusHelpers: Clone + Send + Sync + 'static {
33 fn bus_sub(prefix_latest: bool) -> mpsc::Receiver<BusEvent<Self>>;
34 fn bus_send(self);
35 fn bus_latest() -> Option<BusEvent<Self>>;
36}
37
38impl<T> BusHelpers for T
39where
40 T: BusType,
41{
42 fn bus_sub(prefix_latest: bool) -> mpsc::Receiver<BusEvent<Self>> {
43 Bus::get_default().subscribe::<Self>(prefix_latest)
44 }
45
46 fn bus_send(self) {
47 Bus::get_default().send(self);
48 }
49
50 fn bus_latest() -> Option<BusEvent<Self>> {
51 Bus::get_default().get_latest::<Self>()
52 }
53}
54
55pub trait BusTypeTrace: BusType {
56 fn bus_trace();
57}
58
59impl<T> BusTypeTrace for T
60where
61 T: BusType + fmt::Debug,
62{
63 fn bus_trace() {
64 Bus::get_default().trace_events::<Self>();
65 }
66}