Created
February 6, 2018 22:27
-
-
Save elfsternberg/11b0eeb39b3ac79f29030891f3a1e1c5 to your computer and use it in GitHub Desktop.
A pair of Rust macros to assert if a value matches a simple enum (no ADT support).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I was really annoyed that I couldn't easily assert that a | |
// straightforward enum was being matched. I'm sure there's a better | |
// way to do this but, hey, this is my first Rust macro. | |
macro_rules! assert_is_enum { | |
($left:expr, $right:path) => ({ | |
match &$left { | |
left_val => | |
if let $right = *left_val { } | |
else { | |
panic!(r#"assertion failed: `(left == right)` | |
left: `{:?}`, | |
right: `{:?}`"#, $left, $right) | |
} | |
} | |
}); | |
($left:expr, $right:path, $($arg:tt)+) => ({ | |
match &$left { | |
left_val => | |
if let $right = *left_val { } | |
else { | |
panic!(r#"assertion failed: `(left == right)` | |
left: `{:?}`, | |
right: `{:?}`: {}"#, $left, $right, | |
format_args!($($arg)+)) | |
} | |
} | |
}); | |
} | |
macro_rules! assert_is_not_enum { | |
($left:expr, $right:path) => ({ | |
match &$left { | |
left_val => | |
if let $right = *left_val { | |
panic!(r#"assertion failed: `(left == right)` | |
left: `{:?}`, | |
right: `{:?}`"#, $left, $right) | |
} | |
else { } | |
} | |
}); | |
($left:expr, $right:path, $($arg:tt)+) => ({ | |
match &$left { | |
left_val => | |
if let $right = *left_val { | |
panic!(r#"assertion failed: `(left == right)` | |
left: `{:?}`, | |
right: `{:?}`: {}"#, $left, $right, | |
format_args!($($arg)+)) | |
} | |
else { } | |
} | |
}); | |
} | |
#[cfg(test)] | |
mod tests { | |
#[derive(Debug)] | |
pub enum Demo { | |
This, | |
Test | |
} | |
use self::Demo::*; | |
#[test] | |
pub fn test() { | |
let x: Demo = This; | |
assert_is_enum!(x, This); | |
assert_is_not_enum!(x, Test); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment