Skip to main content

azul_core/
macros.rs

1//! Utility macros for implementing common trait patterns on callback types
2//! and enum conversions (`From`, `Display`). Used by the `core`, `layout`,
3//! and `css` crates.
4
5/// Implement the `From` trait for any type.
6#[macro_export]
7macro_rules! impl_from {
8    // From a type with a lifetime to a type which also has a lifetime
9    ($a:ident < $c:lifetime > , $b:ident:: $enum_type:ident) => {
10        impl<$c> From<$a<$c>> for $b<$c> {
11            fn from(e: $a<$c>) -> Self {
12                $b::$enum_type(e)
13            }
14        }
15    };
16
17    // From a type without a lifetime to a type which also does not have a lifetime
18    ($a:ident, $b:ident:: $enum_type:ident) => {
19        impl From<$a> for $b {
20            fn from(e: $a) -> Self {
21                $b::$enum_type(e)
22            }
23        }
24    };
25}
26
27/// Implement `Display` for an enum.
28#[macro_export]
29macro_rules! impl_display {
30    // For a type with a lifetime
31    ($enum:ident<$lt:lifetime>, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
32
33        impl<$lt> ::core::fmt::Display for $enum<$lt> {
34            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
35                use self::$enum::*;
36                match &self {
37                    $(
38                        $variant => write!(f, "{}", $fmt_string),
39                    )+
40                }
41            }
42        }
43
44    };
45
46    // For a type without a lifetime
47    ($enum:ident, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
48
49        impl ::core::fmt::Display for $enum {
50            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
51                use self::$enum::*;
52                match &self {
53                    $(
54                        $variant => write!(f, "{}", $fmt_string),
55                    )+
56                }
57            }
58        }
59
60    };
61}
62
63/// Helper macro implementing the shared trait impls (`Display`, `Debug`, `Hash`,
64/// `PartialEq`, `Eq`, `PartialOrd`, `Ord`) for callback types.
65///
66/// Used internally by [`impl_callback!`] and [`impl_callback_simple!`].
67#[macro_export]
68macro_rules! impl_callback_traits {
69    ($callback_value:ident) => {
70        impl ::core::fmt::Display for $callback_value {
71            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
72                write!(f, "{:?}", self)
73            }
74        }
75
76        impl ::core::fmt::Debug for $callback_value {
77            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
78                let callback = stringify!($callback_value);
79                write!(f, "{} @ 0x{:x}", callback, self.cb as *const () as usize)
80            }
81        }
82
83        impl ::core::hash::Hash for $callback_value {
84            fn hash<H>(&self, state: &mut H)
85            where
86                H: ::core::hash::Hasher,
87            {
88                state.write_usize(self.cb as *const () as usize);
89            }
90        }
91
92        impl PartialEq for $callback_value {
93            fn eq(&self, rhs: &Self) -> bool {
94                self.cb as *const () as usize == rhs.cb as usize
95            }
96        }
97
98        impl PartialOrd for $callback_value {
99            fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
100                Some((self.cb as *const () as usize).cmp(&(other.cb as *const () as usize)))
101            }
102        }
103
104        impl Ord for $callback_value {
105            fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
106                (self.cb as *const () as usize).cmp(&(other.cb as *const () as usize))
107            }
108        }
109
110        impl Eq for $callback_value {}
111    };
112}
113
114/// Implements `Display, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord`
115/// for a callback struct with `.cb` (function pointer) and `.ctx` (`OptionRefAny`) fields.
116///
117/// Also implements `From<$callback_ty>` to create a callback from a raw function pointer.
118///
119/// For callbacks with only a `.cb` field (no `.ctx`), use [`impl_callback_simple!`] instead.
120///
121/// This is necessary to work around for <https://github.com/rust-lang/rust/issues/54508>
122#[macro_export]
123macro_rules! impl_callback {
124    // Version with callable field (for UI callbacks that need FFI support)
125    ($callback_value:ident, $callback_ty:ty) => {
126        $crate::impl_callback_traits!($callback_value);
127
128        impl Clone for $callback_value {
129            fn clone(&self) -> Self {
130                $callback_value {
131                    cb: self.cb.clone(),
132                    ctx: self.ctx.clone(),
133                }
134            }
135        }
136
137        /// Allow creating callback from a raw function pointer
138        /// Sets callable to None (for native Rust/C usage)
139        impl From<$callback_ty> for $callback_value {
140            fn from(cb: $callback_ty) -> Self {
141                $callback_value {
142                    cb,
143                    ctx: $crate::refany::OptionRefAny::None,
144                }
145            }
146        }
147    };
148}
149
150/// Macro to implement callback traits for simple system callbacks (no callable field)
151///
152/// Use this for destructor callbacks, system callbacks, and other internal callbacks
153/// that don't need FFI callable support.
154#[macro_export]
155macro_rules! impl_callback_simple {
156    ($callback_value:ident) => {
157        $crate::impl_callback_traits!($callback_value);
158
159        // the macro impls Clone for an externally-defined type, so #[derive(Clone)]
160        // isn't available here; the explicit `*self` impl is required.
161        #[allow(clippy::expl_impl_clone_on_copy)]
162        impl Clone for $callback_value {
163            fn clone(&self) -> Self { *self }
164        }
165
166        impl Copy for $callback_value {}
167    };
168}