Guest User

Untitled

a guest
Feb 19th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. // I was really annoyed that I couldn't easily assert that a
  2. // straightforward enum was being matched. I'm sure there's a better
  3. // way to do this but, hey, this is my first Rust macro.
  4.  
  5. macro_rules! assert_is_enum {
  6. ($left:expr, $right:path) => ({
  7. match &$left {
  8. left_val =>
  9. if let $right = *left_val { }
  10. else {
  11. panic!(r#"assertion failed: `(left == right)`
  12. left: `{:?}`,
  13. right: `{:?}`"#, $left, $right)
  14. }
  15. }
  16. });
  17. ($left:expr, $right:path, $($arg:tt)+) => ({
  18. match &$left {
  19. left_val =>
  20. if let $right = *left_val { }
  21. else {
  22. panic!(r#"assertion failed: `(left == right)`
  23. left: `{:?}`,
  24. right: `{:?}`: {}"#, $left, $right,
  25. format_args!($($arg)+))
  26. }
  27. }
  28. });
  29. }
  30.  
  31.  
  32. macro_rules! assert_is_not_enum {
  33. ($left:expr, $right:path) => ({
  34. match &$left {
  35. left_val =>
  36. if let $right = *left_val {
  37. panic!(r#"assertion failed: `(left == right)`
  38. left: `{:?}`,
  39. right: `{:?}`"#, $left, $right)
  40. }
  41. else { }
  42. }
  43. });
  44. ($left:expr, $right:path, $($arg:tt)+) => ({
  45. match &$left {
  46. left_val =>
  47. if let $right = *left_val {
  48. panic!(r#"assertion failed: `(left == right)`
  49. left: `{:?}`,
  50. right: `{:?}`: {}"#, $left, $right,
  51. format_args!($($arg)+))
  52. }
  53. else { }
  54. }
  55. });
  56. }
  57.  
  58. #[cfg(test)]
  59. mod tests {
  60.  
  61. #[derive(Debug)]
  62. pub enum Demo {
  63. This,
  64. Test
  65. }
  66.  
  67. use self::Demo::*;
  68.  
  69. #[test]
  70. pub fn test() {
  71. let x: Demo = This;
  72. assert_is_enum!(x, This);
  73. assert_is_not_enum!(x, Test);
  74. }
  75. }
Add Comment
Please, Sign In to add comment