inertia_rust/
macros.rs

1#[macro_export]
2macro_rules! hashmap {
3    () => ( std::collections::HashMap::new() );
4    ($( $key: expr => $value: expr ),+ $(,)?) => {
5        {
6            let mut map = std::collections::HashMap::new();
7            $(
8                map.insert($key, $value);
9            )*
10            map
11        }
12    };
13}
14
15#[macro_export]
16macro_rules! prop_resolver {
17    () => (std::sync::Arc::new(move || Box::pin(async move { () })));
18
19    ($($clone_stmt: stmt),+; $block: block) => {{
20        std::sync::Arc::new(move || {
21            $($clone_stmt)+
22            Box::pin(async move $block)
23        })
24    }};
25
26    ($block: block) => {{
27        std::sync::Arc::new(move || Box::pin(async move $block))
28    }};
29}
30
31#[cfg(test)]
32mod test {
33    use std::{
34        collections::HashMap,
35        sync::{Arc, Mutex},
36    };
37
38    use crate::{InertiaProp, IntoInertiaPropResult};
39
40    #[test]
41    fn test_hashmap_macro() {
42        let mut manual_hashmap = HashMap::new();
43        manual_hashmap.insert("foo".to_string(), 10);
44        manual_hashmap.insert("bar".to_string(), 25);
45        manual_hashmap.insert("baz".to_string(), 49020);
46
47        let macro_hashmap = hashmap![
48            "foo".to_string() => 10,
49            "bar".to_string() => 25,
50            "baz".to_string() => 49020,
51        ];
52
53        assert_eq!(manual_hashmap, macro_hashmap);
54        assert_eq!(
55            HashMap::<_, _>::new() as HashMap<String, String>,
56            hashmap![]
57        );
58    }
59
60    async fn an_async_operation() {}
61
62    #[tokio::test]
63    async fn test_prop_resolver_with_moving_let() {
64        let message = Arc::new("Super important and often used message!");
65        let counter = Arc::new(Mutex::new(1));
66
67        let counter_clone = counter.clone();
68        let message_clone = message.clone();
69
70        let prop_with_macro = InertiaProp::lazy(prop_resolver!(
71            let counter_clone = counter_clone.clone(),
72            let message_clone = message_clone.clone();
73            {
74                an_async_operation().await;
75                Ok(format!("{} {}", message_clone, *counter_clone.lock().unwrap()).into())
76            }
77        ));
78
79        let counter_clone = counter.clone();
80        let message_clone = message.clone();
81
82        let prop_with_arc = InertiaProp::lazy(Arc::new(move || {
83            let counter_clone = counter_clone.clone();
84            let message_clone = message_clone.clone();
85
86            Box::pin(async move {
87                an_async_operation().await;
88                format!("{} {}", message_clone, *counter_clone.lock().unwrap()).into_inertia_value()
89            })
90        }));
91
92        assert_eq!(
93            prop_with_arc.resolve_unconditionally().await.unwrap(),
94            prop_with_macro.resolve_unconditionally().await.unwrap()
95        );
96    }
97}