Skip to content

Commit 0a8e401

Browse files
committed
Add debug_assert_matches macro.
1 parent cfce60e commit 0a8e401

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

library/core/src/macros/mod.rs

+34
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,40 @@ macro_rules! debug_assert_ne {
260260
($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
261261
}
262262

263+
/// Asserts that an expression matches any of the given patterns.
264+
///
265+
/// Like in a `match` expression, the pattern can be optionally followed by `if`
266+
/// and a guard expression that has access to names bound by the pattern.
267+
///
268+
/// On panic, this macro will print the value of the expression with its
269+
/// debug representation.
270+
///
271+
/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
272+
/// enabled in non optimized builds by default. An optimized build will not
273+
/// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
274+
/// passed to the compiler. This makes `debug_assert_matches!` useful for
275+
/// checks that are too expensive to be present in a release build but may be
276+
/// helpful during development. The result of expanding `debug_assert_matches!`
277+
/// is always type checked.
278+
///
279+
/// # Examples
280+
///
281+
/// ```
282+
/// let a = 1u32.checked_add(2);
283+
/// let b = 1u32.checked_sub(2);
284+
/// debug_assert_matches!(a, Some(_));
285+
/// debug_assert_matches!(b, None);
286+
///
287+
/// let c = Ok("abc".to_string());
288+
/// debug_assert_matches!(a, Ok(x) | Err(x) if x.len() < 100);
289+
/// ```
290+
#[macro_export]
291+
#[unstable(feature = "assert_matches", issue = "none")]
292+
#[allow_internal_unstable(assert_matches)]
293+
macro_rules! debug_assert_matches {
294+
($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_matches!($($arg)*); })
295+
}
296+
263297
/// Returns whether the given expression matches any of the given patterns.
264298
///
265299
/// Like in a `match` expression, the pattern can be optionally followed by `if`

library/std/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -551,8 +551,8 @@ pub use std_detect::detect;
551551
#[stable(feature = "rust1", since = "1.0.0")]
552552
#[allow(deprecated, deprecated_in_future)]
553553
pub use core::{
554-
assert_eq, assert_matches, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, matches,
555-
r#try, todo, unimplemented, unreachable, write, writeln,
554+
assert_eq, assert_matches, assert_ne, debug_assert, debug_assert_eq, debug_assert_matches,
555+
debug_assert_ne, matches, r#try, todo, unimplemented, unreachable, write, writeln,
556556
};
557557

558558
// Re-export built-in macros defined through libcore.

0 commit comments

Comments
 (0)