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
|
|
|
|
///
|
2022-12-09 09:41:01 +01:00
|
|
|
/// * `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_ `)`
|
2022-02-06 01:29:05 +01:00
|
|
|
macro_rules! reify {
|
2022-12-09 09:41:01 +01:00
|
|
|
($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)) };
|
2022-02-06 01:29:05 +01:00
|
|
|
$code
|
|
|
|
} else {
|
|
|
|
$fallback
|
|
|
|
}
|
|
|
|
}};
|
2022-12-09 09:41:01 +01:00
|
|
|
($old:expr => |$new:ident : $t:ty| $code:expr, || $fallback:expr) => {{
|
2022-02-06 01:29:05 +01:00
|
|
|
let old = $old;
|
2022-12-09 09:41:01 +01:00
|
|
|
reify! { old => |$new: $t| $code, || $fallback }
|
2022-02-06 01:29:05 +01:00
|
|
|
}};
|
2022-02-10 01:31:41 +01:00
|
|
|
|
2022-12-09 09:41:01 +01:00
|
|
|
($old:ident => |$new:ident : $t:ty| $code:expr) => {
|
|
|
|
reify! { $old => |$new: $t| $code, || () }
|
2022-02-06 01:29:05 +01:00
|
|
|
};
|
2022-12-09 09:41:01 +01:00
|
|
|
($old:expr => |$new:ident : $t:ty| $code:expr) => {
|
|
|
|
reify! { $old => |$new: $t| $code, || () }
|
2022-02-06 01:29:05 +01:00
|
|
|
};
|
2022-02-08 02:25:53 +01:00
|
|
|
|
|
|
|
($old:ident => Option<$t:ty>) => {
|
2022-12-09 09:41:01 +01:00
|
|
|
reify! { $old => |v: $t| Some(v), || None }
|
2022-02-08 02:25:53 +01:00
|
|
|
};
|
|
|
|
($old:expr => Option<$t:ty>) => {
|
2022-12-09 09:41:01 +01:00
|
|
|
reify! { $old => |v: $t| Some(v), || None }
|
2022-02-08 02:25:53 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
($old:ident => $t:ty) => {
|
2022-12-09 09:41:01 +01:00
|
|
|
reify! { $old => |v: $t| v, || unreachable!() }
|
2022-02-08 02:25:53 +01:00
|
|
|
};
|
|
|
|
($old:expr => $t:ty) => {
|
2022-12-09 09:41:01 +01:00
|
|
|
reify! { $old => |v: $t| v, || unreachable!() }
|
2022-02-08 02:25:53 +01:00
|
|
|
};
|
2022-02-06 01:29:05 +01:00
|
|
|
}
|