eventbus_tiny/macros.rs
1//! Useful macros
2
3/// Creates a filter-map clause that maps any event of type `$source` into `Some(T)`
4#[macro_export]
5macro_rules! where_into {
6 ($($source:ty),+ => $target:ty) => {{
7 // Create mapper function
8 fn convert(event: &dyn ::std::any::Any) -> ::std::option::Option<$target> {
9 // Try to downcast events
10 $(
11 // Downcast event if possible
12 if let Some(event) = event.downcast_ref::<$source>() {
13 let cloned = event.clone();
14 return Some(cloned.into());
15 }
16 )+
17
18 // No downcast successful
19 return None;
20 }
21
22 // Return mapper function
23 convert
24 }};
25}
26
27/// Creates a filter-map clause that tries to map any event of type `$source` into `Some(T)`
28#[macro_export]
29macro_rules! where_try_into {
30 ($($source:ty),+ => $target:ty) => {{
31 // Create mapper function
32 fn convert(event: &dyn ::std::any::Any) -> ::std::option::Option<$target> {
33 // Try to downcast events
34 $(
35 // Downcast and map event if possible
36 if let Some(event) = event.downcast_ref::<$source>() {
37 let cloned = event.clone();
38 if let Ok(mapped) = cloned.try_into() {
39 // Return mapped event
40 return Some(mapped);
41 }
42 }
43 )+
44
45 // No downcast+mapping successful
46 return None;
47 }
48
49 // Return mapper function
50 convert
51 }};
52}
53
54/// Implements `From` to convert `$source` into `$enum::$variant($source)`
55#[macro_export]
56macro_rules! enum_from {
57 ($($source:ty => $enum:tt :: $variant:tt),+) => {
58 $(
59 // Enum conversion
60 impl ::std::convert::From<$source> for $enum {
61 fn from(source: $source) -> Self {
62 // Do conversion
63 <$enum>::$variant(source)
64 }
65 }
66 )+
67 };
68}