rusty_typesh/
macros.rs

1//! Macro definitions for the type pattern matching system.
2//! 
3//! This module provides the `type_match!` macro for convenient
4//! pattern matching syntax.
5
6/// Matches a value against multiple type patterns using a convenient macro syntax.
7/// 
8/// # Arguments
9/// * `$value` - The value to match
10/// * `$type` - The type to match against
11/// * `$handler` - The closure to handle the matched type
12/// 
13/// # Examples
14/// ```
15/// use rusty_typesh::type_match;
16/// 
17/// let value = 42i32;
18/// let result = type_match!(
19///     value,
20///     i32 => |x: &i32| format!("Integer: {}", x),
21///     String => |x: &String| format!("String: {}", x)
22/// );
23/// ```
24#[macro_export]
25macro_rules! type_match {
26    ($value:expr, $($type:ty => $handler:expr),+ $(,)?) => {{
27        let value: &dyn std::any::Any = &$value;
28        match value {
29            $(
30                x if x.is::<$type>() => Some(($handler)(x.downcast_ref::<$type>().unwrap())),
31            )+
32            _ => None,
33        }
34    }};
35}
36
37#[cfg(test)]
38mod tests {
39    #[test]
40    fn test_type_match_macro() {
41        let value = 42i32;
42        let result = type_match!(
43            value,
44            i32 => |x: &i32| -> Result<String, ()> { Ok(format!("Integer: {}", x)) },
45            String => |x: &String| -> Result<String, ()> { Ok(format!("String length: {}", x.to_string().len())) }
46        );
47        assert_eq!(result, Some(Ok("Integer: 42".to_string())));
48    }
49}