rhai/src/reify.rs

50 lines
1.7 KiB
Rust
Raw Normal View History

2022-02-10 01:31:41 +01:00
/// Macro to cast an identifier or expression to another type with type checks.
2022-02-06 16:02:59 +01:00
///
2022-02-10 01:31:41 +01:00
/// Runs _code_ if _variable_ or _expression_ is of type _type_, otherwise run _fallback_.
///
/// # Syntax
///
/// * `reify!(`_variable_ or _expression_`,|`_temp-variable_`: `_type_`|` _code_`,` `||` _fallback_ `)`
/// * `reify!(`_variable_ or _expression_`,|`_temp-variable_`: `_type_`|` _code_ `)`
/// * `reify!(`_variable_ or _expression_ `=>` `Option<`_type_`>` `)`
/// * `reify!(`_variable_ or _expression_ `=>` _type_ `)`
#[macro_export]
macro_rules! reify {
($old:ident, |$new:ident : $t:ty| $code:expr, || $fallback:expr) => {{
2022-08-27 10:26:41 +02:00
#[allow(clippy::redundant_else)]
2022-02-07 05:02:00 +01:00
if std::any::TypeId::of::<$t>() == std::any::Any::type_id(&$old) {
2022-02-10 01:31:41 +01:00
// SAFETY: This is safe because we already checked to make sure the two types
// are actually the same.
2022-02-06 16:02:59 +01:00
let $new: $t = unsafe { std::mem::transmute_copy(&std::mem::ManuallyDrop::new($old)) };
$code
} else {
$fallback
}
}};
($old:expr, |$new:ident : $t:ty| $code:expr, || $fallback:expr) => {{
let old = $old;
2022-02-06 16:02:59 +01:00
reify!(old, |$new: $t| $code, || $fallback)
}};
2022-02-10 01:31:41 +01:00
($old:ident, |$new:ident : $t:ty| $code:expr) => {
2022-02-06 16:02:59 +01:00
reify!($old, |$new: $t| $code, || ())
};
($old:expr, |$new:ident : $t:ty| $code:expr) => {
2022-02-06 16:02:59 +01:00
reify!($old, |$new: $t| $code, || ())
};
2022-02-08 02:25:53 +01:00
($old:ident => Option<$t:ty>) => {
reify!($old, |v: $t| Some(v), || None)
};
($old:expr => Option<$t:ty>) => {
reify!($old, |v: $t| Some(v), || None)
};
($old:ident => $t:ty) => {
reify!($old, |v: $t| v, || unreachable!())
};
($old:expr => $t:ty) => {
reify!($old, |v: $t| v, || unreachable!())
};
}